<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    width="70%"
  >
    <el-card shadow="never">
      <user-search @search="reload" />

      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        :selection.sync="selection"
        @cell-click="cellClick"
        row-key="id"
      >
        <!-- 表头工具栏 -->
        <template v-slot:action="{ row }">
          <el-radio
            :disabled="
              selectWorkingProcess.taskParam.some((item) => item.id == row.id)
            "
            class="radio"
            v-model="radio"
            :label="row.id"
            ><i></i
          ></el-radio>
        </template>
      </ele-pro-table>
    </el-card>

    <div class="btns">
      <el-button type="primary" size="small" @click="selected">选择</el-button>
      <el-button size="small" @click="handleClose">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {
    workingProcedureSave,
    workingProcedureUpdate
  } from '@/api/material/BOM';
  import producetask from '@/api/technology/production';
  import userSearch from './user-search.vue';
  export default {
    components: {
      userSearch
    },
    data() {
      return {
        visible: false,
        title: '添加工序',
        type: '新增',
        // 表格列配置
        columns: [
          {
            prop: 'code',
            label: '工序编码',
            // sortable: 'custom',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },
          {
            prop: 'name',
            label: '工序名称',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },
          {
            align: 'center',
            prop: 'controlName',
            label: '工序控制码',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'workCenterName',
            label: '所属工作中心',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          }
        ],

        // 表格选中数据
        selection: [],
        processData: {},
        selectWorkingProcess: {},
        currentRow: {},
        current: {},
        radio: null,
        id: null
      };
    },
    methods: {
      /* 表格数据源 */
      async datasource({ page, limit, where, order }) {
        const res = await parameter.list({
          ...where,
          ...order,
          pageNum: page,
          size: limit
        });
        return res;
      },
      initColumns() {
        this.columns = [
          {
            prop: 'code',
            label: '工序编码',
            // sortable: 'custom',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },
          {
            prop: 'name',
            label: '工序名称',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },
          {
            align: 'center',
            prop: 'controlName',
            label: '工序控制码',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'workCenterName',
            label: '所属工作中心',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          }
        ];
      },
      open(item, selectWorkingProcess, type, currentRow) {
        this.type = type;
        if (
          Object.prototype.hasOwnProperty.call(
            selectWorkingProcess,
            'taskParam'
          )
        ) {
          this.selectWorkingProcess = selectWorkingProcess;
        } else {
          this.selectWorkingProcess = {
            taskParam: []
          };
        }

        this.currentRow = currentRow;
        this.processData = item;
        this.initColumns();
        this.current = {};
        this.radio = null;
        if (type === '新增') {
          this.columns = [
            {
              columnKey: 'selection',
              type: 'selection',
              width: 45,
              align: 'center',
              selectable: (row, index) => {
                return !this.selectWorkingProcess.taskParam.some(
                  (item) => item.id == row.id
                );
              },
              reserveSelection: true,
              fixed: 'left'
            }
          ].concat(this.columns);
        } else {
          this.columns = [
            {
              action: 'action',
              slot: 'action',
              align: 'center',
              label: '选择'
            }
          ].concat(this.columns);
        }
        this.visible = true;
      },
      // 单击获取id
      cellClick(row) {
        if (
          !this.selectWorkingProcess.taskParam.some((item) => item.id == row.id)
        ) {
          this.current = row;
          this.radio = row.id;
        }
      },
      /* 表格数据源 */
      async datasource({ page, limit, where, order }) {
        const res = await producetask.list({
          ...where,
          ...order,
          pageNum: page,
          size: limit
        });
        return res;
      },

      /* 刷新表格 */
      reload(where) {
        this.$refs.table.reload({ page: 1, where: where });
      },

      handleClose() {
        this.visible = false;
        this.$refs.table.setSelectedRows([]);
        this.selection = [];
      },
      selected() {
        if (this.type === '新增') {
          if (!this.selection.length) {
            this.$message.error('请至少选择一条数据');
            return;
          }
        } else {
          if (!this.current) {
            this.$message.error('请至少选择一条数据');
            return;
          }
        }
        if (this.selectWorkingProcess.taskParam.length > 0) {
          let taskParam = [];
          if (this.type === '新增') {
            taskParam = this.selection
              .map((item) => {
                return {
                  ...item,
                  versions: this.processData.versions,
                  status: this.processData.status
                };
              })
              .concat(this.selectWorkingProcess.taskParam);
          } else {
            taskParam = this.selectWorkingProcess.taskParam.map((item) => {
              if (item.id === this.currentRow.id) {
                return {
                  ...this.current,
                  versions: this.processData.versions,
                  status: this.processData.status
                };
              } else {
                return item;
              }
            });
          }
          workingProcedureUpdate({
            id: this.selectWorkingProcess.id,
            categoryId: this.processData.categoryId,
            bomCategoryId: this.processData.id,
            categoryCode: this.processData.categoryCode,
            taskParam
          }).then((data) => {
            this.$message.success('添加成功');
            this.$emit('chooseProcess');
            this.handleClose();
          });
        } else {
          workingProcedureSave({
            categoryId: this.processData.categoryId,
            bomCategoryId: this.processData.id,
            categoryCode: this.processData.categoryCode,
            taskParam: this.selection.map((item) => {
              return {
                ...item,
                versions: this.processData.versions,
                status: this.processData.status
              };
            })
          }).then((data) => {
            this.$message.success('添加成功');
            this.$emit('chooseProcess');
            this.handleClose();
          });
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .btns {
    text-align: center;
    padding: 10px 0;
  }
</style>
