<template>
  <div class="assets-container" v-show="assetsName">
    <div class="tree-wrapper">
      <div class="title">
        {{ assetsName }}
        <el-checkbox
          :value="assetsSelectAll"
          @click.native.prevent="handleAssetsSelectAll"
          :disabled="isBindPlan"
        ></el-checkbox>
      </div>
      <div class="scroll-wrapper">
        <el-tree
          show-checkbox
          :data="treeList"
          :props="{
            children: 'children',
            value: 'code',
            label: 'name',
          }"
          :filter-node-method="filterNode"
          v-loading="treeLoading"
          node-key="id"
          ref="treeRef"
          :default-expanded-keys="defaultExpandedKeys"
          :highlight-current="true"
          @node-click="handleNodeClick"
          @check="clickCheck"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
          </span>
        </el-tree>
      </div>
    </div>
    <div :class="isBindPlan ? 'table-wrapper' : 'table-box'">
      <el-table
        style="width: 100% !important"
        height="400px"
        ref="tableRef"
        :data="tableData"
        @selection-change="handleSelectionChange"
        @select="handleCurSelectionChange"
        :key="assetsName"
        :header-cell-style="{
          background: '#F0F3F3',
          border: 'none',
        }"
        :disabled="isBindPlan"
      >
        <el-table-column
          v-for="item in tableInfoData"
          :key="item.key"
          :prop="item.inKey"
          :label="item.label"
          :width="item.width"
        >
        </el-table-column>
        <el-table-column
          type="selection"
          :selectable="selectable"
          :width="tableData.length ? '55' : '500'"
        >
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
// import classManagement from "@/api/ledgerAssets/classManagement";
// import { tableContentData } from '../../../components/enum'
import { mapGetters } from "vuex";
// import {
//   getInventoryListGroup,
//   getgoodspage,
// } from "@/api/stockManagement/stocking";
import { tableContentData } from "./tableContentData.js";
export default {
  props: {
    assetsName: {
      type: String,
      default: "",
    },
    warehouseId: {
      type: [Number, String],
      default: "",
    },
    tableValuableList: {
      type: Array,
      default: () => [],
    },
    assetsType: {
      type: [String, Number],
      default: "",
    },
    assetSubType: {
      type: [String, Number],
      default: "",
    },
    planRuleInventoryDetailList: {
      type: Array,
      default: [],
    },
    isBindPlan: {
      type: Boolean,
      default: function () {
        return false;
      },
    },
  },
  computed: {
    ...mapGetters(["addOrUpdate"]),
  },
  watch: {
    // warehouseId() {
    //   if (this.curNode) {
    //     this.getTableInfo(
    //       this.curNode.data.id === this.curNode.data.originId
    //         ? ""
    //         : this.curNode.data.id
    //     );
    //   }
    // },
    planRuleInventoryDetailList(val) {
      console.log('asd',val)
      if (val) {
        this.$nextTick(() => {
          val.forEach((item) => {
            if (!this.tableSelectionList[item.bizTypeId]) {
              this.tableSelectionList[item.bizTypeId] = [item];
            } else {
              this.tableSelectionList[item.bizTypeId].push(item);
            }
          });
          this.handleAssetsChange();
        });
      }
    },
  },
  data() {
    return {
      treeList: [],
      tableInfoData: [],
      tableData: [],
      requestApi: "",
      treeLoading: false,
      tableSelectionList: {},
      assetsSelectionList: [],
      assetsSelectAll: false,
      curNode: null,
      defaultExpandedKeys: [],
      changeData: [],
      isChecked: false,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.handleAssetsChange();
    });
  },
  created() {
    // console.log('库内')
    // if(this.planRuleInventoryDetailList){
    //   console.log('this.planRuleInventoryDetailList',this.planRuleInventoryDetailList)
    //   this.tableData = this.planRuleInventoryDetailList
    // }
  },
  methods: {
    //表格复选框禁用
    selectable(row, rowIndex) {
      if (this.isBindPlan) {
        return false;
      } else {
        return true;
      }
    },
    // 重置
    resetData() {
      this.clearSelection();
      this.treeList = [];
    },
    //清除选中
    clearSelection() {
      this.assetsSelectAll = false;
      this.tableData = [];
      this.tableSelectionList = {};
    },
    //派单过滤
    filterNode(value, data, node) {
      return (
        this.tableValuableList.findIndex(
          (item) => item.bizTypeId === data.id
        ) !== -1
      );
    },
    getSelectList() {
      const classificationList =
        (this.$refs.treeRef && this.$refs.treeRef.getCheckedNodes()) || [];
      const list = Object.values(this.tableSelectionList) || [];
      var arr = [];
      list.map((item, index) => {
        for (var i = 0; i < item.length; i++) {
          arr.push(item[i]);
        }
      });
      const tableSelectionList = arr;
      return {
        classificationList,
        tableSelectionList,
        // tableSelectionList: Object.values(this.tableSelectionList)
        //   .flat()
        //   .filter(
        //     // i => !classificationList.find(itm => i.classificationId == itm.id)
        //      i => !classificationList.find(itm => i.bizTypeId == itm.id)
        //   )
        //   .map(item => {
        //     item.minPackUnit = item.minPackUtil
        //     return item
        //   })
      };
    },
    handleAssetsChange() {
      setTimeout(() => {
        if (this.assetsName) {
          let obj = tableContentData.find(
            (item) => item.name === this.assetsName
          );
          this.tableInfoData = (obj && obj.tableData) || [];
          this._getTreeList();
          // this.clearSelection()
        }
      }, 0);
    },
    // 设备、舟皿、周转车、模具
    async _getTreeList() {
      let res = await classManagement.getClassificationTreeAsyncCall({
        id: "0",
        type: this.assetsType,
      });
      if (res?.success) {
        this.treeList = res.data[0]?.children || [];
        if (this.isBindPlan) {
          this.deepEach(this.treeList);
        }
        if (this.tableValuableList?.length) {
          this.$nextTick(() => {
            this.$refs.treeRef.filter();
          });
        }

        if (this.addOrUpdate === "edit") {
          let keys = [];
          this.planRuleInventoryDetailList.map((item) => {
            if (item.bizTypeId !== null) {
              keys.push(item.bizTypeId);
            }
          });
          keys = [...new Set(keys)];
          this.defaultExpandedKeys = keys;
          if (keys.length) {
            this.$nextTick(() => {
              this.$refs.treeRef.setCurrentKey(keys[0]);
              this.convertTreeData();
              let chooseData = null;
              this.changeData.map((item) => {
                if (item.id == keys[0]) {
                  chooseData = item;
                }
              });
              if (chooseData) {
                this.getTableInfo(chooseData.id);
              }
              //    this.handleNodeClick(chooseData,node)
            });
          }
        }
      }
    },
    handleNodeClick(data, node) {
      console.log(node, "node");
      if (!node.isLeaf) return; //限制叶子节点
      this.curNode = node;
      // this.getTableInfo(data.id === data.originId ? '' : data.id)
      this.getTableInfo({
        assetType: data.type,
        classificationIds: [data.id],
      });
    },
    setclassIds(data, list) {
      if (data && data.length !== 0) {
        data.forEach((item) => {
          if (item.children && item.children.length !== 0) {
            this.setclassIds(item.children, list);
          }
          list.push(item.id);
        });
      }
      return list;
    },

    async getTableInfo(assetSubType) {
      const params = {
        page: 1,
        size: 9999,
        ...assetSubType,
      };

      if (assetSubType) {
        params.assetSubType = assetSubType;
      }
      const res = await getgoodspage(params);
      if (res?.success) {
        if (this.tableValuableList && this.tableValuableList.length) {
          // 派单过滤
          this.tableData = res.data.records
            .filter(
              (item) =>
                this.tableValuableList.findIndex(
                  (i) => i.assetId == item.id
                ) !== -1
            )
            .map((i, index) => ({
              ...i,
              index,
              classificationId: assetSubType,
            }));
        } else {
          this.tableData = res.data.records.map((i, index) => ({
            ...i,
            index,
            classificationId: assetSubType,
          }));
        }
        const checkedTrees = this.$refs.treeRef.getCheckedKeys();

        // if(this.addOrUpdate === 'edit'){
        //   this.defaultExpandedKeys
        // }
        this.$nextTick(() => {
          //分类选中
          this.tableData.map((item) => {
            if (checkedTrees.includes(item.classificationId + "")) {
              this.$refs.tableRef.toggleRowSelection(item);
            }
          });
          // 表格选中（切换保存状态
          for (const key in this.tableSelectionList) {
            this.tableSelectionList[key].forEach((item) => {
              const row = this.tableData.find((i) => i.id === item.id);
              if (row) {
                //this.$refs.tableRef.toggleRowSelection(row, true)
              }
            });
          }
        });

        if (this.addOrUpdate === "edit") {
          if (this.planRuleInventoryDetailList) {
            this.tableData.map((item) => {
              for (
                var i = 0;
                i < this.planRuleInventoryDetailList.length;
                i++
              ) {
                if (
                  item.id == this.planRuleInventoryDetailList[i].id
                ) {
                  this.$nextTick(() => {
                    this.$refs.tableRef.toggleRowSelection(item, true);
                  });
                }
              }
            });
          }
        }
      }
    },

    // tree选中状态改变
    clickCheck(data, checkinfo) {
      const isChecked = checkinfo.checkedKeys.indexOf(data.id) > -1;

      if (!isChecked) {
        //取消全选
        this.assetsSelectAll = false;
      }

      if (this.curNode && this.curNode.data.id === data.id) {
        this.tableData.forEach((row) => {
          this.$refs.tableRef.toggleRowSelection(row, isChecked);
        });
      }
    },

    // 资产分类全选  通过点击事件更改状态
    handleAssetsSelectAll() {
      if (this.isBindPlan) return;
      this.assetsSelectAll = !this.assetsSelectAll;
      if (this.assetsSelectAll) {
        const keys = this.treeList.map((item) => item.id);
        this.$refs.treeRef.setCheckedKeys(keys);
      } else {
        this.$refs.treeRef.setCheckedKeys([]);
      }
    },
    handleSelectionChange(val) {
      console.log(val);
      let bizType = {};
      if (this.curNode) {
        bizType = {
          bizTypeId: this.curNode.data?.id,
          bizTypeName: this.curNode.data?.name,
        };
        this.$set(
          this.tableSelectionList,
          this.curNode.data.id,
          val.map((i) => ({
            ...i,
            ...bizType,
          }))
        );
      }
      if (val.length > 0 && val.length === this.tableData.length) {
        //全选
        this.$refs.treeRef.setChecked(val[0].classificationId, true);
      }
      if (val.length === 0 && this.tableData.length > 0) {
        //全不选
        this.$refs.treeRef.setChecked(
          this.tableData[0].classificationId,
          false
        );
      }
    },
    handleCurSelectionChange(selection, row) {
      if (selection.findIndex((item) => item.index === row.index) === -1) {
        //取消选中
        this.$refs.treeRef.setChecked(row.classificationId, false);

        for (const key in this.tableSelectionList) {
          const idx = this.tableSelectionList[key].findIndex(
            (item) => item.id === row.id
          );
          if (idx !== -1) {
            this.tableSelectionList[key].splice(idx, 1);
          }
        }
      }
    },

    convertTreeData() {
      this.changeData = this.treeList;
      for (let i = 0; i < this.changeData.length; i++) {
        if (this.changeData[i].children != undefined) {
          const temp = this.changeData[i].children;
          delete this.changeData[i].children;
          this.changeData = this.changeData.concat(temp);
        }
      }
    },

    // 子节点处理
    deepEach(arr) {
      arr.forEach((item) => {
        item.disabled = true;
        if (item.children) {
          this.deepEach(item.children); // 递归
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .table-wrapper .el-table__header-wrapper .el-checkbox {
  display: none;
}
::v-deep.assets-container {
  display: flex;
  width: 100%;
  .el-tree-node__content > .el-checkbox {
    position: absolute;
    right: 0;
  }
  .tree-wrapper {
    // width: 350px;
    width: 30%;
    margin-right: 12px;
    border: 1px solid #ccc;

    .title {
      text-align: center;
      font-size: 16px;
      font-weight: bold;
      background: #f0f3f3;
      padding: 4px;
      padding-right: 8px;
      .el-checkbox {
        float: right;
      }
    }
    .scroll-wrapper {
      padding-top: 8px;
    }
  }
  .table-wrapper {
    width: 70%;
    padding: 8px;
    border: 1px solid #ccc;
  }

  .table-box {
    width: 70%;
    padding: 8px;
    border: 1px solid #ccc;
  }
}
</style>
