<template>
  <div>
    <p-spin size="small" :spinning="spinning">
      <p-card title="普通养护录入">
        <div slot="extra">
          <p-button type="primary" @click="onEdit">批量修改措施</p-button>
          <p-button class="ml-10" type="primary" @click="send">发送设备指令</p-button>
          <!-- <p-button type="primary" class="ml-10" @click="split">拆分</p-button> -->
          <!-- <p-button type="primary" class="ml-10" @click="add">新增</p-button> -->
          <p-button type="primary" class="ml-10" @click="save">保存</p-button>
        </div>
        <mainTable ref="maintable" :tablecolumns="tableColumns" />
      </p-card>
    </p-spin>
    <p-modal
      width="80%"
      title="普通养护录入"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <p-table
        bordered
        ref="mable"
        row-key="id"
        :columns="tableColumns.search.columns"
        :dataSource.sync="dataSource"
        :rowSelectType="1"
        :selectedRowKeys.sync="selectedRowKeys"
        @selectChange="selectChange"
        @dblclickRow="dblclickRow"
        :hasRowSelectCheck="true"
      />
    </p-modal>
    <!-- 批量修改 -->
    <p-modal
      title="养护措施"
      :visible="isShow"
      @ok="onOk"
      @cancel="onCancel"
    >
      <p-block-select 
        :options="option1" 
        mode="multiple" 
        :showAllSeclect="false"
        :value="value1"
        @change="handleChange1"
      >
      </p-block-select>
      <a-divider />
      <p-block-select 
        :options="option2" 
        mode="multiple" 
        :showAllSeclect="false"
        :value="value2"
        @change="handleChange2"
      >
      </p-block-select>
      <a-divider />
      <p-block-select 
        :options="option3" 
        mode="multiple" 
        :showAllSeclect="false"
        :value="value3"
        @change="handleChange3"
      >
      </p-block-select>
    </p-modal>
  </div>
</template>

