<template>
  <div>
    <el-select style="margin: 10px;relative;left:20%;" v-model="queryParams.planId" placeholder="请选择检查计划"
               @change="handleChangePlan"
    >
      <el-option

        v-for="dict in PlanOptions"
        :key="dict.planId"
        :label="dict.planName"
        :value="dict.planId"
      />
    </el-select>
    <div style="width: 1000px;position: relative;left:20%;">
      <el-table :data="materialList">
        <!-- 编号列 -->
        <el-table-column prop="materialsId" label="编号"></el-table-column>
        <!-- 物资类型列 -->
        <el-table-column prop="materialsTypeName" label="物资类型"></el-table-column>
        <!-- 物资名称列 -->
        <el-table-column prop="materialsName" label="物资名称"></el-table-column>
        <!-- RFID列 -->
        <el-table-column prop="materialsRfid" label="RFID"></el-table-column>

        <!-- 正常 -->
        <el-table-column label="正常">
          <template slot-scope="scope">
    <span
      class="status-icon"
      :class="{'selected': scope.row.value === 1}"
      @click="toggleValue(scope.row, 1)"
    >
      {{ scope.row.value === 1 ? '✔️' : '✅' }}
    </span>
          </template>
        </el-table-column>

        <!-- 过期 -->
        <el-table-column label="过期">
          <template slot-scope="scope">
    <span
      class="status-icon"
      :class="{'selected': scope.row.value === 2}"
      @click="toggleValue(scope.row, 2)"
    >
      {{ scope.row.value === 2 ? '🚷' : '⚠️' }}
    </span>
          </template>
        </el-table-column>

        <!-- 损坏 -->
        <el-table-column label="损坏">
          <template slot-scope="scope">
    <span
      class="status-icon"
      :class="{'selected': scope.row.value === 3}"
      @click="toggleValue(scope.row, 3)"
    >
      {{ scope.row.value === 3 ? '🚫' : '🛠️' }}
    </span>
          </template>
        </el-table-column>


        <!-- 措施列 -->
        <el-table-column label="措施">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.measure"
              placeholder="请输入措施"
            >
            </el-input>
          </template>
        </el-table-column>
      </el-table>

      <!-- 提交按钮 -->
      <el-button @click="submitData" style="margin: 10px;position: relative;left:43%;" type="primary">提交</el-button>
    </div>
  </div>
</template>
<script>
import {
  getIsMaterialsCabinets,
  listMaterials,
  selectMaterialsById,
  updateIsMaterialById, insertIsMaterialsCheckRecord
} from '@/api/mes/material/information'
import { listPlan, selectPlanById } from '@/api/mes/material/plan'

export default {
  name: 'demo4',
  data() {
    return {
      queryParams: {
        current: 1,
        size: -1
      },
      PlanOptions: null,
      materialList: [],//检查的物资列表
      measure: ''
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      listPlan(this.queryParams).then(res => {
        console.log(res, '检查计划')
        this.PlanOptions = res.data.records.map(item => {
          return {
            planId: item.planId,
            planName: item.planName
          }
        })
      })
    },
    handleChangePlan(value) {
      selectPlanById(value).then(res => {
        console.log(res, '拿到选中的检查计划')

        const cabinetIds = res.data.cabinetIds || [] // 确保 cabinetIds 存在
        if (cabinetIds.length === 0) {
          console.log('没有 cabinetIds，无需查询')
          return
        }

        this.materialList = [] // 每次查询前清空数组

        // 遍历 cabinetIds 并行查询 listMaterials
        Promise.all(cabinetIds.map(id => this.fetchMaterialsByCabinetId(id)))
          .then(results => {
            const allData = results.flat(); // 合并所有返回的数据
            console.log(allData, '所有查询结果');

            // 添加 value 字段并给它一个默认值
            allData.forEach(item => {
              item.value = 0; // 默认设置为正常状态
            });

            this.materialList = allData; // 保存到 materialList 中

          })
          .catch(error => {
            console.error('查询物资数据出错', error)
          })
      })
    },

    // 按单个 cabinetId 查询物资数据
    fetchMaterialsByCabinetId(id) {
      // 搜索对应检查记录的检查物资柜物资 而且是在物资柜中的数据
      const params = { current: 1, size: -1, materialsCabinetId: id, loanState:'1'}
      return new Promise((resolve, reject) => {
        listMaterials(params)
          .then(res => {
            console.log(res, `cabinetId: ${id} 的物资数据`)
            resolve(res.data.records || []) // 确保返回数组
          })
          .catch(error => {
            console.error(`查询 cabinetId: ${id} 的数据失败`, error)
            reject(error)
          })
      })
    },
    // 更新状态和原因
    toggleValue(row, newValue) {
      console.log(row,'我点击了')
      // 如果点击的是当前状态，则重置回“正常”状态（value=1）
      row.value = row.value === newValue ? 1 : newValue;

      // 解析 value 对应的 status 和 reason
      const mapping = {
        1: { status: 0, reason: 0 }, // 正常
        2: { status: 1, reason: 2 }, // 过期
        3: { status: 1, reason: 1 }, // 损坏
      };

      row.status = mapping[row.value].status;
      row.reason = mapping[row.value].reason;
    },

    // 提交数据
    submitData() {
      // 将表格中的数据转换成符合要求的格式
      const submitData = this.materialList.map(item => ({
        planId: this.queryParams.planId,
        materialsId: item.materialsId,
        materialsTypeName: item.materialsTypeName,
        materialsName: item.materialsName,
        materialsRfid: item.materialsRfid,
        status: item.status,
        reason: item.reason,
        measure: item.measure,
        cabinetId: item.materialsCabinetId
      }))

      // 输出最终的数据（此处可以进行实际的提交操作）
      console.log(submitData)
      insertIsMaterialsCheckRecord(submitData).then(res => {
        console.log(res, '新增的结果')
        if (res.data) {
          this.$message.success('物资检查完成')
        } else {
          this.$message.error('提交失败')
        }
      })
    }
  }
//    methods结束
}
</script>
<style scoped lang="scss">
.status-icon {
  display: inline-block;
  font-size: 20px;
  cursor: pointer;
  color: gray;
  transition: color 0.3s;
}

.status-icon.selected {
  color: blue;
}

</style>
