<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="danger" plain @click="handleDelete()">删除</el-button>
      </template>

      <template #menu-right>
        <span style="display: inline-flex; margin-right: 12px">
          <avue-select
            v-model="slectForm.wtName"
            placeholder="请选择能力类型"
            type="tree"
            :dic="slectDic"
            :filterable="true"
            :props="{
              label: 'dictValue',
              value: 'dictKey',
            }"
            style="width: 200px; margin-right: 12px"
          ></avue-select>
          <el-button type="primary" @click="batchSet()">批量设置</el-button>
          <el-button type="primary" @click="handleImport">导入</el-button>
        </span>
      </template>

      <template #localArea-form="{type}">
        <el-input v-if="type == 'add' || 'edit'" v-model="form.localArea" @input="validateSmallBat"></el-input>
      </template>

      <template #name="{ row }">
        <i :class="row.source" style="margin-right: 5px" />
        <span>{{ row.name }}</span>
      </template>
      <template #source="{ row }">
        <div style="text-align: center">
          <i :class="row.source" />
        </div>
      </template>
    </avue-crud>

    <!-- 导入 -->
    <basic-import v-if="isShowImport" title="导入" :isShow="isShowImport"
      templateUrl="/blade-desk/BA/craftAbility/downloadExcelTemplate"
      templateName="工艺能力模板.xls"
      importUrl="/blade-desk/BA/craftAbility/importExcel"
      @closeDialog="closeDialog"></basic-import>
  </basic-container>
</template>
<script>
import { mapGetters } from "vuex";
import {getList,getPlateSmall,addProcessAbility,updateProcessAbility,deleteProcessAbility,saveProcessAbility} from "@/api/basicData/processCapability"
import { getDictionary } from "@/api/system/dict";
import basicImport from "@/components/basic-import/main.vue";
import {getDecimal} from "@/utils/formatter";

