<template>
  <el-dialog :visible.sync="dialogVisible" title="物料速查" width="1500px" append-to-body>
    <div class="query_model">
      <el-row :gutter="16">
        <el-col :span="4">
          <el-tree
            :data="treeData"
            :props="defaultProps"
            node-key="id"
            :highlight-current="true"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            default-expand-all
          >
            <!-- 使用插槽自定义节点内容 -->
            <span class="custom-tree-node" slot-scope="{ node, data }">
            <!-- 自定义图标 -->
            <i :class="getCustomIcon(node, data)" class="tree-icon"></i>
            <span>{{ node.label }}</span>
          </span>
          </el-tree>
        </el-col>
        <el-col :span="20">
          <!-- 单选：无 radio，点击行高亮；多选：勾选框 -->
          <el-table
            ref="queryTable"
            stripe
            :class="{ 'query-table-single': !isMultiple }"
            :data="queryList"
            border
            height="600"
            :highlight-current-row="!isMultiple"
            @row-click="handleRowClick"
            @selection-change="handleSelectionChange"
          >
            <!-- 多选：已选中的物料禁止再次选择 -->
            <el-table-column v-if="isMultiple" type="selection" width="55" align="center" fixed :selectable="isRowSelectable" />
            <el-table-column label="货物编号" align="center" width="150" fixed prop="goodsNum" />
            <el-table-column label="货物名称" align="center" width="150" fixed prop="goodsName" />
            <el-table-column label="仓库名称" align="center" width="150" prop="warehouseName" />
            <el-table-column label="货品类别" align="center" width="100" prop="goodsTypeName" />
            <el-table-column label="货品规格" align="center" width="100" prop="goodsSpec" />
            <el-table-column label="货品条码" align="center" width="100" prop="goodsBarcode" />
            <el-table-column label="计量单位" align="center" width="100" prop="unit" />
            <el-table-column label="辅助计量单位" align="center" width="100" prop="assistantUnit" />
            <el-table-column label="换算值" align="center" width="100" prop="conversionValue" />
            <el-table-column label="品种" align="center" width="100" prop="varietyName" />
            <el-table-column label="级别" align="center" width="100" prop="goodsLevel" />
            <el-table-column label="状态" align="center" width="100" prop="goodsStatus" />
            <el-table-column label="货品颜色" align="center" width="100" prop="goodsColor" />
            <el-table-column label="货品尺寸" align="center" width="100" prop="goodsSize" />
            <el-table-column label="产品类型" align="center" width="150" prop="productTypeName" />
          </el-table>
        </el-col>
      </el-row>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="confirmList">确 定</el-button>
      <el-button @click="close">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
  import { getGoodsTree } from "../../api/baseInfo/goods";
  import { getGoodsByMaterial } from "../../api/baseInfo/material";

  export default {
    name: 'QueryMaterial',
    props: {
      isMultiple: {
        type: Boolean,
        default: true
      },
      /** 已经选中的物料编号（goodsNum），在速查里禁止再次选择 */
      excludeGoodsNums: {
        type: Array,
        default: () => []
      },
    },
    data() {
      return {
        dialogVisible: false,
        treeData: [
          {
            id: null,
            categoryName: '货品类别',
            child: [
            ]
          }
        ],
        defaultProps: {
          children: 'child',
          label: 'categoryName'
        },
        queryList: [],
        selectList: []
      }
    },
    methods: {
      // 根据节点类型返回图标
      getCustomIcon(node, data) {
        let icon = node.expanded ? 'el-icon-folder-opened' : 'el-icon-folder'
        return icon;
      },
      open() {
        this.initTree()
        this.initMaterial()
        this.selectList = []
        this.dialogVisible = true
        this.$nextTick(() => {
          if (this.$refs.queryTable && !this.isMultiple) {
            this.$refs.queryTable.setCurrentRow(null)
          }
        })
      },
      close() {
        if (this.$refs.queryTable) {
          if (this.isMultiple) {
            this.$refs.queryTable.clearSelection()
          } else {
            this.$refs.queryTable.setCurrentRow(null)
          }
        }
        this.dialogVisible = false
      },
      // 选中
      handleNodeClick(data) {
        this.initMaterial(data.num)
      },
      /**
       * 单选模式：点击行高亮并选中（不使用 radio）
       * @param {Object} row 当前行数据
       */
      handleRowClick(row) {
        if (this.isMultiple) return
        if (this.isGoodsDisabled(row)) return
        this.selectList = [row]
        this.$nextTick(() => {
          if (this.$refs.queryTable) this.$refs.queryTable.setCurrentRow(row)
        })
      },
      // 表格选中
      handleSelectionChange(selection) {
        if(this.isMultiple) {
          /** 兜底：过滤掉已禁用的物料（防止通过程序选中） */
          this.selectList = (selection || []).filter((row) => !this.isGoodsDisabled(row))
          /** 若 selection 中包含禁用项，则主动清理勾选状态 */
          this.$nextTick(() => {
            if (!this.$refs.queryTable) return
            ;(selection || []).forEach((row) => {
              if (this.isGoodsDisabled(row)) this.$refs.queryTable.toggleRowSelection(row, false)
            })
          })
        }
      },
      /** 判断当前行是否允许勾选（多选列 selectable） */
      isRowSelectable(row) {
        return !this.isGoodsDisabled(row)
      },
      /** 判断某个物料是否应被禁用（已选过则禁用） */
      isGoodsDisabled(row) {
        /** 仅在多选模式下禁用重复选择 */
        if (!this.isMultiple) return false
        const goodsNum = row && row.goodsNum != null ? String(row.goodsNum) : ''
        return (this.excludeGoodsNums || []).map(String).includes(goodsNum)
      },
      // 获取货品类别树状
      initTree() {
        getGoodsTree({}).then(res => {
          this.treeData[0].child = res.data
        })
      },
      // 拿到货品
      initMaterial(num = null) {
        let params = {
          goodsType: num
        }
        getGoodsByMaterial(params).then(res => {
          this.queryList = res.data || []
          /** 切换类别后清空单选高亮与已选 */
          this.selectList = []
          this.$nextTick(() => {
            if (this.$refs.queryTable && !this.isMultiple) {
              this.$refs.queryTable.setCurrentRow(null)
            }
          })
        })
      },
      confirmList() {
        if(this.selectList.length < 1) {
          this.$message.error('请选择物料！')
          return
        }
        this.$emit('selectList', this.selectList)
        this.close()
      },

    },
    mounted() {
    }
  }
</script>

<style scoped lang="scss">
.tree-icon {
  margin-right: 8px;
  font-size: 16px;
}

/* 文件夹图标颜色 */
.el-icon-folder {
  color: #FFB74D;
}

.el-icon-folder-opened {
  color: #FF9800;
}

/* 文件图标颜色 */
.el-icon-document {
  color: #78909C;
}

.el-icon-picture {
  color: #F06292;
}

.el-icon-edit {
  color: #4FC3F7;
}

.el-icon-data-board {
  color: #4DB6AC;
}

/* 移除默认的展开/收起图标 */
.el-tree-node__expand-icon {
  display: none;
}

/* 自定义节点选中样式 */
.el-tree-node.is-current > .el-tree-node__content {
  background: linear-gradient(90deg, #e6f7ff, #f0f7ff);
  border-radius: 4px;
  border-left: 3px solid #1890ff;
}
.query_model {
  width: 100%;
  height: 600px;
}

/** 单选模式：当前行浅蓝高亮 */
::v-deep .query-table-single .el-table__body tr.current-row > td {
  background-color: #d9ecff !important;
}

/** 单选模式：行可点，鼠标小手 */
::v-deep .query-table-single .el-table__body-wrapper tbody tr {
  cursor: pointer;
}
</style>
