<template>
  <!-- 设备人员信息维护 -->
  <el-container>
    <el-header style="width: 100%">
      <el-form ref="requestForm" :model="request" label-width="75px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="设备名称:">
              <el-input
                v-model="request.sbmc"
                placeholder="设备名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="20" style="text-align: right">
            <el-button type="success" @click="toolbarButtonClickEvent('insert')"
              >添加</el-button
            >
            <el-button type="primary" @click="initList()">查询</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right">
            <el-button type="danger" @click="toolbarButtonClickEvent('delete')"
              >删除</el-button
            >
            <el-button type="primary" @click="toolbarButtonClickEvent('save')"
              >保存</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </el-header>
    <el-container style="padding-top: 10px">
      <el-container>
        <el-main>
          <div class="mytable">
            <vxe-grid
              id="id"
              ref="tableRef"
              border
              resizable
              keep-source
              :height="height"
              :auto-resize="true"
              :columns="tableColumn"
              :data="list"
              :custom-config="{ storage: true }"
              :edit-rules="validRules"
              :edit-config="{
                trigger: 'click',
                mode: 'row',
                showStatus: true,
              }"
              highlight-hover-row
              @checkbox-all="selectAllEvent"
              @checkbox-change="selectChangeEvent"
            >
              <template #sbbh_edit="{ row }">
                <vxe-input
                  v-model="row.sbbh"
                  :disabled="row.sbbhDisabled"
                  placeholder=""
                ></vxe-input>
              </template>
              <template #sbmc_edit="{ row }">
                <vxe-select
                  v-model="row.sbmc"
                  :options="sbmcOptions"
                  :disabled="row.sbmcDisabled"
                  @change="changeSbmc($event, row)"
                  placeholder=""
                  clearable
                  transfer
                ></vxe-select>
              </template>
            </vxe-grid>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </el-container>
</template>

