<template>
  <ele-modal
    width="70%"
    :append-to-body="true"
    :close-on-click-modal="false"
    custom-class="ele-dialog-form"
    :title="type == 1 ? '质检项派单' : '质检项请托'"
    :visible.sync="visible"
    :maxable="true"
    @close="cancel"
  >
    <header-title title="质检项信息"></header-title>
    <ele-pro-table
      :needPage="false"
      :columns="tableColumns"
      :datasource="list"
      :selection.sync="selection"
      rowKey="id"
      ref="table"
    ></ele-pro-table>
    <header-title title="派单信息"></header-title>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      class="el-form-box"
      label-width="120px"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item
            :label="type == 1 ? '任务单号' : '质检项请托单号'"
            prop="code"
          >
            <el-input
              v-model="form.code"
              placeholder=" "
              disabled
            ></el-input> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="任务名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入"
            ></el-input> </el-form-item></el-col
      ></el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="执行部门" prop="executeDeptId">
            <deptSelect
              v-model="form.executeDeptId"
              @changeGroup="searchDeptNodeClick"
            /> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="执行人" prop="executeUserId">
            <el-select
              v-model="form.executeUserId"
              @change="changeExecutor"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in executorList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select> </el-form-item></el-col
      ></el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="要求完成时间" prop="requiredCompletionTime">
            <el-date-picker
              v-model="form.requiredCompletionTime"
              style="width: 100%"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder=" "
            >
            </el-date-picker> </el-form-item
        ></el-col>
      </el-row>
    </el-form>

    <template v-slot:footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        确认
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
  import {
    qualityInspectionItemDispatching,
    qualityInspectionItemRequest
  } from '@/api/inspectionProjectTask';
  import { getById } from '@/api/inspectionWork';
  import {
    getById as getQualityInspectionItemById,
    updateRequestentrust
  } from '@/api/inspectionProjectRequest';
  import { inspectionProjectStatus } from '@/enum/dict.js';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import { getUserPage } from '@/api/system/organization';
  const defaultForm = {
    id: null,
    executeDeptId: '',
    executeDeptName: '',
    executeUserId: '',
    executeUserName: '',
    name: '',
    code: '',
    qualityWorkOrderId: '',
    requiredCompletionTime: '',
    type: 1
  };
  export default {
    components: { deptSelect },

    data() {
      return {
        type: 1,
        pgaeName: '',
        form: { ...defaultForm },
        executorList: [],
        selection: [],
        list: [],
        tableColumns: [
          {
            width: 45,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            selectable: (row, index) => {
              return row.status == 0 || this.templateIdS.includes(row.id);
            }
          },
          {
            minWidth: 150,
            prop: 'qualitySchemeTemplateCode',
            align: 'center',
            label: '质检方案编码',
            showOverflowTooltip: true
          },
          {
            minWidth: 120,
            prop: 'qualitySchemeTemplateName',
            align: 'center',
            label: '质检方案名称',
            showOverflowTooltip: true
          },
          {
            minWidth: 100,
            prop: 'categoryLevelClassName',
            align: 'center',
            label: '质检类型',
            showOverflowTooltip: true
          },
          {
            minWidth: 130,
            prop: 'inspectionCode',
            align: 'center',
            label: '质检项编码',
            showOverflowTooltip: true
          },
          {
            minWidth: 120,
            prop: 'inspectionName',
            align: 'center',
            label: '质检项名称',
            showOverflowTooltip: true
          },
          {
            minWidth: 150,
            prop: 'defaultValue',
            align: 'center',
            label: '工艺参数',
            showOverflowTooltip: true
          },
          {
            minWidth: 150,
            prop: 'status',
            align: 'center',
            formatter: (row) => {
              return (
                inspectionProjectStatus.find(
                  (item) => item.value === row.status
                )?.label || ''
              );
            },

            label: '状态',
            showOverflowTooltip: true
          }
        ],
        rules: {
          executeDeptId: [
            { required: true, message: '请选择部门', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入任务名称', trigger: 'blur' }
          ],
          requiredCompletionTime: [
            { required: true, message: '请输入要求完成日期', trigger: 'blur' }
          ],
          executeUserId: [
            { required: true, message: '请选择人员', trigger: 'blur' }
          ]
        },
        templateIdS: [],
        loading: false,
        visible: false
      };
    },

    created() {},
    methods: {
      async open(row, type, pgaeName) {
        this.type = type;
        this.pgaeName = pgaeName;
        this.visible = true;
        this.templateIdS = [];
        if (pgaeName == 'inspectionProjectRequest') {
          this.form = await getQualityInspectionItemById(row.id);
          this.getUserList({ groupId: this.form.executeDeptId }, true);
          if (this.form.templateList.length) {
            this.templateIdS = this.form.templateList.map((item) => item.id);
          }
        } else {
          this.form.qualityWorkOrderId = row.id;
        }
        //获取工单质检方案
        await getById(this.form.qualityWorkOrderId).then((res) => {
          this.list = res.data.templateList;
          this.$nextTick(() => {
            this.$refs.table.setSelectedRowKeys(this.templateIdS);
          });
        });
      },
      searchDeptNodeClick(info, row) {
        if (info) {
          const params = { groupId: info };
          this.form.executeDeptId = info;
          this.form.executeDeptName = row.name;
          this.getUserList(params);
        } else {
          this.form.executeUserId = null;
          this.form.executeUserName = null;
          this.executorList = [];
        }
      },
      // 获取人员
      async getUserList(params, init) {
        try {
          let data = { pageNum: 1, size: -1 };

          if (params) {
            data = Object.assign(data, params);
          }
          const res = await getUserPage(data);
          this.executorList = res.list;
          if (init) {
            return;
          }
          this.form.executeUserId = null;
          this.form.executeUserName = null;
        } catch (error) {}
      },
      changeExecutor(val) {
        if (val) {
          this.form.executeUserId = val;
          this.form.executeUserName = this.executorList.find(
            (item) => item.id === val
          ).name;
        }
      },
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          if (this.selection.length == 0) {
            return this.$message.warning('请至少选择一条数据');
          }
          this.loading = true;
          let api =
            this.type == 1
              ? qualityInspectionItemDispatching
              : this.type == 2
              ? this.pgaeName == 'inspectionProjectRequest'
                ? updateRequestentrust
                : qualityInspectionItemRequest
              : '';

          api({
            ...this.form,
            detailList: this.selection.map((item) => {
              return { qualityPlanTemplateId: item.id };
            })
          })
            .then((msg) => {
              this.loading = false;
              this.$emit('reload');
              this.cancel();
            })
            .catch((e) => {
              this.loading = false;
            });
        });
      },
      cancel() {
        this.visible = false;
        this.$refs.form.clearValidate();
        this.form = { ...defaultForm };
        this.list = [];
      }
    }
  };
</script>

<style lang="scss" scoped></style>
