<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.tzbh" placeholder="图纸名称" clearable>
                <el-option
                  v-for="item in kwOptions"
                  :key="item.bm"
                  :value="item.bm"
                  :label="item.bmsm"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
          </el-col>
          <el-col :span="16" 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"
              :align="'center'"
              :columns="tableColumn"
              :data="list"
              :custom-config="{ storage: true }"
              :edit-rules="validRules"
              :edit-config="{
                trigger: 'click',
                mode: 'row',
                showStatus: true,
              }"
              :span-method="rowspanMethod"
              :scroll-y="{enabled: false}"
              highlight-hover-row
              @checkbox-all="selectAllEvent"
              @checkbox-change="selectChangeEvent"

            >
<!--              @cell-dblclick="cellClickEvent_xb"-->
            </vxe-grid>
          </div>
        </el-main>
      </el-container>
      <!-- 弹出层——展示产能-->
      <vxe-modal v-model="dialogVisible1" width="80%" :title="title1">
        <template #default>
          <el-row class="query_wrapper">
            <el-row>
              <el-button size="small" style="float: right;margin-bottom: 5px;margin-right: 5px;" type="success"
                         @click="save">保存
              </el-button>
            </el-row>
          </el-row>
          <div class="mytable">
            <vxe-grid
              id="id6"
              ref="tableRef1"
              border
              resizable
              keep-source
              :align="'center'"
              :height="height"
              :auto-resize="true"
              :columns="tableColumn1"
              highlight-current-row
              :data="mxList"
              :custom-config="{ storage: true }"
              :edit-config="{
                                     trigger: 'click',
                                     mode: 'row',
                                     showStatus: true,
                                   }"
              @checkbox-all="selectAllEvent1"
              @checkbox-change="selectChangeEvent1"
              :cell-style="cellStyle"
              highlight-hover-row
              show-overflow
            >
            </vxe-grid>
          </div>
        </template>
      </vxe-modal>
    </el-container>
  </el-container>
</template>

