<template>
  <div class="assets-container" v-show="assetsName">
    <div class="tree-wrapper">
      <div class="title">
        {{ assetsName }}
        <!-- <el-checkbox
          :value="assetsSelectAll"
          @click.native.prevent="handleAssetsSelectAll"
        ></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"
          :highlight-current="true"
          @node-click="handleNodeClick"
          @check="handleCheckChange"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
          </span>
        </el-tree>
      </div>
    </div>
    <div class="table-wrapper">
      <el-table
        style="width: 100%"
        height="400px"
        ref="tableRef"
        :data="tableData"
        @selection-change="handleSelectionChange"
        @select="handleCurSelectionChange"
        :key="assetsName"
        :header-cell-style="{
          background: '#F0F3F3',
          border: 'none'
        }"
      >
        <el-table-column label="序号" type="index"> </el-table-column>
        <el-table-column
          v-for="item in tableInfoData"
          :key="item.index"
          :prop="item.inKey"
          :label="item.label"
        >
          <template slot-scope="scope">
            <div v-if="item.inKey == 'ckg'">{{ setZKG(scope.row) }}</div>
            <div v-else-if="item.inKey == 'shrinkageCoefficient'">
              {{ setExtendField(scope.row, 'shrinkageCoefficient') }}
            </div>
            <div v-else>{{ scope.row[item.inKey] }}</div>
          </template>
        </el-table-column>
        <el-table-column type="selection" width="55"> </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
