<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model="form"
      v-model:page="page"
      ref="crud"
      @row-del="rowDel"
      @row-save="rowSave"
      @row-update="rowUpdate"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      :before-open="beforeOpen"
    >
      <template #menu-left>
        <el-button type="primary" @click="barchSet">批量维护</el-button>
        <el-button type="danger" @click="handleDelete">删除</el-button>
      </template>
      <template #menu-right>
        <el-button type="primary" @click="handleImport">导入 </el-button>
      </template>
      <template #levelNum-form="{ type }">
        <div style="width: 100%;">
          {{ console.log('levelNum-form 插槽渲染, type:', type, 'form.levelNum:', form.levelNum, 'form.levelNum类型:', typeof form.levelNum, '是否数组:', Array.isArray(form.levelNum), 'gradeData前3项:', gradeData.slice(0, 3)) }}
          <el-transfer
            v-if="type === 'add' || type === 'edit'"
            v-model="form.levelNum"
            :data="gradeData"
            :titles="['未选择', '已选择']"
            filterable
            :props="{
              key: 'key',
              label: 'label'
            }"
            style="text-align: left;"
          ></el-transfer>
        </div>
      </template>
    </avue-crud>
    <barchSet v-if="isOpen" :showDialog="isOpen" :list="selectionList" @closeDialog="closeDialog"></barchSet>
     <!-- 导入 -->
    <basic-import v-if="isShowImport" title="导入" :isShow="isShowImport"
      templateUrl="/blade-desk/BA/CoatingThickness/downloadExcelTemplate"
      templateName="镀层厚度对应表.xls"
      importUrl="/blade-desk/BA/CoatingThickness/importExcel"
     @closeDialog="closeDialog"></basic-import>
  </basic-container>