export default {
  components: {
    basicImport
  },
  data() {
    return {
      isShowImport:false,
      slectForm: {
        wtName: "",
      },
      slectDic: [],
      form: {},
      query: {},
      loading: true,
      selectionList: [],
      parentId: "",
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      formOption: {
        menuSpan: 12,
        enter: true,
        menuBtn: false,
        column: [
          {
            label: "",
            prop: "wtName",
            type: "select",
            filterable: true,
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dicUrl: "/blade-system/dict/dictionary?code=ProcessCapabilityType",
          },
        ],
      },
      option: {
        columnSort: true,
        tip: false,
        height: "auto",
        calcHeight: 32,
        simplePage: false,
        searchShow: true,
        searchMenuSpan: 6,
        dialogWidth: 600,
        border: true,
        selection: true,
        viewBtn: true,
        addBtnIcon: " ",
        viewBtnIcon: " ",
        delBtnIcon: " ",
        editBtnIcon: " ",
        menuWidth: 120,
        dialogClickModal: false,
        excelBtn: true,
        viewBtn: false,
        editBtnText: "修改",
        refreshBtn: false,
        searchShowBtn: false,
        gridBtn: false,
        searchIndex: 3,
        searchIcon: true,
        searchLabelPosition: "left",
        searchLabelPosition: "left",
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: "center",
        gridBtn: false,
        searchMenuPosition: "right",
        align: "center",
        labelWidth:140,

        column: [
          {
            label: "编码",
            prop: "caCode",
            search: true,
            sortable: true,
            span:24,
            rules: [
              {
                required: true,
                message: "请输入编码",
                trigger: "blur",
              },
            ],
          },
          {
            label: "名称",
            prop: "caName",
            span:24,
            sortable: true,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入名称",
                trigger: "blur",
              },
            ],
          },
          // {
          //   label: "镀种小类",
          //   prop: "bpsId",
          //   type:'select',
          //   span:24,
          //   sortable: true,
          //   search: true,
          //   dicUrl:"/api/blade-desk/BA/PlatingSmall/listForSelect",
          //   props:{
          //     label:'bpsName',
          //     value:"id"
          //   },
          //   rules: [
          //     {
          //       required: true,
          //       message: "请选择镀种小类",
          //       trigger: "blur",
          //     },
          //   ],
          // },
          {
            label: "能力类型",
            span:24,
            prop: "wxLimit", 
            // bind: "bsWorkType.wtName",
            sortable: true,
            search: true,
            type: "select",
            filterable: true,
            formatter: (row, value, label, column) => {
              // -1 转换为空字符串
              if (value === -1 || value === '') {
                return '';
              }
              // 显示匹配的字典值
              const dictItem = this.slectDic.find(item => item.dictKey == value);
              return dictItem ? dictItem.dictValue : value;
            },
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dicUrl: "/blade-system/dict/dictionary?code=ProcessCapabilityType",
            rules: [
              {
                required: false,
                message: "请选择能力类型",
                trigger: "click",
              },
            ],
          },
          {
            label:"外协限制",
            prop:"wtId",
            type:"select",
            span:24,
            dicUrl: "/blade-system/dict/dictionary?code=WxLimit",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
          },
          {
            label:"厂内比例(%)",
            prop:"inRate",
            type: 'number',
            span:24,
            controls: false,
            max:100,
            rules: [
              {
                required: true,
                message: "请输入厂内比例",
                trigger: "change",
              },
            ],
            change: (val) => {
             console.log('val==========',val)
             this.form.outRate = 100 - val.value
            }
          },
          {
            label:"外协比例(%)",
            prop:"outRate",
            type: 'number',
            disabled:true,
            span:24,
            controls: false,
            rules: [
              {
                required: true,
                message: "请输入外协比例",
                trigger: "change",
              },
            ],
          },
          {
            label:"局部镀订单面积(dm²)",
            prop:"localArea",
            type: 'number',
            span:24,
            controls: false,
          },
          {
            label: "修改时间",
            prop: "updateTime",
            sortable: true,
            search: true,
            searchRange: true,
            display: false,
            hide:true,
            type: "date",
            valueFormat: "YYYY-MM-DD",
            format:"YYYY-MM-DD"
          },
          {
            label: "修改时间",
            prop: "updateTime",
            sortable: true,
            search: false,
            display: false,
            type: "date",

          },
        ],
      },
      data: [],
    };
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.menu_add, false),
        viewBtn: this.validData(this.permission.menu_view, false),
        delBtn: this.validData(this.permission.menu_delete, false),
        editBtn: this.validData(this.permission.menu_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  methods: {
    validateSmallBat(value){
      this.form.localArea = getDecimal(value,5)
    },
    getType(){
      getTypeData().then(res =>{

      })
    },
    closeDialog(val){
      this.isShowImport = false
      if(val){
        // 重新加载列表数据，导入后的数据可能需要特殊处理
        setTimeout(() => {
          this.onLoad()
        }, 500)
      }
    },
    // 导入前处理数据
    beforeUpload(file) {
      // 可以在这里添加文件验证逻辑
      console.log('导入文件:', file);
      return true;
    },
    // 点击导入按钮
    handleImport() {
      this.isShowImport = true
    },
    getDictionary() {
      getDictionary({ code: "ProcessCapabilityType" }).then((res) => {
        this.slectDic = res.data.data;
      });
    },
    // 批量设置
    batchSet() {
      if (this.selectionList.length === 0) {
        return this.$message.error("请先选择数据再进行操作！");
      }
      if (this.slectForm.wtName == "") {
        return this.$message.error("请先选择能力类型！");
      }
      if (this.slectForm.wtName) {
        this.$confirm("请确认此操作！", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() =>{
          saveProcessAbility({
            ids:this.selectionList.map(item => item.id),
            wxLimit:this.slectForm.wtName,
          }).then((res) => {
            if(res.data.code === 200){
              this.$message.success('设置成功');
              this.onLoad()
            }
          });
        })
      }
    },
    initData() {
      // getMenuTree().then(res => {
      //     const column = this.findObject(this.option.column, 'parentId');
      //     column.dicData = res.data.data;
      // });
    },
    handleAdd(row) {
      this.parentId = row.id;
      const column = this.findObject(this.option.column, "parentId");
      column.value = row.id;
      column.addDisabled = true;
      this.$refs.crud.rowAdd();
    },
    // 保存
    rowSave(row, done, loading) {
      const submitData = { ...row };
      // 处理空值，将空字符串转换为 -1
      if (submitData.wtId === '' || submitData.wtId === null || submitData.wtId === undefined) {
        submitData.wtId = '';
      }
      if (submitData.bpsId === '' || submitData.bpsId === null || submitData.bpsId === undefined) {
        submitData.bpsId = '';
      }
      if (submitData.wxLimit === '' || submitData.wxLimit === null || submitData.wxLimit === undefined) {
        submitData.wxLimit = '';
      }
      addProcessAbility(submitData).then(res =>{
        if(res.data.code == 200){
          this.$message.success("新增成功")
          this.onLoad()
          done()
        }
      }).catch(() => {
        loading();
      })
    },
    // 修改
    rowUpdate(row, index, done, loading) {
      const submitData = { ...row };
      // 处理空值，将空字符串转换为 -1
      if (submitData.wtId === '' || submitData.wtId === null || submitData.wtId === undefined) {
        submitData.wtId = '';
      }
      if (submitData.bpsId === '' || submitData.bpsId === null || submitData.bpsId === undefined) {
        submitData.bpsId = '';
      }
      if (submitData.wxLimit === '' || submitData.wxLimit === null || submitData.wxLimit === undefined) {
        submitData.wxLimit = '';
      }
      if(submitData.localArea === '' || submitData.localArea === null || submitData.localArea === undefined){
        submitData.localArea = ''
      }
      updateProcessAbility(submitData).then(res =>{
        if(res.data.code == 200){
          this.$message.success("修改成功")
          this.onLoad()
          done()
        }
      }).catch(() => {
        loading();
      })
    },
    rowDel(row, index, done) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteProcessAbility({
          ids:row.id
        }).then(res =>{
          if(res.data.code == 200){
            this.$message.success("删除成功")
            this.onLoad()
          }
        })
      })
    },
    handleDelete(){
      if(this.selectionList.length == 0){
        this.$message.error('请至少选择一条数据！')
        return
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteProcessAbility({
          ids:this.selectionList.map(item => item.id).join(',')
        }).then(res =>{
          if(res.data.code == 200){
            this.$message.success("删除成功")
            this.onLoad()
          }
        })
      })
      
    },
    // 重置
    searchReset() {
      this.query = {};
      this.parentId = 0;
      this.onLoad(this.page);
    },
    // 搜索
    searchChange(params, done) {
      this.query = params;
      this.parentId = "";
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    // 选中表格数据
    selectionChange(list) {
      this.selectionList = list;
      console.log(67676, this.selectionList);
    },
    //
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    // 打开弹框 前操作  打开表单前会执行beforeOpen方法
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
          // 处理 -1 转换为空字符串
          this.form.bpsId = (this.form.bpsId && this.form.bpsId !== -1) ? this.form.bpsId + '' : ''
          this.form.wtId = (this.form.wtId && this.form.wtId !== -1) ? this.form.wtId + '' : ''
      }
      done();
    },
    // 关闭 弹框  关闭表单前会执行beforeClose方法，
    beforeClose(done) {
      this.parentId = "";
      const column = this.findObject(this.option.column, "parentId");
      column.value = "";
      column.addDisabled = false;
      done();
    },
    // 切换 页码
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    // 切换页面 数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },

    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    // 加载页面数据
    onLoad(page, params = {}) {
      this.loading = true;
      let param = {
        descs:'CA_CODE',
        ...this.query,
        startTime:this.query.updateTime && this.query.updateTime.length != 0 && this.query.updateTime[0],
        endTime:this.query.updateTime && this.query.updateTime.length != 0 && this.query.updateTime[1],
      }
      const {updateTime,...searchParam} = param
      getList({
        current:this.page.currentPage,
        size:this.page.pageSize,
        ...searchParam
      }).then(res =>{
        res.data.data.records.map(item => {
          item.localArea = item.localArea == -1 ? '' : item.localArea
        })
        this.data = res.data.data.records
        this.page.total = res.data.data.total
        this.loading = false
      })
    },
  },

  mounted() {
    this.getDictionary();
  },
};
</script>
