<template>
  <div>
    <p-card :title="title">
      <div slot="extra">
        <div class="btns">
          <p-button type="primary" @click="onEdit">批量修改措施</p-button>
          <p-button type="primary" style="margin-left: 20px" @click="send">发送设备指令</p-button>
          <p-button type="primary" style="margin-left: 20px" @click="split">拆分</p-button>
          <!-- <p-button type="primary" style="margin-left: 20px" @click="add">新增</p-button> -->
          <!-- <p-button type="primary" style="margin-left:20px">打印</p-button> -->
          <p-button type="primary" style="margin-left: 20px" @click="save">保存</p-button>
        </div>
      </div>
      <p-spin size="small" :spinning="spinning">
        <main-table v-if="show" ref="maintable" :tablecolumns="tablecolumns"></main-table>
      </p-spin>
    </p-card>
    <p-modal
      width="80%"
      :title="title"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <p-table
        bordered
        ref="mable"
        row-key="id"
        :columns="tablecolumns.search.columns"
        :data-source.sync="data"
        :rowSelectType="1"
        :selected-row-keys.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 from "./config";
import { batchAdd, findPlan, findByPlanId, batchEdit, gspUpkeepCheckbatchAdd, sendToEis, getList } from "../../api";

export default {
  name: "RecordTable",
  data() {
    return {
      type: true,
      spinning: false,
      ids: {},
      data: [],
      show: true,
      selectedRowsList: [],
      selectedRowKeys: [],
      visible: false,
      businessData: "",
      confirmLoading: false,
      tablecolumns: [],
      isShow: false,
      value1: [],
      value2: [],
      value3: [],
      option: [],
      option1: [],
      option2: [],
      option3: [],
    };
  },
  watch: {
    selectedRowKeys(v) {
      console.log("selectedRowKeys", v);
    },
  },
  props: {
    title: {
      type: String,
      default: "医疗器械养护记录",
    },
    upkeepType: {
      type: Number,
      default: 7,
    },
  },
  created() {
    this.getList()
    this.tablecolumns = tablecolumns(this);
  },
  components: {
    MainTable,
  },

  //   mixins: [setwarehouse],
  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 = []
    },
    send() {
      console.log("发送设备指令");
      const selectRows = this.$refs.maintable.getselectedRowsfun();
      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);
        }
      });
    },
    //双击弹窗表格
    dblclickRow(event, activeID, rowRecord) {
      //   console.log(event, activeID, rowRecord)
      this.handleOk();
    },
    setRowQTy(id, value) {
      console.log(id, value);
      this.$refs.maintable.setRowQTy(id, value);
    },
    add() {
      this.tablecolumns.MainTable.columns = this.tablecolumns.MainTable.columns1;
      //   this.show = false
      //   setTimeout(() => {
      //     this.show = true
      //   }, 0)
      if (this.type) {
        this.$refs.maintable.cleanData();
        this.type = false;
      }
      setTimeout(() => {
        this.$refs.maintable.createRow();
        // moment().format("YYYY-MM-DD HH:mm:ss");
      }, 0);
    },
    split() {
      console.log("拆分");
      let data = this.$refs.maintable.getSelectRowSplit();
      this.$refs.maintable.setType(true);
      //   console.log(data)
      //   this.ids = data
    },
    async save() {
      if (!this.spinning) {
        console.log("保存");
        // console.log(this.selectedRowKeys)
        let tableData = this.$refs.maintable.getselectedRowsfun();
        console.log(tableData);
        if (!tableData.length) {
          this.$message.warning("至少需要一条数据!");
          this.spinning = false;
          return;
        }
        // if (tableData) {
        let data = tableData.map((item) => {
          item.id = item.id.replace(/_copy_\d*/, "");
          return item;
        });
        if (this.type && data.length > 0) {
          console.log("保存", data);
          this.spinning = true;
          let res = await batchEdit(data);
          console.log(res);
          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 if (!this.type && data.length > 0) {
          console.log("新增");
          let sss = this.$refs.maintable.getgridformdata();
          console.log(sss);
          data.forEach((item) => {
            item.warehouseId = sss.warehouseId;
          });
          this.spinning = true;
          let res = await gspUpkeepCheckbatchAdd(data);
          console.log(res);
          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 {
          this.$message.warning("至少需要一条数据!");
          this.spinning = false;
        }
        // } else {
        //   this.$message.warning("至少需要一条数据!");
        //   this.spinning = false;
        // }
      }
    },
    selectChange(selectedRowKeys, selectedRows) {
      console.log(selectedRows);
      this.selectedRowsList = selectedRows;
    },
    async showModal() {
      let data = this.$refs.maintable.getgridformdata();
      console.log(data);
      data.upkeepType = this.upkeepType || 7;
      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.data = res.data.list;
          //   this.cleanSeleRow();
          this.$refs.maintable.cleanData();
          this.$refs.maintable.cleanSeleRow();
        } else {
          this.$exception(res);
        }
      }

      //   this.visible = true
    },
    async handleOk(e) {
      //   this.confirmLoading = true
      if (this.selectedRowsList.length > 0) {
        let id = this.selectedRowsList[0].id;
        let upkeepType = this.upkeepType;
        // this.tablecolumns.MainTable.columns = []
        // this.show = false
        this.tablecolumns.MainTable.columns = this.tablecolumns.MainTable.columns2;
        // setTimeout(() => {
        // this.show = true
        // }, 0)

        console.log(this.tablecolumns.MainTable.columns2);
        this.$refs.maintable.cleanData();
        this.$refs.maintable.cleanSeleRow();
        let sssa = this.tablecolumns.MainTable.columns.filter((item) => {
          //   console.log(item)
          return item.required == true;
        });
        console.log(sssa);

        this.$refs.maintable.gettable({ id, upkeepType });
        this.visible = false;
        this.type = true;
      } else {
        this.$message.success("请选择数据!");
      }

      //   let res = await findByPlanId({ id })
      //   console.log(res)
      //   if (res.success) {
      //     this.visible = false
      //     this.confirmLoading = false
      //   } else {
      //     this.$exception(res)
      //   }
      //   setTimeout(() => {
      //     this.visible = false
      //     this.confirmLoading = false
      //   }, 2000)
    },
    handleCancel(e) {
      console.log("Clicked cancel button");
      this.visible = false;
    },
    aaa() {
      console.log("aaa");
    },
    async Makeplan() {
      let that = this;
      //        selectedRowsfun(selectedRowKeys, selectedRow) {
      //   this.selectedRow = selectedRow
      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>

<style scoped>
.btns {
  /* width: 400px; */
  display: flex;
  justify-content: space-around;
}
</style>
