<template>
  <ele-modal
    width="80%"
    :visible="visible"
    append-to-body
    custom-class="ele-dialog-form"
    :title="title"
    :close-on-click-modal="false"
    :before-close="handleBeforeClose"
    maxable
  >
    <header-title title="基本信息"></header-title>
    <el-form
      :model="addForm"
      :rules="formRules"
      ref="ruleFormRef"
      label-width="150px"
      v-loading="loading"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="记录规则名称" required>
            <el-input
              v-model="addForm.ruleName"
              placeholder="自动带出"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="记录规则分类" required>
            <DictSelection
              dictName="记录规则类型"
              clearable
              v-model="addForm.recordRulesClassify"
              disabled
            >
            </DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            v-if="ruleInfo && ruleInfo.classify == 3"
            label="关联设备"
          >
            <el-input
              v-model="addForm.deviceName"
              placeholder="自动带出"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item v-else label="车间区域" prop="workshopArea">
            <el-input
              v-model="addForm.workshopArea"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="检查完成时间" required prop="checkFinishTime">
            <el-date-picker
              v-model="addForm.checkFinishTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检查有效期" required prop="checkValidity">
            <el-input
              placeholder="请输入"
              v-model="addForm.checkValidity"
              type="text"
            >
              <template slot="append">
                <div style="width: 40px; box-sizing: border-box">
                  <el-form-item required prop="checkValidityUnit">
                    <DictSelection
                      dictName="检查有效期单位"
                      clearable
                      v-model="addForm.checkValidityUnit"
                      placeholder="单位"
                      style="width: auto"
                    >
                    </DictSelection>
                  </el-form-item>
                </div>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结论" required prop="conclution">
            <el-radio-group v-model="addForm.conclution">
              <el-radio :label="1">合格</el-radio>
              <el-radio :label="2">不合格</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <header-title title="检查项目"></header-title>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="addForm.details" style="width: 100%">
      <el-table-column type="index" label="序号" width="50"> </el-table-column>
      <el-table-column label="检查内容">
        <template slot-scope="scope">
          <div>
            {{ scope.row.paramValue || scope.row.productName }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="检查工具">
        <template slot-scope="scope">
          <div>
            {{ scope.row.toolNames }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="检查人">
        <template slot-scope="scope">
          <div
            @click="openSelectUser(scope.row)"
            style="display: flex; align-items: center; cursor: pointer"
          >
            <div>{{ showCheckUserNames(scope.row.checkUsers) }}</div
            ><i class="el-icon-caret-bottom"></i>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="检查情况">
        <template slot-scope="scope">
          <div>
            <el-input
              v-if="
                ruleInfo && (ruleInfo.classify == 3 || ruleInfo.classify == 4)
              "
              type="text"
              :rows="1"
              v-model="scope.row.checkStatusDesc"
            >
              <template
                v-if="ruleInfo.classify == 4 && scope.row.unitName"
                slot="append"
                >{{ scope.row.unitName }}</template
              >
            </el-input>
            <el-radio-group v-else v-model="scope.row.checkStatus">
              <el-radio :label="1">已检查</el-radio>
              <el-radio :label="0">未检查</el-radio>
            </el-radio-group>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="检查结果">
        <template slot-scope="scope">
          <div>
            <el-radio-group v-model="scope.row.checkResult">
              <el-radio :label="1">合格</el-radio>
              <el-radio :label="0">不合格</el-radio>
            </el-radio-group>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="描述">
        <template slot-scope="scope">
          <div>
            <el-input
              type="textarea"
              :rows="1"
              placeholder="请输入"
              v-model="scope.row.errorMsg"
            >
            </el-input>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="modal-footer">
        <el-button
          v-if="$hasPermission('mes:producetaskrecordrulesrecord:sus')"
          :loading="butLoading"
          type="primary"
          @click="submit('submit')"
          :disabled="productionInfo && productionInfo.executeStatus == 2"
        >
          一键报工
        </el-button>

        <template
          v-if="$hasPermission('mes:producetaskrecordrulesrecord:logicdelete')"
        >
          <el-popconfirm
            v-if="
              productionInfo &&
              productionInfo.recordId != null &&
              productionInfo.executeStatus == 1
            "
            title="您确定要清空缓存吗？"
            @confirm="clearCache"
          >
            <el-button slot="reference" :loading="butLoading" type="primary">
              清空缓存
            </el-button>
          </el-popconfirm>
        </template>

        <el-button
          v-if="$hasPermission('mes:producetaskrecordrulesrecord:saveorupdate')"
          :loading="butLoading"
          type="primary"
          @click="submit('cache')"
          :disabled="productionInfo && productionInfo.executeStatus == 2"
        >
          缓存
        </el-button>

        <el-button
          v-if="productionInfo && productionInfo.executeStatus == 2"
          @click="handleBeforeClose"
        >
          关闭
        </el-button>
      </div>
    </template>
    <!-- 选择用户 -->
    <SelectUser
      ref="SelectUserRef"
      v-model="showSelectUser"
      multipleSelect
      @selectUserFinished="selectUserFinished"
    ></SelectUser>
  </ele-modal>
</template>

<script>
  import { submit } from '@/api/entrust';
  import {
    recordRulesDetailPage,
    getRecordRulesDetail
  } from '@/api/recordRules/index.js';
  import DictSelection from '@/components/Dict/DictSelection.vue';
  import SelectUser from '@/components/select/SelectUser/index.vue';
  import {
    saveOrUpdateAndSubmit,
    saveOrUpdate,
    logicDelete,
    getById
  } from '@/api/producetaskrecordrulesrecord/index';
  import { row } from 'mathjs';

  export default {
    components: { SelectUser },
    emits: ['reload'],
    props: {
      isTempRecord: {
        type: Number,
        default: 0
      }
    },
    data() {
      const formDate = {
        id: null,
        workshopArea: '',
        checkFinishTime: '',
        checkValidity: null,
        checkValidityUnit: '',
        conclution: null,
        isTempRecord: this.isTempRecord,
        details: [],
        deviceId: 0,
        deviceName: '',
        batchNo: '',
        executeMethod: 0,
        formingNum: 0,
        itemType: 0,
        produceRoutingId: 0,
        produceRoutingName: '',
        produceTaskConfigId: 0,
        produceTaskId: 0,
        produceTaskName: '',
        productCode: '',
        productModel: '',
        productName: '',
        recordRulesClassify: null,
        ruleId: 0,
        ruleName: '',
        reportWorkType: 0,
        specification: '',
        workOrderCode: '',
        workOrderId: 0
      };

      return {
        visible: false,
        formDate,
        addForm: JSON.parse(JSON.stringify(formDate)),
        formRules: {
          checkFinishTime: [
            { required: true, message: '请选择检查完成时间', trigger: 'blur' },
            { required: true, message: '请选择检查完成时间', trigger: 'change' }
          ],
          conclution: [
            { required: true, message: '请选择结论', trigger: 'blur' },
            { required: true, message: '请选择结论', trigger: 'change' }
          ],
          checkValidity: [
            { required: true, message: '请输入检查有效期', trigger: 'blur' },
            { required: true, message: '请输入检查有效期', trigger: 'change' }
          ],
          checkValidityUnit: [
            {
              required: true,
              message: '请选择检查有效期单位',
              trigger: 'blur'
            },
            {
              required: true,
              message: '请选择检查有效期单位',
              trigger: 'change'
            }
          ]
        },
        productionInfo: null,
        list: [],
        ruleInfo: null,
        showSelectUser: false,
        currentRow: null,
        butLoading: false,
        // 工艺路线
        workOrderInfo: null,
        // 加载中 loading
        loading: false
      };
    },
    computed: {
      title() {
        if (this.ruleInfo) {
          switch (this.ruleInfo.classify) {
            case 1:
              return '清场清洁类记录表';
            case 2:
              return '车间环境类记录表';

            default:
              return '设备检测类记录表';
          }
        }
        return '类记录表';
      }
    },
    methods: {
      open(productionInfo, workOrderInfo) {
        console.log(
          'productionInfo, workOrderInfo',
          productionInfo,
          workOrderInfo
        );
        this.visible = true;
        this.productionInfo = productionInfo;
        this.workOrderInfo = workOrderInfo;

        // 存在缓存记录
        if (this.productionInfo.recordId != null) {
          // 查询详情
          this.getCacheInfo();
        } else {
          this.addForm.batchNo = workOrderInfo.batchNo;
          this.addForm.executeMethod = productionInfo.executeMethod;
          this.addForm.formingNum = workOrderInfo.formingNum;
          this.addForm.itemType = productionInfo.itemType;
          this.addForm.produceRoutingId = workOrderInfo.produceRoutingId;
          this.addForm.produceRoutingName = workOrderInfo.produceRoutingName;
          this.addForm.produceTaskConfigId = productionInfo.produceTaskConfigId;
          this.addForm.produceTaskId = productionInfo.produceTaskId;
          this.addForm.produceTaskName = productionInfo.produceTaskName;
          this.addForm.productCode = workOrderInfo.productCode;
          this.addForm.productModel = workOrderInfo.model;
          this.addForm.productName = workOrderInfo.productName;
          this.addForm.reportWorkType = productionInfo.reportWorkType;
          this.addForm.specification = workOrderInfo.specification;
          this.addForm.workOrderCode = workOrderInfo.code;
          this.addForm.workOrderId = workOrderInfo.id;

          this.getRuleList();
        }

        console.log('this.productionInfo', this.productionInfo);
        console.log('this.addForm', this.addForm);
        this.getRuleInfo();
      },
      // 获取详情
      async getCacheInfo() {
        this.loading = true;
        try {
          const data = await getById(this.productionInfo.recordId);
          console.log('dat 缓存', data);
          this.$util.assignObject(this.addForm, data);
          this.addForm.recordRulesClassify += '';
          if (this.addForm.details?.length == 0) {
            this.getRuleList();
          }
          this.loading = false;
        } catch (error) {
          this.loading = false;
        }
      },
      // 规则信息
      async getRuleInfo() {
        const data = await getRecordRulesDetail(this.productionInfo.ruleId);
        this.ruleInfo = data;
        console.log('this.ruleInfo', this.ruleInfo);
        if (this.productionInfo.recordId == null) {
          // 赋值表单信息
          this.addForm.recordRulesClassify = this.ruleInfo.classify + '';
          this.addForm.ruleId = this.ruleInfo.id;
          this.addForm.ruleName = this.ruleInfo.name;
          this.addForm.deviceId = this.ruleInfo.deviceId;
          this.addForm.deviceName = this.ruleInfo.deviceName;
        }
      },
      // 查询记录规则 事项列表
      async getRuleList() {
        const { list } = await recordRulesDetailPage({
          rulesId: this.productionInfo.ruleId,
          pageNum: 1,
          size: 9999
        });
        // 添加必要参数
        this.addForm.details = list.map((i) => {
          return {
            ...i,
            id: null,
            checkResult: null,
            checkStatus: null,
            checkStatusDesc: i.defaultValue || '',
            errorMsg: '',
            checkUsers: [],
            paramValue: i.paramValue,
            toolNames: i.tools.map((i) => i.toolName).join(',')
          };
        });
        console.log('this.addForm 添加规则', this.addForm, list);
      },
      openSelectUser(row) {
        this.currentRow = row;
        console.log('row', row);
        this.showSelectUser = true;
      },
      handleBeforeClose() {
        this.addForm = JSON.parse(JSON.stringify(this.formDate));
        console.log('this.$refs.ruleFormRef', this.addForm);
        this.$refs.ruleFormRef?.clearValidate();
        this.$nextTick(() => {
          this.visible = false;
        });
      },

      selectUserFinished(userInfo) {
        console.log('userInfo', userInfo);
        this.currentRow.checkUsers = userInfo.map((i) => {
          // 构建参数和接口的对应上
          return { ...i, userName: i.name, userId: i.id };
        });
      },
      showCheckUserNames(userList) {
        if (userList.length == 0) return '请选择部门-选择员工';

        return userList
          .map((i) => {
            return i.groupName + '-' + i.userName;
          })
          .join(',');
      },
      // 提交
      submit(type) {
        // 验证表单
        this.$refs.ruleFormRef.validate(async (valid) => {
          if (!valid) {
            return;
          }

          // 报工需要验证 缓存不验证
          if (type == 'submit') {
            // 验证检查项目
            const detailRequired = this.addForm.details.some((i) => {
              let qk = false;
              if (this.ruleInfo.classify == 3) {
                qk = Boolean(i.checkStatusDesc);
              } else {
                qk = i.checkStatus != null;
              }

              return i.checkResult == null || !qk || i.checkUsers?.length == 0;
            });

            if (detailRequired) {
              return this.$message.warning(
                '请先完善 检查人、检查情况、检查结果 内容！'
              );
            }
          }

          console.log('this.addForm', this.addForm);

          // 提交
          this.butLoading = true;
          try {
            if (type == 'submit') {
              await saveOrUpdateAndSubmit(this.addForm);
              this.$message.success('报工成功！');
            } else {
              const id = await saveOrUpdate(this.addForm);
              this.addForm.id = id;
              this.$message.success('缓存成功！');
            }
            this.butLoading = false;

            // 返回
            this.$emit('reload');

            this.handleBeforeClose();
          } catch (error) {
            this.butLoading = false;
          }
        });
      },
      async clearCache() {
        try {
          this.butLoading = true;
          await logicDelete(this.productionInfo.recordId);
          this.butLoading = false;
          this.productionInfo.recordId == null;
          this.addForm.workshopArea = '';
          this.addForm.checkFinishTime = null;
          this.addForm.checkValidity = null;
          this.addForm.checkValidityUnit = null;
          this.addForm.conclution = null;
          this.addForm.id = null;

          this.getRuleList();
          this.$message.success('缓存清空成功！');
          this.productionInfo.executeStatus = 0;
          if (this.addForm.isTempRecord) {
            this.handleBeforeClose();
          }
          this.$emit('reload');
        } catch (error) {
          this.butLoading = false;
        }
      }
    }
  };
</script>

<style scoped lang="scss">
  .modal-body {
    padding: 16px;
    min-height: 100px;
  }
  .modal-footer {
    display: flex;
    align-items: center;
    gap: 10px;
    justify-content: flex-end;
  }

  .el-form-item .el-form-item {
    margin-bottom: -5px;
  }
</style>