// import classManagement from '@/api/ledgerAssets/classManagement'
import { tableContentData } from './tableContentData.js'
// import {
//   getInventoryListGroup,
//   getgoodspage
// } from '@/api/stockManagement/stocking'
import { deepClone } from '@/utils'

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: ''
    },
    bizType: {
      type: [String, Number],
      default: ''
    }
  },
  // watch: {
  //   warehouseId() {
  //     if (this.curNode) {
  //       this.getTableInfo(
  //         this.curNode.data.id === this.curNode.data.originId
  //           ? ""
  //           : this.curNode.data.id
  //       );
  //     }
  //   },
  // },
  data () {
    return {
      treeList: [],
      tableInfoData: [],
      tableData: [],
      requestApi: '',
      treeLoading: false,
      tableSelectionList: {},
      assetsSelectionList: [],
      assetsSelectAll: false,
      curNode: null
    }
  },
  mounted () {
    // this.handleAssetsChange()
  },
  methods: {
    // 重置
    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()) || []
      return {
        classificationList,
        tableSelectionList: Object.values(this.tableSelectionList).flat()
        // tableSelectionList: Object.values(this.tableSelectionList)
        //   .flat()
        //   .filter(
        //     (i) =>
        //       !classificationList.find((itm) => i.classificationId == itm.id)
        //   ),
      }
    },
    handleAssetsChange () {
      this.clearSelection()
      setTimeout(() => {
        if (this.assetsName) {
          let obj = tableContentData.find(item => item.name === this.assetsName)
          this.tableInfoData = (obj && obj.tableData) || []

          this._getTreeList()
        }
      }, 0)
    },
    // 设备、舟皿、周转车、模具
    async _getTreeList () {
      let res = await classManagement.getClassificationTreeAsyncCall({
        id: '0',
        type: this.assetsType
      })
      if (res?.success) {
        this.treeList = this.formateTree(res.data[0]?.children || [])

        if (this.tableValuableList?.length) {
          this.$nextTick(() => {
            this.$refs.treeRef.filter()
          })
        }
      }
    },
    formateTree (list) {
      const fn = arr => {
        for (const p of arr) {
          p.disabled = true

          p.children?.length && fn(p.children)
        }
      }

      fn(list)

      return list
    },
    handleNodeClick (data, node) {
      console.log((data, node))
      this.curNode = node
      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 (par) {
      const params = {
        page: 1,
        size: 9999,
        ...par
      }

      const res = await getgoodspage(params)
      if (res?.success) {
        const checkedTrees = this.$refs.treeRef.getCheckedKeys()
        const tableSelectionList = deepClone(this.tableSelectionList)

        if (this.tableValuableList && this.tableValuableList.length) {
          // 派单过滤
          this.tableData = res.data.records
            .filter(
              item =>
                this.tableValuableList.findIndex(
                  i => i.informationId == item.id
                ) !== -1
            )
            .map((i, index) => ({
              ...i,
              index
              //classificationId: assetSubType
            }))
        } else {
          this.tableData = res.data.records.map((i, index) => ({
            ...i,
            index
            //classificationId: assetSubType
          }))
        }
        console.log(checkedTrees)
        this.$nextTick(() => {
          //分类选中
          this.tableData.map(item => {
            if (checkedTrees.includes(item.classificationId + '')) {
              this.$refs.tableRef.toggleRowSelection(item)
            }
          })
          // 表格选中（切换保存状态
          for (const key in tableSelectionList) {
            console.log('qqw', key)
            tableSelectionList[key].forEach(item => {
              const row = this.tableData.find(i => {
                console.log(i.id, item.informationId)
                return i.id === (item.informationId || item.id)
              })
              if (row) {
                this.$refs.tableRef.toggleRowSelection(row, true)
              }
            })
          }
        })
      }
    },
    // async getTableInfo (assetSubType) {
    //   const params = {
    //     page: 1,
    //     size: 9999,
    //     assetType: this.assetsType,
    //     warehouseId: this.warehouseId
    //   }

    //   if (assetSubType) {
    //     params.assetSubType = assetSubType
    //   }
    //   const res = await getgoodspage(params)
    //   if (res?.success) {
    //     const checkedTrees = this.$refs.treeRef.getCheckedKeys()
    //     const tableSelectionList = deepClone(this.tableSelectionList)
    //     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
    //       }))
    //     }
    //     this.$nextTick(() => {
    //       //分类选中
    //       this.tableData.map(item => {
    //         if (checkedTrees.includes(item.classificationId + '')) {
    //           this.$refs.tableRef.toggleRowSelection(item)
    //         }
    //       })
    //       // 表格选中（切换保存状态
    //       for (const key in tableSelectionList) {
    //         tableSelectionList[key].forEach(item => {
    //           const row = this.tableData.find(
    //             i => i.classificationId === item.classificationId
    //           )
    //           if (row) {
    //             this.$refs.tableRef.toggleRowSelection(row, true)
    //           }
    //         })
    //       }
    //     })
    //   }
    // },
    // tree点击选中状态改变
    handleCheckChange (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 () {
      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([])
      }
      this.tableData.forEach(row => {
        this.$refs.tableRef.toggleRowSelection(row, this.assetsSelectAll)
      })
    },
    handleSelectionChange (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) {
      //   //全选

      //   val.forEach(item => {
      //     this.$refs.treeRef.setChecked(item.classificationId, true)
      //   })
      // }
      // if (val.length === 0 && this.tableData.length > 0) {
      //   //全不选
      //   this.tableData.forEach(item => {
      //     this.$refs.treeRef.setChecked(item.classificationId, false)
      //   })
      // }
      // if (val.length && val.length < this.tableData.length) {

      this.tableData.forEach(item => {
        let node = {
          parent: this.$refs.treeRef.getNode(item.classificationId)
        }
        do {
          node = node.parent
          node.indeterminate = false
        } while (node.parent)
      })
      val.forEach(item => {
        let node = {
          parent: this.$refs.treeRef.getNode(item.classificationId)
        }
        do {
          node = node.parent
          node.indeterminate = true
        } while (node.parent)
      })
      // }
    },
    handleCurSelectionChange (selection, row) {
      console.log(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)
          }
        }
      }

      // if (selection.length && selection.length < this.tableData.length) {
      //   let node = { parent: this.curNode }
      //   do {
      //     node = node.parent
      //     node.indeterminate = true
      //   } while (node.parent)
      // } else {
      //   this.curNode.indeterminate = false
      // }
    },
    // 设置长宽高
    setZKG (row) {
      if (row.extendField) {
        let item = JSON.parse(row.extendField)
        return `${item.length || '无'}/${item.width || '无'}/${
          item.high || '无'
        }`
      }
    },
    // 显示扩展字段
    setExtendField (row, type) {
      if (row.extendField) {
        let item = JSON.parse(row.extendField)
        return item[type]
      }
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep.assets-container {
  display: flex;
  .el-tree-node__content > .el-checkbox {
    position: absolute;
    right: 0;
  }
  .tree-wrapper {
    width: 350px;
    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;

      .el-checkbox__input.is-indeterminate .el-checkbox__inner {
        background-color: #157a2c;
        border-color: #157a2c;
      }
    }
  }
  .table-wrapper {
    flex: 1;
    padding: 8px;
    border: 1px solid #ccc;
  }
}
</style>
