<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-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      :before-open="beforeOpen"
      @sort-change="sortChange"
    >
      <template #menu-left> </template>
      <template #menu-right> </template>
      <template #menu="{ row }"> </template>

      <template #heatTreat="scope"> </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {
  getListOutsourceProcess,
  removeOutsourceProcess,
  addOutsourceProcess,
  updateOutsourceProcess,
  getDetailOutsourceProcess
} from '@/api/productionSchedulingPlan/basic';
import { mapGetters } from 'vuex';
export default {
  components: {},
  data() {
    return {
      form: {},
      selectionList: [],
      query: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        columnSort: true,
        tip: false,
        height: 'auto',
        calcHeight: 32,
        simplePage: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: true,
        selection: false,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        editBtnText: '修改',
        labelWidth: 120,
        menuWidth: 120,
        dialogWidth: 900,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: false,
        filterBtn: true,
        searchShowBtn: false,
        excelBtn: true,
        showOverflowTooltip: true,
        addBtnIcon: ' ',
        viewBtnIcon: ' ',
        delBtnIcon: ' ',
        editBtnIcon: ' ',
        gridBtn: false,
        searchLabelPosition: 'left',
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: 'left',
        gridBtn: false,
        searchMenuPosition: 'right',
        align: 'center',
        column: [
          {
            label: '工序',
            prop: 'processIds',
            search: false,
            sortable: 'custom',
            span: 12,
            type: 'select',
            filterable: true,
            multiple: false,
            hide: true,
            dicUrl: '/blade-scheduling/processSet/findList',
            props: {
              label: 'name',
              value: 'id',
            },
            rules: [
              {
                required: true,
                message: '请选择',
                trigger: 'blur',
              },
            ],
            change: (val, row) => {
              this.onChangeData(val, 'processIds', row);
            },
          },
          {
            label: '工序',
            prop: 'processName',
            search: false,
            sortable: 'custom',
            span: 12,
            display: false,
          },
          {
            label: '天数',
            prop: 'days',
            search: false,
            sortable: 'custom',
            span: 12,
            type: 'number',
            precision: 0,
            rules: [
              {
                required: true,
                message: '请输入',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '备注',
            prop: 'remarks',
            search: false,
            sortable: 'custom',
            span: 12,
          },
        ],
      },

      data: [],
    };
  },
  computed:{
    ...mapGetters(['permission']),
  },
  created(){
    console.log('this.permission',this.permission)
    this.option.addBtn = this.permission.oemProcess_add ? true : false;
    this.option.editBtn = this.permission.oemProcess_edit ? true : false;
    this.option.delBtn = this.permission.oemProcess_delete ? true : false;
  },
  methods: {
    // 表格排序
    sortChange({ prop, order }) {
      console.log('prop----------',prop)
      console.log('order----------',order)
      this.query.ascs = undefined;
      this.query.descs = undefined;
      const orderByFieldKey = order === 'ascending' ? 'ascs' : 'descs';
      const orderByField = prop.replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase();
      this.query[orderByFieldKey] = orderByField;
      // // 重新加载数据
      this.onLoad(this.page, this.query);
    },
    beforeOpen(done, type) {
      if (['edit'].includes(type)) {
        getDetailOutsourceProcess({id:this.form.id}).then(res => {
          this.form.processIds=res.data.data.processId.split(',')
        });
      }
      done();
    },
    onChangeData(val, type, row) {
      // if (val && type == 'workCenterId') {
      //   this.form.workCenterName = val.wcName;
      // }
      if (val.value && type == 'processIds') {
        if(!val.value){
            return false
        }
        // 筛选选中id对应的名称并拼接
        const selectedNames = val.value.map(id => {
            const item = val.dic.find(dic => dic.id === id);
            return item ? item.name : '';
          })
          .filter(name => name) // 过滤空值
          .join(',');

        // 根据场景赋值（新增/编辑）
        if (row) {
          // 编辑状态 - 给当前行赋值
          this.form.processName = selectedNames;
          this.form.processId = val.value.join(',');
        } else {
          // 新增状态 - 给表单赋值
          this.form.processName = selectedNames;
          this.form.processId = val.value.join(',');
        }
      }
      // if (val && type == 'craftId') {
      //   this.form.craftName = val.caName;
      // }
    },
    rowSave(row, done, loading) {
      addOutsourceProcess(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      updateOutsourceProcess(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return removeOutsourceProcess(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },

    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      // this.$refs.crud.toggleSelection();
    },

    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;
      getListOutsourceProcess(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        this.data = res.data.data.records;
        this.loading = false;
        this.page.total = res.data.data.total;
        this.selectionClear();
      });
    },
  },
  mounted() {},
};
</script>
