<template>
  <!-- 设备加工人员维护 -->
  <el-container>
    <el-header style="width: 100%">
      <el-form ref="requestForm" :model="request" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="工序名称:">
              <el-select v-model="request.gx" placeholder="工序名称" clearable>
                <el-option
                  v-for="item in gxList"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
          </el-col>
          <el-col :span="16" style="text-align: right">
            <el-button type="primary" @click="initList()">查询</el-button>
            <el-button type="success" @click="toolbarButtonClickEvent('insert')">添加</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"
              :align="'center'"
              :columns="tableColumn"
              :data="list"
              :custom-config="{ storage: true }"
              :edit-config="{
                trigger: 'click',
                mode: 'row',
                showStatus: true,
              }"
              :scroll-y="{enabled: false}"
              highlight-hover-row
              @checkbox-all="selectAllEvent"
              @checkbox-change="selectChangeEvent"
            >
              <template #sbbh_edit="{ row }">
                <vxe-input
                  v-model="row.sbbh"
                  disabled
                  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 {
  getSbjgrys,
  saveJgry,
  updateJgry,
  deleteJgry
} from "@/api/sjzx/sbryWH";
import {emSbjbbZM, getBMMCBM} from "@/api/sjzx/sbwxjhWH";
import {getGxDict} from "@/api/jhzx/pc";
export default {
  name: "SbjgryWH",
  data() {
    return {
      request: {
        gx: "",
      },
      gxList:[],
      list: [],
      height: "500px",
      tableColumn: [
        { type: "checkbox", width: "50", align: "center" },
        { type: "seq", width: "50", title: "序号", align: "center" },
        { field: 'dlzh', title: '登录账户', width: 160,editRender: { name: "$input"},
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'employeeNumber', title: '职号', width: 160,editRender: { name: "$input"},
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'gx', title: '工序', width: 160,
          editRender: {
            name: "$select",
            options: [],
            props: { clearable: true },
          },
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'xjsjKs', title: '休假开始时间', width: 160,
          editRender: { name: "$input",
            props: { type: 'date',labelFormat:"yyyy/MM/dd",valueFormat:"yyyy/MM/dd"}
          },
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'xjsjJs', title: '休假结束时间', width: 160,
          editRender: { name: "$input",
            props: { type: 'date',labelFormat:"yyyy/MM/dd",valueFormat:"yyyy/MM/dd"}
          },
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        {
          field: "szcs",
          title: "所属部门",
          align: "center",
          minWidth: "110",
          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",
          minWidth: "110",
          editRender: {
            name: "$select",
            options: [],
            props: {
              clearable: true,
            },
          },
          slots: { edit: "sbmc_edit" },
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        {
          field: "sbbh",
          title: "设备编号",
          align: "center",
          minWidth: "130",
          editRender: { name: "input" },
          slots: { edit: "sbbh_edit" },
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        { field: 'zt', title: '状态', width: 160,formatter:['dictFormat','YGZT'],
          editRender: {
            name: "$select",
            options: [],
            props: { clearable: true },
          },
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'gz', title: '工种', width: 160,formatter:['dictFormat','RYGX'],
          editRender: {
            name: "$select",
            options: [],
            props: { clearable: true },
          },
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
  ],
      departmentOptions: [],
      options: [],
      sbmcOptions: [],
      checkedList: [],
    };
  },
  created() {
    window.addEventListener("resize", this.getHeight);

    this.getHeight();
    this.initList();
    this.initgxList();
    this.getBMMCBM();
    this.emSbjbbZM("bmbm");
    this.getGxList();

  },
  methods: {
    // 部门对应设备名称和编号
    getBMMCBM() {
      getBMMCBM().then((res) => {
        if (res.success) {
          this.options = res.data;
        }
      });
    },
    getGxList(){
      getGxDict().then((res)=>{
        res.data.forEach(item=>{
          // this.gxList.push({label:item.name,value:item.code})
          this.gxList.push({label:item.name,value:item.name})
        })
        const tableRef = this.$refs.tableRef
        const gx = tableRef.getColumnByField('gx')
        gx.editRender.options = this.gxList
      })
    },
    // 设备信息转码接口
    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;
          });
        }
      });
    },
    initgxList(){
      const ztDict=window.localStorage.getItem( 'YGZT');
      const gzDict=window.localStorage.getItem( 'RYGX');
      const ztList =JSON.parse(ztDict)
      const gzList =JSON.parse(gzDict)
        this.$nextTick(() => {
          const tableRef = this.$refs.tableRef;
          const zt = tableRef.getColumnByField("zt");
          const gz = tableRef.getColumnByField("gz");
          const ztList1 = [];
          const gzList1 = [];
          for (let i = 0; i < ztList.length; i++) {
            const temp = {
              label: ztList[i].bmsm,
              value: ztList[i].bm,
            };
            ztList1.push(temp);
          }
          for (let i = 0; i < gzList.length; i++) {
            const temp = {
              label: gzList[i].bmsm,
              value: gzList[i].bm,
            };
            gzList1.push(temp);
          }
          zt.editRender.options = ztList1;
          gz.editRender.options = gzList1;
        });

    },
    // 获取列表接口
    initList() {
      getSbjgrys(this.request).then((res) => {
        this.list = res.data;
        this.checkedList = [];
      });
    },
    // 监听选择所属部门
    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({ sbmcDisabled: true }, -1);
          break;
        case "delete":
          if (this.checkedList.length > 0) {
            this.$refs.tableRef.removeCheckboxRow();
          } else {
            this.$message.warning("请选择数据！");
          }
          break;
        case "save":
          const valid = this.$refs.tableRef;
          let flag = false;
          if (valid) {
            const errMap = await valid.validate(true);
            if (errMap) {
              return false;
            } else {
              // 新增
              if (insertRecords.length !== 0) {
                for(let i = 0; i < insertRecords.length; i++){
                  if(insertRecords[i].dlzh === undefined || insertRecords[i].dlzh === "" || insertRecords[i].dlzh === null){
                    flag = true;
                    break;
                  }
                  if(insertRecords[i].employeeNumber === undefined || insertRecords[i].employeeNumber === "" || insertRecords[i].employeeNumber === null){
                    flag = true;
                    break;
                  }
                  if(insertRecords[i].gx === undefined || insertRecords[i].gx === "" || insertRecords[i].gx === null){
                    flag = true;
                    break;
                  }
                  if(insertRecords[i].zt === undefined || insertRecords[i].zt === "" || insertRecords[i].zt === null){
                    flag = true;
                    break;
                  }
                }
                if(flag){
                  this.$message.error({message:"新增内容未达到可保存标准，请把必要信息空白补全。"})
                }else{
                saveJgry(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",
                    });
                  }
                });
                }
              }
              //  修改
              if (updateRecords.length !== 0) {
                for(let i = 0; i < insertRecords.length; i++){
                  if(insertRecords[i].dlzh === undefined || insertRecords[i].dlzh === "" || insertRecords[i].dlzh === null){
                    flag = true;
                    break;
                  }
                  if(insertRecords[i].employeeNumber === undefined || insertRecords[i].employeeNumber === "" || insertRecords[i].employeeNumber === null){
                    flag = true;
                    break;
                  }
                  if(insertRecords[i].gx === undefined || insertRecords[i].gx === "" || insertRecords[i].gx === null){
                    flag = true;
                    break;
                  }
                  if(insertRecords[i].zt === undefined || insertRecords[i].zt === "" || insertRecords[i].zt === null){
                    flag = true;
                    break;
                  }
                }
                if(flag){
                  this.$message.error({message:"保存内容未达到可保存标准，请把必要信息空白补全。"})
                }else{
                  updateJgry(updateRecords).then((res) => {
                    if (res.success) {
                      const xTable = this.$refs.tableRef;
                      xTable.loadData(this.initList());
                      this.$message({ message: "保存成功！", type: "success" });
                    }
                  });
                }

              }
            }
          }
          // 删除
          if (removeRecords.length !== 0) {
            deleteJgry(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" });
              }
            });
          }
          break;
      }
    },
    getHeight() {
      this.height = window.innerHeight - 230;
    },
  },
};
</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>