<script>
import mainTable from "../../components/mainTable";
import { tableColumns, getList } from "./config";
import { batchAdd, findPlan, findByPlanId, batchEdit, gspUpkeepCheckbatchAdd, sendToEis } from "../../api";
import { diffOption } from "@/views/kzyWMS/utils/index.js";
export default {
  components: { mainTable },
  data() {
    return {
      // 药品养护记录-6
      upkeepType: 6,
      type: true,
      spinning: false,
      ids: {},
      dataSource: [],
      show: true,
      selectedRowsList: [],
      selectedRowKeys: [],
      visible: false,
      confirmLoading: false,
      tableColumns: [],
      isShow: false,
      value1: [],
      value2: [],
      value3: [],
      option: [],
      option1: [],
      option2: [],
      option3: [],
    };
  },
  created() {
    this.getList()
    this.tableColumns = tableColumns(this);
    // diffOption(this.tableColumns).then((res) => {
    //   this.tableColumns = res;
    // });
  },
  methods: {
    getList() {
      getList().then(res => {
        if (res.success) {
          if (res.data.length === 0) return
          this.option1 = res.data.filter(item => item.attr1 == 1).map(t => {
            return { label: t.dictName, value: t.dictCode }
          })
          this.option2 = res.data.filter(item => item.attr1 == 2).map(t => {
            return { label: t.dictName, value: t.dictCode }
          })
          this.option3 = res.data.filter(item => item.attr1 == 3).map(t => {
            return { label: t.dictName, value: t.dictCode }
          })
          this.option = res.data.map(t => {
            return { label: t.dictName, value: t.dictCode }
          })
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleChange1(p1){
      console.log(p1,'p1');

    },
    handleChange2(p1) {
      let list = p1
      if (list.length === 0) return
      if (this.value3.length === 0) return
      list.forEach(item => {
        if (item === 'checkJiaShi') {
          this.value3 = this.value3.filter(item => item !== 'checkChuShi')
        }
        if (item === 'checkShenWen') {
          this.value3 = this.value3.filter(item => item !== 'checkJiangWen')
        }
        if (item === 'checkZheGuang') {
          this.value3 = this.value3.filter(item => item !== 'checkBiGuang')
        }
      })
    },
    handleChange3(p1){
      let list = p1
      if (list.length === 0) return
      if (this.value2.length === 0) return
      list.forEach(item => {
        if (item === 'checkChuShi') {
          this.value2 = this.value2.filter(item => item !== 'checkJiaShi')
        }
        if (item === 'checkJiangWen') {
          this.value2 = this.value2.filter(item => item !== 'checkShenWen')
        }
        if (item === 'checkBiGuang') {
          this.value2 = this.value2.filter(item => item !== 'checkZheGuang')
        }
      })
    },
    onEdit() {
      const selectRows = this.$refs.maintable.getselectedRowsfun()
      if (selectRows.length === 0) return this.$message.warn('请先勾选数据')
      const list1 = this.option1.map(item => item.value)
      const list2 = this.option2.map(item => item.value)
      const list3 = this.option3.map(item => item.value)
      const obj = selectRows[0]
      Object.keys(obj).forEach(key => {
        list1.forEach(item => {
          if (item === key && obj[key]) {
            this.value1.push(key)
          }
        })
        list2.forEach(item => {
          if (item === key && obj[key]) {
            this.value2.push(key)
          }
        })
        list3.forEach(item => {
          if (item === key && obj[key]) {
            this.value3.push(key)
          }
        })
      })
      
      this.isShow = true
    },
    onOk() {
      // id集合
      const selectRows = this.$refs.maintable.getselectedRowsfun().map(item=>item.id)
      let list = this.option.map(item => item.value)
      let obj = {}
      let arr = this.value1.concat(this.value2, this.value3)
      // 统一赋值false
      list.forEach(item => obj[item] = false)
      // 勾选为true
      list.forEach(item => {
        arr.forEach(t1 => {
          if (item === t1) {
            obj[item] = true
          }
        })
      })
      // 赋值
      this.$refs.maintable.data.forEach((item, index) => {
        list.forEach(t => {
          if (selectRows.includes(item.id)) {
            item[t] = obj[t]
          }
        })
      })
      this.onCancel()
    },
    onCancel(){
      this.isShow = false
      this.value1 = []
      this.value2 = []
      this.value3 = []
    },
    //双击弹窗表格
    dblclickRow(event, activeID, rowRecord) {
      this.handleOk();
    },
    send() {
      const selectRows = this.$refs.maintable.getselectedRowsfun();
      if (selectRows.length === 0) return this.$message.error("请勾选需要发送设备指令的养护记录信息");
      //判断是否为立体库
      let LTKType = selectRows.find(
        (i) => i.outWhAreaCategory == "AGVZ" || i.outWhAreaCategory == "AGVL" || i.outWhAreaCategory == "MJK"
      );
      let warehouseRoomCodeList = [...new Set(selectRows.map((i) => i.outWhAreaCategory))];
      if (LTKType && warehouseRoomCodeList.length != 1) {
        this.$message.error("不同库区不能同时发送设备指令!");
        return;
      }

      //   console.log("发送设备指令");

      if (selectRows.length === 0) return this.$message.error("请勾选需要发送设备指令的养护记录信息");
      //   const dataSource = this.dataSource;
      console.log(selectRows);
      let data = selectRows.filter((_) => _.id).map((i) => i.id);
      console.log(data);
      if (data.length == 0) {
        this.$message.error("请勾选需要发送设备指令的养护记录信息");
        return;
      }
      sendToEis(data).then((res) => {
        if (res.success) {
          this.$message.success(res.message);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    add() {
      this.tableColumns.MainTable.columns = this.tableColumns.MainTable.columns1;
      if (this.type) {
        this.$refs.maintable.cleanData();
        this.type = false;
      }
      this.$nextTick(() => {
        this.$refs.maintable.createRow();
      });
    },
    split() {
      console.log("拆分");
      this.$refs.maintable.getSelectRowSplit();
      this.$refs.maintable.setType(true);
    },
    async save() {
      console.log("保存");
      let tableData = this.$refs.maintable.getselectedRowsfun();
      if (tableData.length === 0) return this.$message.warning("至少需要一条数据!");
      let data = tableData.map((item) => {
        item.id = item.id.replace(/_copy_\d*/, "");
        return item;
      });
      if (data.length === 0) {
        this.$message.warning("至少需要一条数据!");
        this.spinning = false;
        return;
      }
      if (this.type) {
        this.spinning = true;
        let res = await batchEdit(data);
        if (res.success) {
          let id = this.selectedRowsList[0].id;
          this.$refs.maintable.gettable({ id });
          this.$message.success("保存成功!");
          this.$refs.maintable.cleanData();
        } else {
          this.$exception(res);
        }
        this.spinning = false;
      } else {
        let form = this.$refs.maintable.getgridformdata();
        data.forEach((item) => {
          item.warehouseId = form.warehouseId;
        });
        this.spinning = true;
        let res = await gspUpkeepCheckbatchAdd(data);
        if (res.success) {
          let id = this.selectedRowsList[0].id;
          this.$refs.maintable.gettable({ id });
          this.$message.success("新增成功!");
          this.$refs.maintable.cleanData();
        } else {
          this.$exception(res);
        }
        this.spinning = false;
      }
    },
    selectChange(selectedRowKeys, selectedRows) {
      this.selectedRowsList = selectedRows;
    },
    async showModal() {
      let data = this.$refs.maintable.getgridformdata();
      console.log(data);
      data.upkeepType = this.upkeepType;
      if (data) {
        let res = await findPlan(data);
        console.log(res, "====");
        if (res.success) {
          res.data.list.forEach((item) => {
            item.source == "0" && (item.source = "手动");
            item.source == "1" && (item.source = "自动");
          });
          this.visible = true;
          this.dataSource = res.data.list;
        } else {
          this.$exception(res);
        }
      }
    },
    async handleOk(e) {
      if (this.selectedRowsList.length > 0) {
        let id = this.selectedRowsList[0].id;
        let upkeepType = this.upkeepType;
        this.tableColumns.MainTable.columns = this.tableColumns.MainTable.columns2;
        this.selectedRowKeys = [];
        this.$refs.maintable.gettable({ id, upkeepType });

        this.visible = false;
        this.type = true;
      } else {
        this.$message.success("请选择数据!");
      }
    },
    handleCancel(e) {
      console.log("Clicked cancel button");
      this.visible = false;
    },
    async makePlan() {
      let that = this;
      let selectedRow = this.$refs.maintable.getselectedRowsfun();
      console.log(selectedRow, "====");
      let res = await batchAdd(selectedRow);
      console.log(res);
      if (res.success) {
        this.$success({
          title: "提示",
          // JSX support
          content: (
            <div>
              <p>生成养护记录成功!</p>
            </div>
          ),
          ok: function () {
            that.$refs.maintable.reload();
          },
        });
      } else {
        this.$exception(res);
      }
    },
  },
};
</script>
