<template>
  <div style="margin-top: 10px; padding: 0 20px">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <header-title title="基本信息" />

      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="放行单编码">
            <el-input v-model="form.code" disabled placeholder="系统自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="放行单名称" prop="name">
            <el-input v-model="form.name" disabled placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>

      <header-title title="物品清单" />
      <ele-pro-table
        ref="table"
        row-key="userId"
        :columns="ordersColumns"
        :datasource="form.orders"
      />

      <header-title title="生产放行规则" />
      <ele-pro-table
        row-key="id"
        :columns="detailsColumns"
        :datasource="scDetails"
      >
        <template #isPass="{ row }">
          <el-radio-group v-model="row.isPass" :disabled="isScDisabled">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </template>

        <template #remark="{ row }">
          <el-input
            v-model="row.remark"
            type="textarea"
            :rows="1"
            :disabled="isScDisabled"
            placeholder="请输入备注"
          />
        </template>
      </ele-pro-table>

      <header-title title="质检放行规则" />
      <ele-pro-table
        row-key="id"
        :columns="detailsColumns"
        :datasource="zjDetails"
      >
        <template #isPass="{ row }">
          <el-radio-group v-model="row.isPass" :disabled="isZjDisabled">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </template>

        <template #remark="{ row }">
          <el-input
            v-model="row.remark"
            type="textarea"
            :rows="1"
            :disabled="isZjDisabled"
            placeholder="请输入备注"
          />
        </template>
      </ele-pro-table>
    </el-form>
  </div>
</template>

<script>
  import dictMixins from '@/mixins/dictMixins';
  import { checklistrecordGetById } from '@/api/checklistrecord/index';

  /** 常量 */
  const CHECK_TYPE = {
    SC: 1, // 生产
    ZJ: 2 // 质检
  };

  export default {
    mixins: [dictMixins],

    props: {
      businessId: { default: '' },
      tasks: { type: Array, default: () => [] }
    },

    data() {
      const formBaseData = {
        id: null,
        approvalStatus: null,
        checklistType: 0,
        code: '',
        name: '',
        orders: [],
        details: [],
        workConclution: null,
        qualityConclution: null
      };

      return {
        loading: false,
        nodeType: '',
        formBaseData,
        form: JSON.parse(JSON.stringify(formBaseData)),
        rules: {}
      };
    },

    mounted() {
      const currentTask = this.tasks.find((v) => v.result === 1);
      this.nodeType = currentTask?.definitionKey || '';
      this.getCheckDetails(this.businessId);
    },

    watch: {
      'form.details': {
        deep: true,
        handler(details) {
          this.updateConclution(details);
        }
      }
    },

    computed: {
      /** 表格 columns 不再重复创建 */
      ordersColumns() {
        return [
          { type: 'index', width: 55, label: '序号', align: 'center' },
          { prop: 'batchNo', label: '批次号', align: 'center' },
          { prop: 'productCode', label: '产品编码', align: 'center' },
          { prop: 'productName', label: '产品名称', align: 'center' },
          { prop: 'workOrderCode', label: '生产工单号', align: 'center' },
          { prop: 'formingNum', label: '数量', align: 'center' },
          { prop: 'specification', label: '规格', align: 'center' },
          { prop: 'productModel', label: '型号', align: 'center' }
        ];
      },

      detailsColumns() {
        return [
          { type: 'index', width: 55, label: '序号', align: 'center' },
          { prop: 'mainIndicatorName', label: '指标名称', align: 'center' },
          { prop: 'isPass', label: '审核结果', slot: 'isPass' },
          { prop: 'remark', label: '备注', slot: 'remark' }
        ];
      },

      scDetails() {
        return this.form.details.filter((v) => v.checkType === CHECK_TYPE.SC);
      },

      zjDetails() {
        return this.form.details.filter((v) => v.checkType === CHECK_TYPE.ZJ);
      },

      isScDisabled() {
        return ['qualityApproval', 'leaderApproval'].includes(this.nodeType);
      },

      isZjDisabled() {
        return ['workOrderApproval', 'leaderApproval'].includes(this.nodeType);
      }
    },

    methods: {
      /** 获取详情 */
      async getCheckDetails(id) {
        this.loading = true;
        try {
          const data = await checklistrecordGetById(id);
          this.$util.assignObject(this.form, data);
          this.form.details.forEach((d) => (d._originIsPass = d.isPass));
        } finally {
          this.loading = false;
        }
      },

      /** 统一结论计算 */
      updateConclution(details) {
        const calc = (type) => {
          const list = details.filter((v) => v.checkType === type);
          if (!list.length) return null;
          return list.every((v) => v.isPass === 1) ? 1 : 0;
        };

        this.form.workConclution = calc(CHECK_TYPE.SC);
        this.form.qualityConclution = calc(CHECK_TYPE.ZJ);
      },

      /** 提交校验 */
      async getTableValue() {
        const typeMap = {
          workOrderApproval: CHECK_TYPE.SC,
          qualityApproval: CHECK_TYPE.ZJ
        };

        const needCheckType = typeMap[this.nodeType];
        if (needCheckType) {
          const invalid = this.form.details.find(
            (v) => v.checkType === needCheckType && ![0, 1].includes(v.isPass)
          );
          if (invalid) {
            this.$message.warning('请先完成所有放行规则的审核结果选择');
            return false;
          }
        }

        const changeList = this.form.details
          .filter((v) => v.isPass !== v._originIsPass)
          .map((v) => ({
            id: v.id,
            isPass: v.isPass,
            remark: v.remark
          }));

        if (changeList.some((v) => !v.remark?.trim())) {
          this.$message.warning('请填写备注');
          return false;
        }

        return {
          formData: this.form,
          changeList
        };
      }
    }
  };
</script>

<style scoped lang="scss">
  .detail-table {
    border: 1px solid #ebeef5;
    // 实线边框
    border-collapse: collapse;

    td {
      border: none;
      padding: 10px 15px;
      border: 1px solid #ebeef5;

      &:first-child {
        font-weight: 600;
        background: #f5f7fa;
        width: 130px;
        text-align: center;
      }
    }
  }

  .mask-box {
    position: relative;
    &::after {
      content: '';
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background: rgba(0, 0, 0, 0);
      cursor: pointer;
    }
  }
</style>