<script>
import {
  getList,
  emSbjbbZM,
  getBMMCBM,
  save,
  update,
  delete1,
} from "@/api/sjzx/sbcnWH";
import { getList as getSbList}from "@/api/sjzx/sbxxWH";
export default {
  name: "sbcnWH1",
  data() {
    return {
      request: {
        tzbh: "",
        sbmc: "",
      },
      dialogVisible1: false,
      title1: '选择加工设备',
      mxList: [],
      sbList:[],
      sbbh:"",
      list: [],
      height: "500px",
      tableColumn: [
        { type: "checkbox", width: "50", align: "center" },
        { type: "seq", width: "50", title: "序号", align: "center" },
        { field: 'zyq', title: '作业区', width: 120,formatter:['dictFormat','BMBM'],
          editRender: {
            name: "$select",
            options: [],
            props: { clearable: true },
          },
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'tzbh', title: '套料图名称', width: 120,formatter:['dictFormat','QGKW'],
          editRender: {
            name: "$select",
            options: [],
            props: { clearable: true },
          },
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'zl', title: '组立', width: 120,formatter:['dictFormat','ZLLB'],
          editRender: {
            name: "$select",
            options: [],
            props: { clearable: true },
          },
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },

        { field: 'jgsx', title: '加工顺序', width: 120,editRender: { name: "$input",props: { clearable: true },},
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'gx', title: '工序', width: 160,formatter:['dictFormat','PCGX'],
          editRender: {
            name: "$select",
            options: [],
            props: { clearable: true },
          },
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        // {
        //   field: "sbbh",
        //   title: "设备编号",
        //   width: 120,
        //   // editRender: { name: "$input",props: { clearable: true },},
        //   filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
        //   filterRender: { name: 'FilterCombination', },
        // },
        { field: 'kw', title: '加工跨', width: 120,formatter:['dictFormat','CNKW'],
          editRender: {
            name: "$select",
            options: [],
            props: { clearable: true },
          },
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'bjry', title: '编辑人员', width: 120,
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'bjrq', title: '编辑日期', width: 120,
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        }
  ],
      tableColumn1:[
        { type: "checkbox", width: "50", align: "center", fixed: "left" },
        {
          type: "seq",
          width: "50",
          title: "序号",
          align: "center",
          fixed: "left",
        },
        {
          field: "szcs",
          title: "所属部门",
          align: "center",
          minWidth: "110",
          formatter:['dictFormat','BMBM'],
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        {
          field: "sbbh",
          title: "设备编号",
          align: "center",
          minWidth: "120",
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        {
          field: "sbmc",
          title: "设备名称",
          align: "center",
          minWidth: "110",
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        {
          field: "sbxh",
          title: "设备型号",
          align: "center",
          minWidth: "110",
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },

        { field: 'gx', title: '工序', width: 100,formatter:['dictFormat','PCGX'],
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'degs', title: '定额工时(小时)', width: 130,
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'degsYb', title: '定额工时(夜班)', width: 130,
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'sdgs', title: '实动工时(小时)', width: 130,
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'cndw', title: '计量单位', width: 110,formatter:['dictFormat','JLDW'],

          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        {
          field: "sbyxzt",
          title: "设备状态",
          align: "center",
          minWidth: "110",
          formatter:this.formatterSbzt,
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        {
          field: "whsj1",
          title: "维护开始时间",
          align: "center",
          minWidth: "150",
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        {
          field: "whsj2",
          title: "维护结束时间",
          align: "center",
          minWidth: "150",
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        {
          field: "xqrs",
          title: "默认人数",
          align: "center",
          minWidth: "110",
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },

      ],
      validRules: {
        // sbbh: [{ required: true, message: "设备编号不可为空" }],
      },
      kwOptions: [],
      zlOptions: [
        {
          label: '小组立',
          value: 1010,
        },
        {
          label: '中大组立',
          value: 1110,
        },
        {
          label: '光电',
          value: 1120,
        },
        {
          label: '焊接机器人肘板',
          value: 4230,
        },
      ],
      departmentOptions: [],
      options: [],
      sbmcOptions: [],
      checkedList: [],
      checkedList1: [],
      cnIndex:0,

    };
  },
  created() {
    window.addEventListener("resize", this.getHeight);
    this.getHeight();
    this.getBMMCBM();
    this.initList();
    this.initgxList();
    this.emSbjbbZM("QGKW");
    this.emSbjbbZM("bmbm");
    this.initkwList();
    this.initSb();
  },
  methods: {
    formatterSbzt({ cellValue }){
      if (cellValue === '0') {
        return '正常'
      } else if (cellValue === '1') {
        return '维护'
      }
      return ''
    },
    initSb(){
      getSbList(this.request).then((res) => {
        this.sbList = res.data;
      });
    },
    //修改设备信息；根据修改后的设备信息；重新排计划期
    save() {
      if (this.checkedList1.length>1 ||this.checkedList1.length==0){
        this.$message.warning('请选择一个设备！');
      }else {
       this.list[this.cnIndex].sbbh=this.checkedList1[0].sbbh
        this.dialogVisible1 = false;
      }
    },
    //设备信息弹窗
    cellClickEvent_xb(row) {
      var gx= row.row.gx;
      this. sbbh= row.row.sbbh;
      this.cnIndex=row.rowIndex;
      //设备list 找到工序下的设备
      this.mxList = this.sbList.filter((item, index) => {
        if ( item.gx == gx){
          return item;
        }
      });
      this.dialogVisible1 = true
    },
    // 工序 xn20231110
    initgxList(){
      const dict=window.localStorage.getItem( 'PCGX');
      const gxList =JSON.parse(dict)
        this.$nextTick(() => {
          const tableRef = this.$refs.tableRef;
          const gx = tableRef.getColumnByField("gx");
          const zl = tableRef.getColumnByField("zl");
          const testList = [];
          for (let i = 0; i < gxList.length; i++) {
            const temp = {
              label: gxList[i].bmsm,
              value: gxList[i].bm,
            };
            testList.push(temp);
          }
          gx.editRender.options = testList;
          zl.editRender.options = this.zlOptions;
        });

    },
    initkwList(){
      const dict=window.localStorage.getItem( 'CNKW');
      const kwList =JSON.parse(dict)
      this.$nextTick(() => {
        const tableRef = this.$refs.tableRef;
        const kw = tableRef.getColumnByField("kw");
        const testList = [];
        for (let i = 0; i < kwList.length; i++) {
          const temp = {
            label: kwList[i].bmsm,
            value: kwList[i].bm,
          };
          testList.push(temp);
        }
        kw.editRender.options = testList;
      });

    },
    // 部门对应设备名称和编号
    getBMMCBM() {
      getBMMCBM().then((res) => {
        if (res.success) {
          this.options = res.data;
        }
      });
    },
    // 获取列表接口
    initList() {
      getList(this.request).then((res) => {
        this.list = res.data;
        this.checkedList = [];
        if (this.list.length > 0) {
          this.list.forEach((item) => {
            item.sbmcDisabled = true;
          });
        }
      });
    },
    // 设备信息转码接口
    emSbjbbZM(params) {
      emSbjbbZM({
        bmlb: params,
      }).then((res) => {
        const tableRef = this.$refs.tableRef;
        if (params == "bmbm") {
          const zyq=this.$refs.tableRef.getColumnByField('zyq');
          const list=[]
          res.data.forEach(item=>{
            const data={label:item.bmsm,value:item.bm}
            list.push(data)
          })
          zyq.editRender.options = list
          // 所属部门
          // 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;
          // });
        } else if (params == "QGKW") {
          // 跨位
          this.kwOptions = res.data;
          const sbztText = tableRef.getColumnByField("tzbh");
          const testList = [];
          for (let i = 0; i < this.kwOptions.length; i++) {
            const temp = {
              label: this.kwOptions[i].bmsm,
              value: this.kwOptions[i].bm,
            };
            testList.push(temp);
          }
          sbztText.editRender.options = testList;
        }
      });
    },
    cellStyle({row}) {
      if (row.sbbh==this.sbbh) {
        return {
          color: 'blue',
          cursor: 'pointer'
        }
      }
    },
    // 全选
    selectAllEvent() {
      const records = this.$refs.tableRef.getCheckboxRecords();
      this.checkedList = records;
    },
    // 单选
    selectChangeEvent() {
      const records = this.$refs.tableRef.getCheckboxRecords();
      this.checkedList = records;
    },
    // 全选
    selectAllEvent1() {
      const records = this.$refs.tableRef1.getCheckboxRecords();
      this.checkedList1 = records;
    },
    // 单选
    selectChangeEvent1() {
      const records = this.$refs.tableRef1.getCheckboxRecords();
      this.checkedList1 = 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].tzbh === undefined || insertRecords[i].tzbh === "" || insertRecords[i].tzbh === null){
                    flag = true;
                    break;
                  }
                  if(insertRecords[i].zl === undefined || insertRecords[i].zl === "" || insertRecords[i].zl === null){
                    flag = true;
                    break;
                  }
                  if(insertRecords[i].jgsx === undefined || insertRecords[i].jgsx === "" || insertRecords[i].jgsx === null){
                    flag = true;
                    break;
                  }
                  if(insertRecords[i].gx === undefined || insertRecords[i].gx === "" || insertRecords[i].gx === null){
                    flag = true;
                    break;
                  }

                }
                if(flag){
                  this.$message.error({message:"新增内容未达到可保存标准，请把必要信息空白补全。"})
                }else{
                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",
                    });
                  }
                });
                }
              }
              //  修改
              if (updateRecords.length !== 0) {
                for(let i = 0; i < insertRecords.length; i++){
                  if(insertRecords[i].tzbh === undefined || insertRecords[i].tzbh === "" || insertRecords[i].tzbh === null){
                    flag = true;
                    break;
                  }
                  if(insertRecords[i].zl === undefined || insertRecords[i].zl === "" || insertRecords[i].zl === null){
                    flag = true;
                    break;
                  }
                  if(insertRecords[i].jgsx === undefined || insertRecords[i].jgsx === "" || insertRecords[i].jgsx === null){
                    flag = true;
                    break;
                  }
                  if(insertRecords[i].gx === undefined || insertRecords[i].gx === "" || insertRecords[i].gx === null){
                    flag = true;
                    break;
                  }
                  if(insertRecords[i].jldw === undefined || insertRecords[i].jldw === "" || insertRecords[i].jldw === null){
                    flag = true;
                    break;
                  }
                  if(insertRecords[i].degs === undefined || insertRecords[i].degs === "" || insertRecords[i].degs === null){
                    flag = true;
                    break;
                  }
                }
                if(flag){
                  this.$message.error({message:"保存内容未达到可保存标准，请把必要信息空白补全。"})
                }else{
                  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;
      }
    },
    //合并行
    rowspanMethod({row, _rowIndex, column, visibleData}) {
      //不要忘记在vxe-grid上配置  :scroll-y="{enabled: false}" 防止下拉时样式变化
      // 需要合并的列字段
      let fields = ['zyq','tzbh'];// 需要合并的列
      const cellValue = row[column.property];// 合并行的相同的唯一标识
      if (cellValue && fields.includes(column.property)) {
        const prevRow = visibleData[_rowIndex - 1];
        let nextRow = visibleData[_rowIndex + 1];
        if (prevRow && prevRow[column.property] === cellValue) {
          // 如果和第一行数据一样，就删除
          return {rowspan: 0, colspan: 0};
        } else {
          // 获取有机会数据是一样的
          let countRowspan = 1;
          while (nextRow && nextRow[column.property] === cellValue) {
            nextRow = visibleData[++countRowspan + _rowIndex];
          }
          if (countRowspan > 1) {
            return {rowspan: countRowspan, colspan: 1};
          }
        }
      }
    },
    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>
