<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.sbbh"
                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-button type="primary" @click="initList(2)">查询全部</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="所属部门:">
              <el-select v-model="request.szcs" placeholder="所属部门" clearable>
                <el-option
                  v-for="item in departmentOptions"
                  :key="item.bm"
                  :value="item.bm"
                  :label="item.bmsm"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
<!--            <el-form-item label="供应商:">-->
<!--              <el-select v-model="request.gysbm" placeholder="供应商" clearable>-->
<!--                <el-option-->
<!--                  v-for="item in supplierList"-->
<!--                  :key="item.ghsbm"-->
<!--                  :value="item.ghsbm"-->
<!--                  :label="item.ghsqc"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
          </el-col>
          <el-col :span="20" 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
              show-overflow
              :height="height"
              :auto-resize="true"
              :columns="tableColumn"
              :data="list"
              :custom-config="{ storage: true }"
              :scroll-y="{ enabled: true }"
              :edit-rules="validRules"
              :edit-config="{
                trigger: 'click',
                mode: 'row',
                showStatus: true,
              }"
              highlight-hover-row
              @checkbox-all="selectAllEvent"
              @checkbox-change="selectChangeEvent"
            >

            </vxe-grid>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </el-container>
</template>

<script>
import {
  getGYS,
  getSBLX,
  emSbjbbZM,
  getList,
  save,
  update,
  delete1,
} from "@/api/sjzx/sbxxWH";
import { mapGetters } from 'vuex';
export default {
  name: "sbxxWH1",
  data() {
    return {
      request: {
        sbbh: '',
        szcs: "",
        gysbm: "",
        scbs: "1",
      },
      supplierList: [], //供应商
      list: [],
      height: "500px",
      tableColumn: [
        { 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: "azwz",
          title: "安装位置",
          align: "center",
          minWidth: "110",
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        {
          field: "sbzt",
          title: "固定资产状态",
          align: "center",
          minWidth: "120",
          formatter:['dictFormat','SBZT'],
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        { field: 'scbs', title: '生产标识', width: 130,editRender: { name: "$input"},
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'gx', title: '工序', width: 100,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: 'kw', title: '跨位', width: 100,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: 'degs', title: '定额工时(小时)', width: 130,editRender: { name: "$input"},
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'degsYb', title: '定额工时(夜班)', width: 130,editRender: { name: "$input"},
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'sdgs', title: '实动工时(小时)', width: 130,editRender: { name: "$input"},
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        { field: 'cndw', title: '计量单位', width: 110,formatter:['dictFormat','JLDW'],
          editRender: {
            name: "$select",
            options: [],
            props: { clearable: true },
          },
          filters: [{ data: { checks: [], sVal: '', sMenu: '', fType1: '', fVal1: '', fMode: 'and', fType2: '', fVal2: '' } }],
          filterRender: { name: 'FilterCombination', },
        },
        {
          field: "sbyxzt",
          title: "设备状态",
          align: "center",
          editRender: {
            name: "$select",
            options: [],
            props: { clearable: true },
          },
          minWidth: "110",
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        {
          field: "whsj1",
          title: "维护开始时间",
          align: "center",
          editRender: {
            name: '$input',
            props:{type:"date" ,
              valueFormat:"yyyy/MM/dd",labelFormat:"yyyy/MM/dd",clearable: true,},
            events: {
              change: this.changeWhsj1
            },},
          formatter: this.whsj1,
          minWidth: "150",
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        {
          field: "whsj2",
          title: "维护结束时间",
          align: "center",
          editRender: { name:  '$input',
            props:{type:"date" ,valueFormat:"yyyy/MM/dd",labelFormat:"yyyy/MM/dd",clearable: true,},
            events: {
              change: this.changeWhsj2
            },
          },
          formatter: this.whsj2,
          minWidth: "150",
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },
        {
          field: "xqrs",
          title: "默认人数",
          align: "center",
          editRender: { name: "input" },
          minWidth: "110",
          filters: [
            {
              data: {
                checks: [],
                sVal: "",
                sMenu: "",
                fType1: "",
                fVal1: "",
                fMode: "and",
                fType2: "",
                fVal2: "",
              },
            },
          ],
          filterRender: { name: "FilterCombination" },
        },

      ],
      validRules: {
        sbbh: [{ required: true, message: "设备编号不可为空" }],
      },
      departmentOptions:[],
      checkedList: [],
      sbbhDisabled: true,
      zdDisabled: true,
      sbyxztList:[
        {label: '正常',
          value: '0'},
        {label: '维护',
          value: '1'}
      ],
    };
  },
  created() {
    window.addEventListener("resize", this.getHeight);
    this.getHeight();
    this.getGYS();
    this.getSBLX();
    this.emSbjbbZM("jldw");
    this.emSbjbbZM("sbzt");
    this.emSbjbbZM("sbyxzt");
    this.emSbjbbZM("bmbm");
    this.initList();
    this.initdwList();
    this.initkwList();
    this.initgzList();
  },
  computed: {
    ...mapGetters([
      'name'
    ]),
  },
  methods: {

    // 获取列表接口
    initList(p) {
      if (p==2){
        this.request.scbs=""
      }else {
        this.request.scbs="1"
      }


      getList(this.request).then((res) => {

        this.list = res.data;
        this.checkedList = [];
        if (this.list > 0) {
          this.list.forEach((item) => {
            item.sbbhDisabled = this.sbbhDisabled;
            item.zdDisabled = this.zdDisabled;
          });
        }
      });
    },
    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;
      });

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

    },
    initgzList(){
      const gxDict=window.localStorage.getItem( 'PCGX');
      const gxList =JSON.parse(gxDict)
      this.$nextTick(() => {
        const tableRef = this.$refs.tableRef;
        const gx = tableRef.getColumnByField("gx");
        const list3 = [];
        for (let i = 0; i < gxList.length; i++) {
          const temp = {
            label: gxList[i].bmsm,
            value: gxList[i].bm,
          };
          list3.push(temp);
        }
        gx.editRender.options = list3;
      });
    },
    //   获取供应商接口
    getGYS() {
      getGYS().then((res) => {
        this.supplierList = res.data;
        const tableRef = this.$refs.tableRef;
        const gysbmText = tableRef.getColumnByField("gysbm");
        const testList = [];
        for (let i = 0; i < this.supplierList.length; i++) {
          const temp = {
            label: this.supplierList[i].ghsqc,
            value: this.supplierList[i].ghsbm,
          };
          testList.push(temp);
        }
        // gysbmText.editRender.options = testList;
      });
    },
    formatterFl1({ cellValue }) {
      for (let i = 0; i < this.typeList.length; i++) {
        if (this.typeList[i].bmjb==='1' && this.typeList[i].bm===cellValue){
          return this.typeList[i].bmsm
        }
      }
      return cellValue
    },
    whsj1({ row }) {
      if (row.whsj){
        return row.whsj.substring(0,10)
      }
      return ''
    },
    whsj2({ row }) {
      if (row.whsj){
        return row.whsj.substring(11,21)
      }
      return  ''
    },
    formatterFl2({ cellValue }) {
      for (let i = 0; i < this.typeList.length; i++) {
        if (this.typeList[i].bmjb==='2' && this.typeList[i].bm===cellValue){
          return this.typeList[i].bmsm
        }
      }
      return cellValue
    },
    formatterFl3({ cellValue }) {
      for (let i = 0; i < this.typeList.length; i++) {
        if (this.typeList[i].bmjb==='3' && this.typeList[i].bm===cellValue){
          return this.typeList[i].bmsm
        }
      }
      return cellValue
    },
    getSBLX() {
      getSBLX().then((res) => {
        this.typeList = res.data;
      })
    },
    changeWhsj1({ row, rowIndex }){
      if(row.whsj1){
        if(!row.whsj){
          row.whsj=row.whsj1+'_'+row.whsj1
          row.whsj2=row.whsj1
        }else {
          var whsj2=row.whsj.substring(11,21)
          if(row.whsj1>whsj2 ){
            row.whsj=row.whsj1+'_'+row.whsj1
            row.whsj2=row.whsj1
          }else {
            row.whsj=row.whsj1+'_'+whsj2
          }
        }
      }
    },
    changeWhsj2({ row, rowIndex }){
      if(row.whsj2){
        if(!row.whsj){
          row.whsj=row.whsj2+'_'+row.whsj2
          row.whsj1=row.whsj2
        }else {
          var whsj1=row.whsj.substring(0,10)
          if(whsj1>row.whsj2 ){
            row.whsj=row.whsj2+'_'+row.whsj2
            row.whsj1=row.whsj2
          }else {
            row.whsj=whsj1+'_'+row.whsj2
          }
        }
      }
    },

    // 设备信息转码接口
    emSbjbbZM(params) {
      emSbjbbZM({
        bmlb: params,
      }).then((res) => {
        const tableRef = this.$refs.tableRef;
     if (params == "bmbm") {
      //     // 所属部门
          this.departmentOptions = res.data;
        }else if (params == "sbyxzt") {
          const sbyxztText = tableRef.getColumnByField("sbyxzt");
          const testList = [];
          for (let i = 0; i < this.sbyxztList.length; i++) {
            const temp = {
              label: this.sbyxztList[i].label,
              value: this.sbyxztList[i].value,
            };
            testList.push(temp);
          }
          sbyxztText.editRender.options = testList;
        }
      });
    },
    // 全选
    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(
            {
              zdry:this.name,
              zdsj: new Date().toLocaleDateString(),
              sbbhDisabled: false,
              zdDisabled: false,
            },
            -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 - 180;
    },
  },
};
</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>
