<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>
        <!-- personnelCapacity_add -->
        <el-button type="primary" @click="handleAdd" v-if="permission.personnelCapacity_add">新增</el-button>
      </template>
      <template #menu-right> </template>
      <template #menu="{ row }">
        <!-- personnelCapacity_edit -->
        <el-button type="text" @click="handleEdit(row)" v-if="permission.personnelCapacity_edit">修改</el-button>
      </template>

      <template #standardTime="scope">
        <span v-if="scope.row.partType == 0">
          {{ scope.row.standardTime }}
        </span>
        <span v-else>
          <p v-for="(item, index) in scope.row.abilityList" :key="index">
            {{ `${item.startNum}≤φ<${item.endNum}` }}{{ item.standardTime!=null?`,${item.standardTime}`:'' }}
          </p>
        </span>
      </template>
    </avue-crud>

    <!-- 新增 -->
    <addPersonnel
      v-if="showDialog"
      :showDialog="showDialog"
      :title="title"
      :rowData="rowData"
      @closeDialog="closeDialog"
    ></addPersonnel>
  </basic-container>
</template>

<script>
import {
  getListPersonAbility,
  removePersonAbility,
  addPersonAbility,
  updatePersonAbility,
  getSelectCertificateList,
} from '@/api/productionSchedulingPlan/basic';
import addPersonnel from './components/addPersonnel.vue';
import { mapGetters } from 'vuex';
export default {
  components: {
    addPersonnel,
  },
  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,  //personnelCapacity_delete
        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: 'workCenterId',
            search: true,
            sortable: 'custom',
            span: 12,
            type: 'select',
            filterable: true,
            dicUrl: '/blade-scheduling/workCenter/findList',
            props: {
              label: 'wcName',
              value: 'id',
            },
            change: (val, row) => {
              this.onChangeData(val.item, 'workCenterId');
            },
            rules: [
              {
                required: true,
                message: '请选择',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '作业中心',
            prop: 'workCenterName',
            search: false,
            sortable: 'custom',
            span: 12,
            hide: true,
            display: false,
          },
          {
            label: '工序',
            prop: 'processId',
            search: true,
            sortable: 'custom',
            span: 12,
            type: 'select',
            filterable: true,
            dicUrl: '/blade-scheduling/processSet/findList',
            props: {
              label: 'name',
              value: 'id',
            },
            rules: [
              {
                required: true,
                message: '请选择',
                trigger: 'blur',
              },
            ],
            change: (val, row) => {
              this.onChangeData(val.item, 'processId');
            },
          },
          {
            label: '工序',
            prop: 'processName',
            search: false,
            sortable: 'custom',
            span: 12,
            hide: true,
            display: false,
          },
          {
            label: '工艺能力',
            prop: 'craftId',
            search: true,
            sortable: 'custom',
            span: 12,
            type: 'select',
            filterable: true,
            dicUrl: '/blade-scheduling/craftAbility/findList',
            props: {
              label: 'caName',
              value: 'id',
            },
            rules: [
              {
                required: true,
                message: '请选择',
                trigger: 'blur',
              },
            ],
            change: (val, row) => {
              this.onChangeData(val.item, 'craftId');
            },
          },
          {
            label: '工艺能力',
            prop: 'craftName',
            search: false,
            sortable: 'custom',
            span: 12,
            hide: true,
            display: false,
          },
          {
            label: '统计类型',
            prop: 'type',
            search: false,
            sortable: 'custom',
            span: 12,
            type: 'select',
            rules: [
              {
                required: true,
                message: '请选择',
                trigger: 'blur',
              },
            ],
            dicData: [
              {
                label: '单个零件',
                value: '0',
              },
              {
                label: '订单',
                value: '1',
              },
            ],
          },
          {
            label: '额定工时（分钟/每人每个）',
            prop: 'standardTime',
            search: false,
            sortable: 'custom',
            span: 12,
            width: 250,
            labelWidth: 220,
            type: 'number',
            rules: [
              {
                required: true,
                message: '请输入',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '准备工时（分钟）',
            prop: 'prepareTime',
            search: false,
            sortable: 'custom',
            span: 12,
            labelWidth: 180,
            width: 180,
          },
          {
            label: '生产标识',
            prop: 'productIdent',
            search: false,
            sortable: 'custom',
            span: 12,
            // labelWidth: 180,
          },
          {
            label: '证书类型',
            prop: 'certificateId',
            search: true,
            sortable: 'custom',
            span: 12,
            type: 'select',
            hide: true,
            filterable: true,
            dicUrl: '/blade-scheduling/personAbility/selectCertificateList',
            props: {
              label: 'name',
              value: 'id',
            },
            change: (val, row) => {
              this.onChangeData(val.item, 'certificateId');
            },
          },
          {
            label: '证书类型',
            prop: 'certificateName',
            search: true,
            sortable: 'custom',
            span: 12,
            display: false,
          },
        ],
      },

      data: [],
      showDialog: false,
      title: '新增',
      rowData: {},
    };
  },
  computed: {
    ...mapGetters(['permission']),
  },
  created() { 
    this.option.delBtn = this.permission.personnelCapacity_delete ? true : false;
  },
  methods: {
    // 表格排序
    sortChange({ prop, order }) {
      if (!prop) {
        // 如果取消排序，清空排序参数
        this.query.orderByField = undefined;
        // this.query.isAsc = undefined;
        this.query.asc = undefined;
      } else {
        const orderByField = prop.replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase();
        if(order === 'ascending'){
          this.query.ascs = orderByField;
          this.query.descs = undefined;
        }else{
          this.query.descs = orderByField;
          this.query.ascs = undefined;
        }
        // this.query.orderByField = orderByField;
        // this.query.isAsc = order === 'ascending' ? true : false;
        // this.query.asc = order === 'ascending' ? true : false;
      }
      // // 重新加载数据
      this.onLoad(this.page, this.query);
    },
    handleAdd() {
      this.showDialog = true;
      this.title = '新增';
    },
    handleEdit(row) {
      this.showDialog = true;
      this.title = '修改';
      this.rowData = row;
    },
    closeDialog() {
      this.showDialog = false;
      this.onLoad(this.page, this.query);
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        this.form.processId = this.form.processId + '';
        this.form.craftId = this.form.craftId + '';
        this.form.workCenterId = this.form.workCenterId + '';
      }
      done();
    },
    onChangeData(val, type) {
      if (val && type == 'workCenterId') {
        this.form.workCenterName = val.wcName;
      }
      if (val && type == 'processId') {
        this.form.processName = val.name;
      }
      if (val && type == 'craftId') {
        this.form.craftName = val.caName;
      }
      if (val && type == 'certificateId') {
        this.form.certificateName = val.name;
      }
    },
    rowSave(row, done, loading) {
      if (row.productIdent != '' && row.certificateId == '') {
        loading();
        return this.$message.error('请选择证书类型');
      }
      addPersonAbility(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      console.log(
        row,
        row.productIdent != '' && (row.certificateId == '' || row.certificateId == undefined)
      );
      if (row.productIdent != '' && (row.certificateId == '' || row.certificateId == undefined)) {
        loading();
        return this.$message.error('请选择证书类型');
      }
      updatePersonAbility(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 removePersonAbility(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;
      getListPersonAbility(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.data.forEach(item => {
            if (item.partType != 0) {
              item.abilityList = JSON.parse(item.standardTime);
            }
          });
        }
      );
    },
  },
  mounted() {},
};
</script>
