<template>
  <div class="app-container" style="overflow: hidden;">
    <splitpanes class="default-theme">
      <!-- 树结构：左侧面板 -->
      <pane size="16" style="overflow: auto;">
        <TreeComponent
          ref="treeComponent"
          :tree-data="categoryTreeData"
          :tree-props="treeProps"
          :node-key="nodeKey"
          :show-search="true"
          search-placeholder="请输入分类名称"
          :default-expand-all="true"
          :highlight-current="true"
          :loading="loadingTree"
          @node-click="handleTreeClick"
        >
          <!-- 自定义节点内容插槽 -->
          <template #node-content="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
            </span>
          </template>
        </TreeComponent>
      </pane>

      <!-- 物料管理：右侧面板 -->
      <pane size="84" style="overflow: auto;">
        <!-- 右侧内容保持不变 -->
        <div style="padding: 10px; display: flex; flex-direction: column;">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
            <!-- <el-form-item label="物料编码" prop="materialCode">
              <el-input
                v-model="queryParams.materialCode"
                placeholder="请输入物料编码"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item> -->
            <el-form-item label="SAP物料号" prop="sapNo">
              <el-input
                v-model="queryParams.sapNo"
                placeholder="请输入SAP物料号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="物料名称" prop="materialName">
              <el-input
                v-model="queryParams.materialName"
                placeholder="请输入物料名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>

            <el-form-item label="TS Code" prop="tsCode">
              <el-input
                v-model="queryParams.tsCode"
                placeholder="请输入TS Code"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="物料分类" prop="categoryNameInput">
              <el-input
                v-model="queryParams.categoryNameInput"
                placeholder="请输入物料分类"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="规格型号" prop="specification">
              <el-input
                v-model="queryParams.specification"
                placeholder="请输入规格型号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['inventory:materials:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['inventory:materials:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['inventory:materials:remove']"
              >删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"
                v-hasPermi="['inventory:materials:import']"
              >导入</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['inventory:materials:export']"
              >导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <el-table v-loading="loading" :data="materialsList" @selection-change="handleSelectionChange" :scroll-x="true">
            <!-- 表格列保持不变 -->
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="index" label="序号" align="center"/>
            <el-table-column label="SAP物料号" align="center" prop="sapNo" />
            <!-- <el-table-column label="物料编码" align="center" prop="materialCode" /> -->
            <el-table-column label="物料名称" align="center" prop="materialName" />
            <el-table-column label="TS Code" align="center" prop="tsCode" />
            <el-table-column label="物料分类" align="center" prop="categoryCode" >
              <template slot-scope="scope">
                {{ scope.row.displayCategory || categoryMap[scope.row.categoryCode] || scope.row.categoryCode }}
              </template>
            </el-table-column>
            <el-table-column label="危险类别ID" align="center" prop="hazardId" />
            <el-table-column label="规格型号" align="center" prop="specification" />
            <el-table-column label="计量单位" align="center" prop="materialUnit" />
            <el-table-column label="单位重量" align="center" prop="unitWeight" />
            <el-table-column label="包装重量" align="center" prop="packageWeight" />
            <el-table-column label="总重量" align="center" prop="totalWeight" />
            <el-table-column label="体积" align="center" prop="volume" />
            <el-table-column label="保质期天数" align="center" prop="shelfLifeDays" />
            <el-table-column label="存储温度要求" align="center" prop="storageTemperature" />
            <el-table-column label="特殊存储要求" align="center" prop="specialRequirements" />
            <el-table-column label="是否批次管理" align="center" prop="isBatchManaged">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isBatchManaged === 1 ? 'success' : 'info'" size="mini">{{ scope.row.isBatchManaged === 1 ? '是' : '否' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="是否序列号管理" align="center" prop="isSerialManaged">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isSerialManaged === 1 ? 'success' : 'info'" size="mini">{{ scope.row.isSerialManaged === 1 ? '是' : '否' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="最低库存" align="center" prop="minStockLevel" />
            <el-table-column label="最高库存" align="center" prop="maxStockLevel" />
            <el-table-column label="是否激活" align="center" prop="isActive">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isActive === 1 ? 'success' : 'info'" size="mini">{{ scope.row.isActive === 1 ? '是' : '否' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="风险等级" align="center" prop="riskLevel" />
            <el-table-column label="排序" align="center" prop="sortNo" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding" fixed="right" width="200">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['inventory:materials:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['inventory:materials:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </pane>
    </splitpanes>

    <!-- 添加或修改物料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <!-- <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
            </el-form-item> -->
            <el-form-item label="SAP物料号" prop="sapNo">
              <el-input v-model="form.sapNo" placeholder="请输入SAP物料号" />
            </el-form-item>
            <el-form-item label="TS Code" prop="tsCode">
              <el-input v-model="form.tsCode" placeholder="请输入TS Code" />
            </el-form-item>
            <el-form-item label="物料分类" prop="categoryCode">
              <el-select v-model="form.categoryCode" placeholder="请选择物料分类" clearable>
                <el-option
                  v-for="item in categoryTreeOptions"
                  :key="item.categoryCode"
                  :label="item.categoryName"
                  :value="item.categoryCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入规格型号" />
            </el-form-item>
            <el-form-item label="单位重量" prop="unitWeight">
              <el-input v-model="form.unitWeight" placeholder="请输入单位重量" />
            </el-form-item>
            <el-form-item label="总重量" prop="totalWeight">
              <el-input v-model="form.totalWeight" placeholder="请输入总重量" />
            </el-form-item>
            <el-form-item label="保质期天数" prop="shelfLifeDays">
              <el-input v-model="form.shelfLifeDays" placeholder="请输入保质期天数" />
            </el-form-item>
            <el-form-item label="特殊存储要求" prop="specialRequirements">
              <el-input v-model="form.specialRequirements" placeholder="请输入特殊存储要求" />
            </el-form-item>
            <el-form-item label="是否序列号管理" prop="isSerialManaged">
              <el-radio-group v-model="form.isSerialManaged">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="最高库存" prop="maxStockLevel">
              <el-input v-model="form.maxStockLevel" placeholder="请输入最高库存" />
            </el-form-item>
            <el-form-item label="排序" prop="sortNo">
              <el-input v-model="form.sortNo" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入物料名称" />
            </el-form-item>
            <el-form-item label="危险类别ID" prop="hazardId">
              <el-input v-model="form.hazardId" placeholder="请输入危险类别ID" />
            </el-form-item>
            <el-form-item label="计量单位" prop="materialUnit">
              <el-input v-model="form.materialUnit" placeholder="请输入计量单位" />
            </el-form-item>
            <el-form-item label="包装重量" prop="packageWeight">
              <el-input v-model="form.packageWeight" placeholder="请输入包装重量" />
            </el-form-item>
            <el-form-item label="体积" prop="volume">
              <el-input v-model="form.volume" placeholder="请输入体积" />
            </el-form-item>
            <el-form-item label="存储温度要求" prop="storageTemperature">
              <el-input v-model="form.storageTemperature" placeholder="请输入存储温度要求" />
            </el-form-item>
            <el-form-item label="是否批次管理" prop="isBatchManaged">
              <el-radio-group v-model="form.isBatchManaged">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="最低库存" prop="minStockLevel">
              <el-input v-model="form.minStockLevel" placeholder="请输入最低库存" />
            </el-form-item>
            <el-form-item label="是否激活" prop="isActive">
              <el-radio-group v-model="form.isActive">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="风险等级" prop="riskLevel">
              <el-input v-model="form.riskLevel" placeholder="请输入风险等级" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <import-excel
      ref="import"
      title="导入"
      import-url="/inventory/materials/import"
      template-url="inventory/materials/importTemplate"
      template-name="materials_importTemplate"
      @success="getList"
    />
  </div>
</template>

<script>
import { listMaterials, getMaterials, delMaterials, addMaterials, updateMaterials } from "@/api/inventory/materials"
import { listMaterials_category } from "@/api/inventory/materials_category"
import TreeComponent from '@/views/inventory/materials_category/treeComponent.vue'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import ImportExcel from "@/components/ImportExcel/index"

export default {
  name: "Materials",
  components: {
    TreeComponent,
    Splitpanes,
    Pane,
    Treeselect,
    ImportExcel
  },
  data() {
    return {
      // 树相关数据
      categoryTreeData: [],
      treeProps: {
        children: 'children',
        label: 'label',
        value: 'sid'
      },
      nodeKey: 'sid',
      loadingTree: false,

      // 分类映射和选项
      categoryMap: {},
      categoryNameToCodeMap: {},
      categoryTreeOptions: [],
      // 选中数组
      ids: [],
      single: true,
      multiple: true,

      // 显示搜索条件
      showSearch: true,

      // 总条数
      total: 0,

      // 物料表格数据
      materialsList: [],

      // 弹出层标题
      title: "",

      // 是否显示弹出层
      open: false,

      // 当前选中的树节点ID
      currentNodeId: null,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // materialCode: null,
        materialName: null,
        sapNo: null,
        tsCode: null,
        categoryCode: null,
        categoryNameInput: null,
        specification: null,
      },

      // 表单参数
      form: {
        id: null,
        // materialCode: null,
        sapNo: null,
        materialName: null,
        tsCode: null,
        categoryCode: null,
        hazardId: null,
        specification: null,
        materialUnit: null,
        unitWeight: null,
        packageWeight: null,
        totalWeight: null,
        volume: null,
        shelfLifeDays: null,
        storageTemperature: null,
        specialRequirements: null,
        isBatchManaged: 0,
        isSerialManaged: 0,
        minStockLevel: null,
        maxStockLevel: null,
        isUsed: 1,
        isActive: 1,
        riskLevel: null,
        sortNo: null,
        createUserCode: null,
        updateUserCode: null
      },

      // 表单校验
      rules: {
        // materialCode: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
        materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
        sapNo: [{ required: true, message: '请输入SAP物料号', trigger: 'blur' }],
        tsCode: [{ required: true, message: '请输入TS Code', trigger: 'blur' }]
      },

      loading: true
    }
  },
  async created() {
    await Promise.all([
      this.getCategoryTreeData(),
      this.getCategoryList()
    ]);
    this.getList()
  },
  methods: {
    async getCategoryList() {
      try {
        const response = await listMaterials_category({
          pageNum: 1,
          pageSize: 1000
        });

        if (response.rows && response.rows.length > 0) {
          // 正向映射：code → name
              this.categoryMap = {};
          // 反向映射：name → code（支持模糊匹配时用数组存储）
          this.categoryNameToCodeMap = {};

          response.rows.forEach(item => {
            if (item.isUsed !== 0 && item.isUsed !== '0') {
              this.categoryMap[item.categoryCode] = item.categoryName;
              // 反向映射：名称作为key，编码作为value（若名称重复可存数组）
            if (!this.categoryNameToCodeMap[item.categoryName]) {
                this.categoryNameToCodeMap[item.categoryName] = item.categoryCode;
              } else {
                // 处理名称重复的情况（可选）
               if (Array.isArray(this.categoryNameToCodeMap[item.categoryName])) {
                 this.categoryNameToCodeMap[item.categoryName].push(item.categoryCode);
              } else {
                  this.categoryNameToCodeMap[item.categoryName] = [this.categoryNameToCodeMap[item.categoryName], item.categoryCode];
                }
              }
            }
          });

          this.categoryTreeOptions = response.rows
            .filter(item => item.isUsed !== 0 && item.isUsed !== '0')
            .map(item => ({
              categoryCode: item.categoryCode,
              categoryName: item.categoryName
            }));
        }
      } catch (error) {
        console.error('获取分类列表失败:', error);
      }
    },
    /** 获取分类树数据 */
    async getCategoryTreeData() {
      this.loadingTree = true
      try {
        // 调用物料分类列表API获取所有分类
        const response = await listMaterials_category({
          pageNum: 1,
          pageSize: 1000 // 获取足够多的数据
        })

        if (response.rows && response.rows.length > 0) {
          // 过滤掉已禁用的分类
          const activeCategories = response.rows.filter(item =>
            item.isUsed !== 0 && item.isUsed !== '0'
          )

          // 构建树形结构
          this.categoryTreeData = this.buildTreeData(activeCategories)
          console.log('分类树数据:', this.categoryTreeData)
        }
      } catch (error) {
        console.error('获取分类树数据失败:', error)
      } finally {
        this.loadingTree = false
      }
    },

    /** 构建树形结构 */
    buildTreeData(list, parentId = null) {
      const result = list
        .filter(item => {
          if (parentId === null) {
            // 根节点：parentId为null、0或空
            return !item.parentId || item.parentId === 0 || item.parentId === '0'
          } else {
            // 子节点：parentId匹配
            return item.parentId == parentId
          }
        })
        .map(item => {
          const children = this.buildTreeData(list, item.id)
          return {
            ...item,
            sid: String(item.id),
            label: item.categoryName,
            children: children.length > 0 ? children : undefined
          }
        })

      return result
    },

    /** 处理树节点点击 */
    handleTreeClick(data) {
      console.log('点击树节点:', data)
      this.currentNodeId = data.sid

      // 更新查询参数，按选中的分类筛选物料
      this.queryParams.categoryCode = data.categoryCode
      this.queryParams.categoryNameInput = null // 清空名称输入
      this.queryParams.pageNum = 1
      this.getList()
    },



    /** 查询物料列表 */
    getList() {
      this.loading = true
      listMaterials(this.queryParams).then(response => {
        // 对物料列表中的分类字段做映射处理
        this.materialsList = response.rows
        .filter(item => item.isUsed !== 0 && item.isUsed !== '0')
        .map(item => ({
        ...item,
        // 兜底：如果映射表中没有，显示原始code并标注
        displayCategory: this.categoryMap[item.categoryCode] || `${item.categoryCode}（未匹配分类）`
      }));
        this.total = response.total;
      }).catch(() => {
        this.loading = false;
      }).finally(() => {
        this.loading = false;
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        // materialCode: null,
        materialName: null,
        sapNo: null,
        tsCode: null,
        categoryCode: null,
        hazardId: null,
        specification: null,
        materialUnit: null,
        unitWeight: null,
        packageWeight: null,
        totalWeight: null,
        volume: null,
        shelfLifeDays: null,
        storageTemperature: null,
        specialRequirements: null,
        isBatchManaged: 0,
        isSerialManaged: 0,
        minStockLevel: null,
        maxStockLevel: null,
        isUsed: 1,
        isActive: 1,
        riskLevel: null,
        sortNo: null,
        createUserCode: null,
        updateUserCode: null
      }
      this.$refs.form && this.$refs.form.resetFields()
    },

    /** 搜索按钮操作 */
    handleQuery() {
      // 清空原有分类编码
      this.queryParams.categoryCode = null;

          // 获取用户输入的分类名称
      const inputName = this.queryParams.categoryNameInput;
      if (inputName) {
        // 1. 精确匹配名称 → 编码
        const matchedCode = this.categoryNameToCodeMap[inputName];
        if (matchedCode) {
          // 若有多个编码（名称重复），取第一个
          this.queryParams.categoryCode = Array.isArray(matchedCode) ? matchedCode[0] : matchedCode;
        } else {
          // 2. 模糊匹配名称 → 编码（可选）
          const matchedCodes = Object.entries(this.categoryMap)
            .filter(([code, name]) => name.includes(inputName))
            .map(([code]) => code);
          if (matchedCodes.length > 0) {
            this.queryParams.categoryCode = matchedCodes[0]; // 或传多个（需后端支持）
          }
        }
      }

      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        // materialCode: null,
        materialName: null,
        sapNo: null,
        tsCode: null,
        categoryCode: null,
        categoryNameInput: null,
        specification: null,
      };
      this.currentNodeId = null;

      // 修复树形高亮重置：直接操作 TreeComponent 内部的 el-tree
      if (this.$refs.treeComponent && this.$refs.treeComponent.$refs.tree) {
        this.$refs.treeComponent.$refs.tree.setCurrentKey(null); // 清空选中
      } else if (this.$refs.treeComponent) {
        // 如果 TreeComponent 有自定义重置方法
        this.$refs.treeComponent.resetTree();
      }

      this.getList();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加物料"
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getMaterials(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改物料"
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const promise = this.form.id
            ? updateMaterials(this.form)
            : addMaterials(this.form)

          promise.then(response => {
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功")
            this.open = false
            this.getList()
          }).catch(error => {
            console.error('提交失败:', error)
          })
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm(row.id ? '是否确认删除编号为"' + row.sapNo + '"的数据项？' : '是否确认删除选中数量为"' + ids.length + '"的数据项？' ).then(() => {
        return delMaterials(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },

    /** 导入按钮操作 */
    handleImport() {
      this.$refs.import.show()
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('inventory/materials/export', {
        ...this.queryParams
      }, `materials_${new Date().getTime()}.xlsx`)
    },

    /** 表单重置方法 */
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  height: 100vh;
}

.custom-tree-node {
  font-size: 14px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