</template>
<script>
import barchSet from "./barchSet.vue";
import basicImport from '@/components/basic-import/main.vue'
import {getList,addThickness,updateThickness,deleteThickness} from "@/api/basicData/platThicknessRelation"
import {getProduction} from "@/api/basicData/ruleMaintenance"
export default {
  components: {
    barchSet,
    basicImport,
  },
  data() {
    return {
      isShowImport:false,
      selectionList: [],
      loading:false,
      query:{},
      gradeData: [],
      option: {
        height: "auto",
        calcHeight: 32,
        tip: false,
        // size: "medium",
        simplePage: true,
        searchShow: true,
        searchMenuSpan: 18,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: true,
        selection: true,
        viewBtn: false,
        delBtn: true,
        addBtn: true,
        editBtnText: "修改",
        viewBtnIcon: " ",
        delBtnIcon: " ",
        editBtnIcon: " ",
        viewBtnText: "详情",
        labelWidth: 120,
        menuWidth: 120,
        dialogWidth: 1040,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: false,
        filterBtn: true,
        searchShowBtn: false,
        columnSort: true,
        excelBtn: true,
        columnSort: true,
        index: false,
        showOverflowTooltip: true,
        searchLabelPosition: "left",
        searchLabelPosition: "left",
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: "center",
        gridBtn: false,
        searchMenuPosition: "right",
        addBtnIcon: " ",
        viewBtnIcon: " ",
        delBtnIcon: " ",
        editBtnIcon: " ",
        align: "center",

        column: [
          {
            label: "镀层代号",
            prop: "thicknessCode",
            sortable: true,
            filter: true,
            labelWidth: 150,
            span: 24,
            search: true,
          },
        
          {
            label: "是否以21E8-210开头",
            prop: "startF21e8",
            sortable: true,
            filter: true,
            span: 24,
            search: false,
            labelWidth: 150,
            type: "select",
            dicData: [
              {
                label: "是",
                value: 1,
              },
              {
                label: "否",
                value: 0,
              },
            ],
          },
          {
            label: "厚度",
            prop: "thickness",
            labelWidth: 150,
            sortable: true,
            filter: true,
            span: 24,
            search: false,
          },
            {
            label: "质量等级",
            prop: "levelNum",
            labelWidth: 150,
            sortable: true,
            filter: true,
            span: 24,
            search: false,
            addDisplay: true,
            editDisplay: true,
            formslot: true,
            formatter: (row, value, label, column) => {
              if (Array.isArray(value)) {
                return value.join(', ');
              }
              return value || '';
            },
          },
        ],
      },
      form: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      isOpen: false,
    };
  },
  mounted() {
    this.loadGradeData()
  },
  methods: {
    loadGradeData() {
      getProduction().then(res => {
        const rawData = res.data.data || []
        this.gradeData = rawData.map(item => ({
          key: String(item.qualityGrade),
          label: String(item.qualityGrade),
          qualityGrade: item.qualityGrade
        }))
        console.log('质量等级数据加载完成:', this.gradeData)
      })
    },
    beforeOpen(done, type) {
      console.log('beforeOpen 开始, type:', type)
      console.log('当前form.levelNum:', this.form.levelNum, '类型:', typeof this.form.levelNum)

      // 确保数据已加载
      if (this.gradeData.length === 0) {
        this.loadGradeData()
      }

      // 立即进行数据转换
      if (type == 'edit') {
        if (this.form.levelNum) {
          console.log('编辑模式，原始levelNum:', this.form.levelNum, '类型:', typeof this.form.levelNum)
          // 将 levelNum 转换为字符串数组，确保类型一致
          if (typeof this.form.levelNum === 'string') {
            this.form.levelNum = this.form.levelNum.split(',').map(item => String(item).trim()).filter(item => item !== '')
          } else if (typeof this.form.levelNum === 'number') {
            this.form.levelNum = [String(this.form.levelNum)]
          } else if (Array.isArray(this.form.levelNum)) {
            this.form.levelNum = this.form.levelNum.map(item => String(item).trim())
          }
          console.log('编辑模式，处理后levelNum:', this.form.levelNum, '是否数组:', Array.isArray(this.form.levelNum))
        } else {
          this.form.levelNum = []
        }
      } else if (type == 'add') {
        this.form.levelNum = []
      }

      console.log('beforeOpen 结束，form.levelNum:', this.form.levelNum, '是否数组:', Array.isArray(this.form.levelNum))
      // 先调用 done() 让对话框显示
      done()
      // 然后在 nextTick 中再次确认数据
      this.$nextTick(() => {
        console.log('nextTick 中的 form.levelNum:', this.form.levelNum, '是否数组:', Array.isArray(this.form.levelNum))
      })
    },
    // 点击导入按钮
    handleImport() {
      this.isShowImport = true
    },
    refreshChange(){
      this.onLoad()
    },
    // 搜索
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    // 重置
    searchReset() {
      this.query = {};
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    rowSave(row, done, loading){
      const params = {
        ...row,
        levelNum: Array.isArray(row.levelNum) ? row.levelNum.join(',') : row.levelNum
      }
      addThickness(params).then(res => {
        if(res.data.code == 200){
          this.$message.success('新增成功')
          this.onLoad()
          done()
        }
      })
    },
    rowUpdate(row, index, done, loading){
      const params = {
        ...row,
        levelNum: Array.isArray(row.levelNum) ? row.levelNum.join(',') : row.levelNum
      }
      updateThickness(params).then(res =>{
        if(res.data.code == 200){
          this.$message.success('修改成功')
          this.onLoad()
          done()
        }
      })
    },
    rowDel(row){
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteThickness({
          ids:row.id
        }).then(res =>{
          if(res.data.code == 200){
            this.$message.success('删除成功')
            this.onLoad()
          }
        })
      })
    },
    barchSet() {
      if(this.selectionList.length == 0){
        this.$message.error('请至少选择一条数据')
        return
      }
      this.isOpen = true;
    },
    closeDialog(val) {
      console.log('val---------',val)
      this.isOpen = false;
      this.isShowImport = false
      if(val){
        this.onLoad()
      }
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.error("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteThickness({
          ids:this.selectionList.map(item => item.id).join(',')
        }).then(res =>{
          if(res.data.code == 200){
            this.$message.success('删除成功')
            this.onLoad()
          }
        })
      });
    },
    // 多选
    selectionChange(list) {
      this.selectionList = list;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList({
        current:this.page.currentPage,
        size:this.page.pageSize,
        ...this.query
      }).then(res =>{
        this.data = res.data.data.records
        this.page.total = res.data.data.total
        this.loading = false
      })
    },
  },
};
</script>
<style lang="scss" scoped></style>