<script>
import {
  getRYList,
  emSbjbbZM,
  getBMMCBM,
  getList,
  save,
  update,
  delete1,
} from "@/api/sjzx/sbryWH";
export default {
  name: "sbryWH",
  data() {
    return {
      request: {
        sbmc: "",
      },
      list: [],
      height: "500px",
      tableColumn: [
        { type: "checkbox", width: "50", align: "center" },
        { type: "seq", width: "50", title: "序号", align: "center" },
        {
          field: "szcs",
          title: "所属部门",
          align: "center",
          editRender: {
            name: "$select",
            options: [],
            props: { clearable: true },
            events: {
              change: this.changeSzcs,
            },
          },
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        {
          field: "sbmc",
          title: "设备名称",
          align: "center",
          editRender: {
            name: "$select",
            options: [],
            props: {
              clearable: true,
            },
            events: {
              change: this.changeSbmc,
            },
          },
          slots: { edit: "sbmc_edit" },
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        {
          field: "sbbh",
          title: "设备编号",
          align: "center",
          editRender: { name: "input" },
          slots: { edit: "sbbh_edit" },
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        // {
        //   field: "rymc",
        //   title: "人员名称",
        //   align: "center",
        //   editRender: {
        //     name: "$select",
        //     options: [],
        //     props: { clearable: true }
        //   },
        //   filters: [
        //     {
        //       data: {
        //         checks: [],
        //         sVal: "",
        //         sMenu: "",
        //         fType1: "",
        //         fVal1: "",
        //         fMode: "and",
        //         fType2: "",
        //         fVal2: "",
        //       },
        //     },
        //   ],
        //   filterRender: { name: "FilterCombination" },
        // },
        {
          field: "jlr",
          title: "负责人",
          align: "center",
          editRender: { name: "input" },
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
      ],
      validRules: {
        sbbh: [{ required: true, message: "设备编号不可为空" }],
      },
      departmentOptions: [],
      options: [],
      sbmcOptions: [],
      checkedList: []
    };
  },
  created() {
    window.addEventListener("resize", this.getHeight);
    this.getHeight();
    this.getRYList();
    this.getBMMCBM();
    this.emSbjbbZM("bmbm");
    this.initList();
  },
  methods: {
    // 获取列表接口
    initList() {
      getList(this.request).then((res) => {
        this.list = res.data;
        this.checkedList = [];
        if (this.list.length > 0) {
          this.list.forEach((item) => {
            item.sbbhDisabled = true;
            item.sbmcDisabled = true;
          });
        }
      });
    },
    // 获取人员信息接口
    getRYList() {
      getRYList().then((res) => {
        this.personnelInfoList = res.data;
        const tableRef = this.$refs.tableRef;
        const personnelInfoText = tableRef.getColumnByField("rymc");
        const testList = [];
        for (let i = 0; i < this.personnelInfoList.length; i++) {
          const temp = {
            label: this.personnelInfoList[i].rymc,
            value: this.personnelInfoList[i].rymc,
          };
          testList.push(temp);
        }
        personnelInfoText.editRender.options = testList;
      });
    },
    // 部门对应设备名称和编号
    getBMMCBM() {
      getBMMCBM().then((res) => {
        if (res.success) {
          this.options = res.data;
        }
      });
    },
    // 设备信息转码接口
    emSbjbbZM(params) {
      emSbjbbZM({
        bmlb: params,
      }).then((res) => {
        const tableRef = this.$refs.tableRef;
        if (params == "bmbm") {
          // 所属部门
          this.departmentOptions = res.data;
          const sbztText = tableRef.getColumnByField("szcs");
          const testList = [];
          Object.keys(this.options).forEach((item) => {
            for (let i = 0; i < this.departmentOptions.length; i++) {
              if (item == this.departmentOptions[i].bm) {
                const temp = {
                  label: this.departmentOptions[i].bmsm,
                  value: this.departmentOptions[i].bm,
                };
                testList.push(temp);
              }
            }
            sbztText.editRender.options = testList;
          });
        }
      });
    },
    // 监听选择所属部门
    changeSzcs(row, id) {
      if (row.row.szcs) {
        row.row.sbmcDisabled = false;
        row.row.sbmc = "";
        row.row.sbbh = "";
        this.sbmcOptions = [];
        const testList = [];
        for (let i = 0; i < this.options[id.value].length; i++) {
          const temp = {
            label: this.options[id.value][i].sbmc,
            value: this.options[id.value][i].sbbh,
          };
          testList.push(temp);
        }
        this.sbmcOptions = testList;
      } else {
        row.row.sbmcDisabled = true;
        row.row.sbmc = "";
        row.row.sbbh = "";
        this.sbmcOptions = [];
      }
    },
    // 监听选择设备名称
    changeSbmc(event, row) {
      if (row.sbmc) {
        row.sbbh = event.value;
        let arr = this.sbmcOptions.filter((item, index) => {
          if (item.value == event.value) {
            return item;
          }
        });
        row.sbmc = arr[0].label;
      } else {
        row.sbbh = "";
      }
    },
    // 全选
    selectAllEvent() {
      const records = this.$refs.tableRef.getCheckboxRecords();
      this.checkedList = records;
    },
    // 单选
    selectChangeEvent() {
      const records = this.$refs.tableRef.getCheckboxRecords();
      this.checkedList = records;
    },
    // 操作
    async toolbarButtonClickEvent(code) {
      const { insertRecords, removeRecords, updateRecords } =
        this.$refs.tableRef.getRecordset();
      switch (code) {
        case "insert":
          this.$refs.tableRef.insertAt(
            {
              sbbhDisabled: true,
              sbmcDisabled: true,
            },
            -1
          );
          break;
        case "delete":
          if (this.checkedList.length > 0) {
            this.$confirm("是否确认删除选中的数据?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.$refs.tableRef.removeCheckboxRow();
              })
              .catch(() => {});
          } else {
            this.$message.warning("请选择数据！");
          }
          break;
        case "save":
          const valid = this.$refs.tableRef;
          if (valid) {
            const errMap = await valid.validate(true);
            if (errMap) {
              return false;
            } else {
              // 新增
              if (insertRecords.length !== 0) {
                this.$confirm("是否确认保存选中的数据?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                })
                  .then(() => {
                    save(insertRecords).then((res) => {
                      if (res.success) {
                        this.list = this.list.concat(insertRecords);
                        const xTable = this.$refs.tableRef;
                        xTable.loadData(this.initList());
                        this.$message({
                          message: "保存成功！",
                          type: "success",
                        });
                      }
                    });
                  })
                  .catch(() => {});
              }

              //  修改
              if (updateRecords.length !== 0) {
                update(updateRecords).then((res) => {
                  if (res.success) {
                    const xTable = this.$refs.tableRef;
                    xTable.loadData(this.initList());
                    this.$message({ message: "保存成功！", type: "success" });
                  }
                });
              }
            }
          }
          // 删除
          if (removeRecords.length !== 0) {
            delete1(removeRecords).then((res) => {
              if (res.success) {
                for (let i = 0; i < this.list.length; i++) {
                  if (removeRecords.indexOf(this.list[i]) !== -1) {
                    this.list.splice(i, 1);
                    i--;
                  }
                }
                const xTable = this.$refs.tableRef;
                xTable.loadData(this.initList());
                this.$message({ message: "保存成功！", type: "success" });
              }
            });
          }

          if (removeRecords.length !== 0) {
            this.$message(
              `新增 ${insertRecords.length} 条，删除 ${removeRecords.length} 条，更新 ${updateRecords.length} 条`
            );
          } else {
            const valid = this.$refs.tableRef;
            if (valid) {
              const errMap = await valid.validate(true);
              if (errMap) {
                return false;
              } else {
                this.$message(
                  `新增 ${insertRecords.length} 条，删除 ${removeRecords.length} 条，更新 ${updateRecords.length} 条`
                );
              }
            }
          }
          break;
      }
    },
    getHeight() {
      this.height = window.innerHeight - 160;
    },
  },
};
</script>
<style lang="scss" scoped>
.el-header {
  margin: 0;
  padding: 5px 0;
  height: auto;
}
.el-container {
  padding: 0;
  margin: 0;
}
.el-main {
  padding: 0;
}
.el-col {
  padding: 0;
}
.el-aside {
  background: #fff;
  padding: 0;
}
.el-container {
  padding: 0;
}
.el-row {
  margin-bottom: 5px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.tableStyles {
  background: #0a76a4;
}
.my-dropdown {
  width: 450px;
  height: 250px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
  font-size: 12px;
}
::v-deep .mytable .vxe-input {
  display: flex !important;
}
::v-deep .el-form-item {
  margin-bottom: 0px !important;
}
::v-deep .el-input {
  width: auto !important;
}
</style>
