<template>
  <div class="bg-check-container">
    <!-- 加载中 -->
    <div v-if="loading" class="success-wrapper">
      <el-icon class="is-loading" :size="48" color="#3b82f6"><Loading /></el-icon>
      <p style="margin-top:16px;color:#666;">加载中...</p>
    </div>
    <!-- 提交成功提示 -->
    <div v-else-if="submitted" class="success-wrapper">
      <el-icon class="success-icon" :size="64" color="#67c23a"><CircleCheckFilled /></el-icon>
      <h2 class="success-title">提交成功</h2>
      <p class="success-desc">感谢您的真实填写与支持，背调反馈已成功提交！</p>
      <p class="success-hint">您可以安全关闭此页面</p>
    </div>

    <template v-else>
    <div class="bg-header">
      <h1 class="header-title">背景调查报告</h1>
    </div>
    
    <div class="form-wrapper">
      <el-form ref="formRef" :model="form" :rules="rules" class="word-style-form">
        <table class="report-table" border="1" cellspacing="0" cellpadding="0">
          <thead>
            <tr>
              <th width="15%">调查项目</th>
              <th width="35%">调查内容</th>
              <th width="20%">核实结果</th>
              <th width="30%">备注/信息来源</th>
            </tr>
          </thead>
          <tbody>
            <!-- 候选人基本信息 -->
            <tr>
              <td><strong>候选人基本信息</strong></td>
              <td class="content-cell">
                <div class="form-row"><span class="label">姓名：</span><el-input v-model="form.candidateName" disabled class="noline-input" /></div>
                <div class="form-row"><span class="label">应聘职位：</span><el-input v-model="form.applyPosition" disabled class="noline-input" /></div>
                <div class="form-row"><span class="label">调查时间：</span><el-date-picker v-model="form.checkTime" type="date" class="noline-input" /></div>
              </td>
              <td></td>
              <td></td>
            </tr>
            <!-- 学历核实 -->
            <tr>
              <td><strong>学历核实</strong></td>
              <td class="content-cell">
                <div class="form-row"><span class="label">毕业院校：</span><el-input v-model="form.gradSchool" class="noline-input" /></div>
                <div class="form-row"><span class="label">学历证书编号：</span><el-input v-model="form.eduCertNo" class="noline-input" /></div>
                <div class="form-row"><span class="label">学信网核实：</span><el-input v-model="form.eduVerifyStatus" class="noline-input" /></div>
              </td>
              <td class="center-cell">
                 <el-form-item prop="eduVerifyResult" style="margin-bottom:0">
                   <el-radio-group v-model="form.eduVerifyResult" class="vertical-radio">
                    <el-radio label="属实">属实</el-radio>
                    <el-radio label="不属实">不属实</el-radio>
                    <el-radio label="无法核实">无法核实</el-radio>
                  </el-radio-group>
                 </el-form-item>
              </td>
              <td></td>
            </tr>
            <!-- 最近工作单位 -->
            <tr>
              <td><strong>最近工作单位（上家公司）</strong></td>
              <td class="content-cell">
                <div class="form-row"><span class="label">公司名称：</span><el-input v-model="form.companyName" class="noline-input" /></div>
                <div class="form-row"><span class="label">任职时间：</span><el-date-picker v-model="form.workPeriod" type="daterange" class="noline-input" /></div>
                <div class="form-row"><span class="label">担任职务：</span><el-input v-model="form.position" class="noline-input" /></div>
                <div class="form-row"><span class="label">最后薪酬：</span><el-input v-model="form.lastSalary" class="noline-input" /></div>
                <div class="form-row"><span class="label">离职原因：</span><el-input v-model="form.leaveReasonVerify" type="textarea" autosize class="noline-input flex-1" /></div>
              </td>
              <td class="center-cell">
                 <el-form-item prop="companyVerifyResult" style="margin-bottom:0">
                   <el-radio-group v-model="form.companyVerifyResult" class="vertical-radio">
                    <el-radio label="属实">属实</el-radio>
                    <el-radio label="部分属实">部分属实</el-radio>
                    <el-radio label="不属实">不属实</el-radio>
                  </el-radio-group>
                 </el-form-item>
              </td>
              <td class="content-cell">
                <div></div>
                <el-input v-model="form.attachment1Remark" type="textarea" :rows="4" class="noline-input" placeholder="请输入备注" />
              </td>
            </tr>
            <!-- 工作表现评估 -->
            <tr>
              <td><strong>工作表现评估</strong></td>
              <td class="content-cell">
                <div class="eval-section"><strong>上级评价：</strong></div>
                <div class="form-row"><span class="label">总体优势：</span><el-input v-model="form.leaderEvalAdvantage" class="noline-input" /></div>
                <div class="form-row"><span class="label">待改进方面：</span><el-input v-model="form.leaderEvalImprove" class="noline-input" /></div>
                <div class="form-row"><span class="label">专业能力：</span><el-input v-model="form.leaderEvalProf" class="noline-input" /></div>
                <div class="form-row"><span class="label">工作态度：</span><el-input v-model="form.leaderEvalAttitude" class="noline-input" /></div>
                <div class="form-row"><span class="label">团队协作：</span><el-input v-model="form.leaderEvalTeam" class="noline-input" /></div>
                <div class="form-row"><span class="label">职业操守：</span><el-input v-model="form.leaderEvalMorals" class="noline-input" /></div>
                <div class="eval-section"><strong>同事评价：</strong></div>
                <div class="form-row"><span class="label">合作顺畅度：</span><el-input v-model="form.colleagueEvalTeamwork" class="noline-input" /></div>
                <div class="form-row"><span class="label">专业能力评价：</span><el-input v-model="form.colleagueEvalProf" class="noline-input" /></div>
                <div class="eval-section"><strong>HR评价：</strong></div>
                <div class="form-row"><span class="label">是否有违纪/纠纷：</span><el-input v-model="form.hrEvalDispute" class="noline-input" /></div>
                <div class="form-row"><span class="label">离职交接情况：</span><el-input v-model="form.hrEvalTransfer" class="noline-input" /></div>
              </td>
              <td class="center-cell">
                 <el-form-item prop="evalResult" style="margin-bottom:0">
                   <el-radio-group v-model="form.evalResult" class="vertical-radio">
                    <el-radio label="良好">良好</el-radio>
                    <el-radio label="一般">一般</el-radio>
                    <el-radio label="需关注">需关注</el-radio>
                  </el-radio-group>
                 </el-form-item>
              </td>
              <td class="content-cell">
                <div></div>
                <el-input v-model="form.attachment2Remark" type="textarea" :rows="8" class="noline-input" placeholder="请输入备注" />
              </td>
            </tr>
            <!-- 是否存在限制性协议 -->
            <tr>
              <td><strong>是否存在限制性协议</strong></td>
              <td class="content-cell">
                <div class="form-row">
                  <span class="label">竞业禁止协议：</span>
                  <el-radio-group v-model="form.hasNonCompete">
                    <el-radio :value="true">是</el-radio>
                    <el-radio :value="false">否</el-radio>
                  </el-radio-group>
                </div>
                <div class="form-row">
                  <span class="label">保密协议：</span>
                  <el-radio-group v-model="form.hasNda">
                    <el-radio :value="true">是</el-radio>
                    <el-radio :value="false">否</el-radio>
                  </el-radio-group>
                </div>
              </td>
              <td></td>
              <td class="content-cell">
                <div></div>
                <el-input v-model="form.agreementRemark" type="textarea" :rows="2" class="noline-input" placeholder="请输入备注"/>
              </td>
            </tr>
            <!-- 是否存在劳动争议/失信记录 -->
            <tr>
              <td><strong>是否存在劳动争议/失信记录</strong></td>
              <td class="content-cell">
                <div class="form-row">
                  <el-radio-group v-model="form.hasDisputeStatus">
                    <el-radio :value="true">是</el-radio>
                    <el-radio :value="false">否</el-radio>
                  </el-radio-group>
                </div>
              </td>
              <td></td>
              <td class="content-cell">
                <div></div>
                <el-input v-model="form.disputeRemark" type="textarea" :rows="2" class="noline-input" placeholder="请输入备注"/>
              </td>
            </tr>
            <!-- 调查结论 -->
            <tr>
              <td><strong>调查结论</strong></td>
              <td class="content-cell">
                <el-form-item prop="conclusion" style="margin-bottom:0">
                  <el-radio-group v-model="form.conclusion" class="vertical-radio">
                    <el-radio :value="'推荐入职'">推荐入职</el-radio>
                    <el-radio :value="'有条件推荐'">有条件推荐</el-radio>
                    <el-radio :value="'不推荐'">不推荐</el-radio>
                  </el-radio-group>
                </el-form-item>
              </td>
              <td colspan="2" class="content-cell">
                <div class="form-row align-top">
                  <span class="label">理由简述：</span>
                  <el-input v-model="form.conclusionReason" type="textarea" :rows="3" class="noline-input flex-1" />
                </div>
              </td>
            </tr>
            <!-- 调查人 & 日期 -->
            <tr>
              <td><strong>调查人</strong></td>
              <td class="content-cell">
                 <el-form-item prop="investigatorName" style="margin-bottom:0">
                    <el-input v-model="form.investigatorName" class="noline-input" />
                 </el-form-item>
              </td>
              <td class="center-cell"><strong>日期</strong></td>
              <td class="content-cell">
                 <el-form-item prop="investigatorDate" style="margin-bottom:0">
                    <el-date-picker v-model="form.investigatorDate" type="date" class="noline-input" />
                 </el-form-item>
              </td>
            </tr>
          </tbody>
        </table>

        <div class="interview-header">
          附件2：访谈记录摘要
        </div>

        <!-- 调查表（一） -->
        <div class="interview-table-wrapper">
          <div class="interview-meta">
            <span>调查表（一）</span>
            <span class="meta-item">姓名：<el-input v-model="form.interviewSupervisor.name" class="inline-input" /></span>
            <span class="meta-item">关系：<el-input v-model="form.interviewSupervisor.relationship" class="inline-input" placeholder="不填则为上级" /></span>
            <span class="meta-item">联系方式：<el-input v-model="form.interviewSupervisor.contact" class="inline-input" /></span>
          </div>
          <table class="report-table" border="1" cellspacing="0" cellpadding="0">
            <tbody>
              <tr class="q-row"><td><strong>问：请问你和*****是什么时候认识的？他的职务是什么？具体工作职责有哪些方面？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewSupervisor.q1" class="noline-input form-q-input" /></td></tr>
              
              <tr class="q-row"><td><strong>问：你觉得他在工作方面有哪些优势？比较擅长哪方面的工作？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewSupervisor.q2" class="noline-input form-q-input" /></td></tr>
              
              <tr class="q-row"><td><strong>问：他在职业道德方面的表现怎么样？你有没有看到或听到关于他不太好的现象和评价？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewSupervisor.q3" class="noline-input form-q-input" /></td></tr>
              
              <tr class="q-row"><td><strong>问：请问他人际关系怎么样？和其他同事相处有没有问题？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewSupervisor.q4" class="noline-input form-q-input" /></td></tr>
              
              <tr class="q-row"><td><strong>问：你对他的总体评价如何？你觉得他哪些方面需要提高和改进呢？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewSupervisor.q5" class="noline-input form-q-input" /></td></tr>
            </tbody>
          </table>
        </div>

        <!-- 调查表（二） -->
        <div class="interview-table-wrapper">
          <div class="interview-meta">
            <span>调查表（二）</span>
            <span class="meta-item">姓名：<el-input v-model="form.interviewHR.name" class="inline-input" /></span>
            <span class="meta-item">关系：<el-input v-model="form.interviewHR.relationship" class="inline-input" placeholder="不填则为HR" /></span>
            <span class="meta-item">联系方式：<el-input v-model="form.interviewHR.contact" class="inline-input" /></span>
          </div>
          <table class="report-table" border="1" cellspacing="0" cellpadding="0">
            <tbody>
              <tr class="q-row"><td><strong>问：请问你和*****是什么时候认识的？他的职务是什么？具体工作职责有哪些方面？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewHR.q1" class="noline-input form-q-input" /></td></tr>
              
              <tr class="q-row"><td><strong>问：你觉得他在工作方面有哪些优势？比较擅长哪方面的工作？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewHR.q2" class="noline-input form-q-input" /></td></tr>
              
              <tr class="q-row"><td><strong>问：他在职业道德方面的表现怎么样？你有没有看到或听到关于他不太好的现象和评价？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewHR.q3" class="noline-input form-q-input" /></td></tr>
              
              <tr class="q-row"><td><strong>问：请问他人际关系怎么样？和其他同事相处有没有问题？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewHR.q4" class="noline-input form-q-input" /></td></tr>
              
              <tr class="q-row"><td><strong>问：你对他的总体评价如何？你觉得他哪些方面需要提高和改进呢？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewHR.q5" class="noline-input form-q-input" /></td></tr>
            </tbody>
          </table>
        </div>

        <!-- 调查表（三） -->
        <div class="interview-table-wrapper">
          <div class="interview-meta">
            <span>调查表（三）</span>
            <span class="meta-item">姓名：<el-input v-model="form.interviewColleague.name" class="inline-input" /></span>
            <span class="meta-item">关系：<el-input v-model="form.interviewColleague.relationship" class="inline-input" placeholder="不填则为同事" /></span>
            <span class="meta-item">联系方式：<el-input v-model="form.interviewColleague.contact" class="inline-input" /></span>
          </div>
          <table class="report-table" border="1" cellspacing="0" cellpadding="0">
            <tbody>
              <tr class="q-row"><td><strong>问：请问你和*****是什么时候认识的？他的职务是什么？具体工作职责有哪些方面？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewColleague.q1" class="noline-input form-q-input" /></td></tr>
              
              <tr class="q-row"><td><strong>问：你觉得他在工作方面有哪些优势？比较擅长哪方面的工作？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewColleague.q2" class="noline-input form-q-input" /></td></tr>
              
              <tr class="q-row"><td><strong>问：他在职业道德方面的表现怎么样？你有没有看到或听到关于他不太好的现象和评价？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewColleague.q3" class="noline-input form-q-input" /></td></tr>
              
              <tr class="q-row"><td><strong>问：请问他人际关系怎么样？和其他同事相处有没有问题？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewColleague.q4" class="noline-input form-q-input" /></td></tr>
              
              <tr class="q-row"><td><strong>问：你对他的总体评价如何？你觉得他哪些方面需要提高和改进呢？</strong></td></tr>
              <tr class="a-row"><td><span class="a-label">答：</span><el-input type="textarea" autosize v-model="form.interviewColleague.q5" class="noline-input form-q-input" /></td></tr>
            </tbody>
          </table>
        </div>

        <div class="form-actions" v-if="showAuditActions">
          <template v-if="props.recordId">
            <el-button type="primary" size="large" class="submit-btn" :loading="submitting" @click="handleSubmit(2)">
              审核通过
            </el-button>
            <el-button type="danger" size="large" class="submit-btn" :loading="submitting" @click="handleSubmit(3)">
              审核不通过
            </el-button>
          </template>
          <template v-else>
            <el-button type="primary" size="large" class="submit-btn" :loading="submitting" @click="handleSubmit()">
              确认并提交背调反馈
            </el-button>
          </template>
        </div>
      </el-form>
    </div>
    </template>
  </div>
</template>

<script setup lang="ts">

import { ref, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { CircleCheckFilled, Loading } from '@element-plus/icons-vue';
import request from '@/utils/request';
import { getBackCheckReport, submitBackCheckReport } from '@/api/system/backRecord';
import type { BackCheckReportVO, InterviewVO } from '@/api/system/backRecord/types';

const props = defineProps<{
  recordId?: string | number;
  reportStatus?: number;
}>();

const emit = defineEmits<{
  submitted: [status: number];
}>();

const route = useRoute();
const formRef = ref();
const submitting = ref(false);
const submitted = ref(false);
const loading = ref(true);
const formReportStatus = ref<number>(0);

/** 当前报告状态：优先用 props，其次用内部值 */
const currentReportStatus = computed(() => {
  if (props.reportStatus !== undefined && props.reportStatus !== null) {
    return props.reportStatus;
  }
  return formReportStatus.value;
});

const showAuditActions = computed(() => {
  if (!props.recordId) {
    return true;
  }
  return currentReportStatus.value === 1;
});

const form = ref({
  candidateName: '',
  applyPosition: '',
  checkTime: '' as any,
  gradSchool: '',
  eduCertNo: '',
  eduVerifyStatus: '',
  eduVerifyResult: '',
  companyVerifyResult: '',
  evalResult: '',
  companyName: '',
  workPeriod: [] as string[],
  position: '',
  lastSalary: '',
  leaveReasonVerify: '',
  attachment1Remark: '',
  leaderEvalAdvantage: '',
  leaderEvalImprove: '',
  leaderEvalProf: '',
  leaderEvalAttitude: '',
  leaderEvalTeam: '',
  leaderEvalMorals: '',
  colleagueEvalTeamwork: '',
  colleagueEvalProf: '',
  hrEvalDispute: '',
  hrEvalTransfer: '',
  attachment2Remark: '',
  hasNonCompete: false,
  hasNda: false,
  agreementRemark: '',
  hasDisputeStatus: false,
  disputeRemark: '',
  interviewSupervisor: { name: '', relationship: '', contact: '', q1: '', q2: '', q3: '', q4: '', q5: '' },
  interviewHR: { name: '', relationship: '', contact: '', q1: '', q2: '', q3: '', q4: '', q5: '' },
  interviewColleague: { name: '', relationship: '', contact: '', q1: '', q2: '', q3: '', q4: '', q5: '' },
  conclusion: '',
  conclusionReason: '',
  investigatorName: '',
  investigatorDate: '' as any
});

const rules = {
  candidateName: [{ required: true, message: '无法获取候选人信息', trigger: 'blur' }],
  investigatorName: [{ required: true, message: '请输入调查人姓名', trigger: 'blur' }],
  investigatorDate: [{ required: true, message: '请选择调查日期', trigger: 'change' }],
  conclusion: [{ required: true, message: '请选择最终推荐结论', trigger: 'change' }],
  eduVerifyResult: [{ required: true, message: '请选择学历核实结果', trigger: 'change' }],
  companyVerifyResult: [{ required: true, message: '请选择工作单位核实结果', trigger: 'change' }],
  evalResult: [{ required: true, message: '请选择表现核实结果', trigger: 'change' }]
};

/** 将后端访谈记录映射到表单结构 */
const mapInterviewToForm = (interviews?: InterviewVO[]) => {
  const defaultInterview = { name: '', relationship: '', contact: '', q1: '', q2: '', q3: '', q4: '', q5: '' };
  if (!interviews || interviews.length === 0) {
    return {
      interviewSupervisor: { ...defaultInterview },
      interviewHR: { ...defaultInterview },
      interviewColleague: { ...defaultInterview }
    };
  }
  const mapOne = (iv?: InterviewVO) => iv ? {
    name: iv.intervieweeName || '',
    relationship: iv.intervieweeRelation || '',
    contact: iv.intervieweeContact || '',
    q1: iv.qa1 || '', q2: iv.qa2 || '', q3: iv.qa3 || '', q4: iv.qa4 || '', q5: iv.qa5 || ''
  } : { ...defaultInterview };

  return {
    interviewSupervisor: mapOne(interviews[0]),
    interviewHR: mapOne(interviews[1]),
    interviewColleague: mapOne(interviews[2])
  };
};

/** 从后端报告数据回填表单 */
const fillForm = (data: BackCheckReportVO) => {
  const f = form.value;
  f.candidateName = data.candidateName || '';
  f.applyPosition = data.applyPosition || '';
  f.checkTime = data.checkTime || '';
  f.gradSchool = data.gradSchool || '';
  f.eduCertNo = data.eduCertNo || '';
  f.eduVerifyStatus = data.eduVerifyStatus || '';
  f.eduVerifyResult = data.eduCheckResult || '';
  f.companyVerifyResult = data.companyCheckResult || '';
  f.evalResult = data.performCheckResult || '';
  f.companyName = data.companyName || '';
  f.position = data.jobTitle || '';
  f.lastSalary = data.lastSalary || '';
  f.leaveReasonVerify = data.leaveReasonVerify || '';
  f.attachment1Remark = data.companyCheckRemark || '';
  f.leaderEvalAdvantage = data.leaderEvalAdvantage || '';
  f.leaderEvalImprove = data.leaderEvalImprove || '';
  f.leaderEvalProf = data.leaderEvalProf || '';
  f.leaderEvalAttitude = data.leaderEvalAttitude || '';
  f.leaderEvalTeam = data.leaderEvalTeam || '';
  f.leaderEvalMorals = data.leaderEvalMorals || '';
  f.colleagueEvalTeamwork = data.colleagueEvalTeamwork || '';
  f.colleagueEvalProf = data.colleagueEvalProf || '';
  f.hrEvalDispute = data.hrEvalDispute || '';
  f.hrEvalTransfer = data.hrEvalTransfer || '';
  f.attachment2Remark = data.performCheckRemark || '';
  f.hasNonCompete = data.hasNonCompete === 1;
  f.hasNda = data.hasNda === 1;
  f.agreementRemark = data.agreementRemark || '';
  f.hasDisputeStatus = data.hasDispute === 1;
  f.disputeRemark = data.disputeRemark || '';
  f.conclusion = data.conclusion || '';
  f.conclusionReason = data.conclusionReason || '';
  f.investigatorName = data.investigatorName || '';
  f.investigatorDate = data.investigatorDate || '';

  // 任职时间（后端存 workStartTime / workEndTime）
  if (data.workStartTime || data.workEndTime) {
    f.workPeriod = [data.workStartTime || '', data.workEndTime || ''];
  }

  // 访谈记录
  const interviewMap = mapInterviewToForm(data.interviews);
  f.interviewSupervisor = interviewMap.interviewSupervisor;
  f.interviewHR = interviewMap.interviewHR;
  f.interviewColleague = interviewMap.interviewColleague;

  // 报告状态
  if (data.reportStatus !== undefined && data.reportStatus !== null) {
    formReportStatus.value = data.reportStatus;
  }
};

onMounted(async () => {
  const rid = props.recordId || route.query.recordId;

  // 如果有 recordId，先尝试从管理端接口获取报告数据回显
  if (rid) {
    try {
      const res = await getBackCheckReport(rid as string);
      if (res.data) {
        fillForm(res.data);
        loading.value = false;
        return;
      }
    } catch (e) {
      // 管理端接口查询失败，回退到门户接口
    }

    // 回退：门户端查询表单提交状态
    try {
      const statusRes = await request.get('/portal/check/bgform/status', {
        params: { recordId: rid },
        skipAuth: true
      } as any);
      if (statusRes?.submitted) {
        submitted.value = true;
        loading.value = false;
        return;
      }
      if (statusRes?.candidateName) {
        form.value.candidateName = statusRes.candidateName;
      }
    } catch (e) {
      // 查询失败不影响表单填写
    }
  }

  if (route.query.candidateName) {
    form.value.candidateName = route.query.candidateName as string;
  }
  loading.value = false;
});

const handleSubmit = (reportStatus?: number) => {
  formRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      ElMessage.error('请完善必填信息！');
      return;
    }

    const rid = props.recordId || route.query.recordId;
    if (!rid) {
      ElMessage.error('缺少背调记录ID，无法提交');
      return;
    }

    submitting.value = true;
    try {
      if (props.recordId) {
        // 管理端提交：使用新接口，带登录校验，含三个核实结果 + reportStatus
        const f = form.value;
        const mapInterview = (iv: typeof f.interviewSupervisor) => ({
          name: iv.name,
          relationship: iv.relationship,
          contact: iv.contact,
          q1: iv.q1, q2: iv.q2, q3: iv.q3, q4: iv.q4, q5: iv.q5
        });
        const submitData = {
          reportStatus: reportStatus || 2,
          candidateName: f.candidateName,
          applyPosition: f.applyPosition,
          checkTime: f.checkTime,
          gradSchool: f.gradSchool,
          eduCertNo: f.eduCertNo,
          eduVerifyStatus: f.eduVerifyStatus,
          eduCheckResult: f.eduVerifyResult,
          companyName: f.companyName,
          workPeriod: f.workPeriod?.length === 2 ? f.workPeriod : [],
          position: f.position,
          lastSalary: f.lastSalary,
          leaveReasonVerify: f.leaveReasonVerify,
          companyCheckRemark: f.attachment1Remark,
          companyCheckResult: f.companyVerifyResult,
          leaderEvalAdvantage: f.leaderEvalAdvantage,
          leaderEvalImprove: f.leaderEvalImprove,
          leaderEvalProf: f.leaderEvalProf,
          leaderEvalAttitude: f.leaderEvalAttitude,
          leaderEvalTeam: f.leaderEvalTeam,
          leaderEvalMorals: f.leaderEvalMorals,
          colleagueEvalTeamwork: f.colleagueEvalTeamwork,
          colleagueEvalProf: f.colleagueEvalProf,
          hrEvalDispute: f.hrEvalDispute,
          hrEvalTransfer: f.hrEvalTransfer,
          performCheckRemark: f.attachment2Remark,
          performCheckResult: f.evalResult,
          hasNonCompete: f.hasNonCompete,
          hasNda: f.hasNda,
          agreementRemark: f.agreementRemark,
          hasDisputeStatus: f.hasDisputeStatus,
          disputeRemark: f.disputeRemark,
          conclusion: f.conclusion,
          conclusionReason: f.conclusionReason,
          investigatorName: f.investigatorName,
          investigatorDate: f.investigatorDate,
          interviewSupervisor: mapInterview(f.interviewSupervisor),
          interviewHR: mapInterview(f.interviewHR),
          interviewColleague: mapInterview(f.interviewColleague)
        };
        await submitBackCheckReport(rid, submitData);
        ElMessage.success(reportStatus === 3 ? '已标记为审核不通过' : '审核通过');
        formReportStatus.value = reportStatus || 2;
        emit('submitted', reportStatus || 2);
      } else {
        // 门户端提交：使用原接口（免登录）
        await request.post('/portal/check/bgform/submit', {
          recordId: rid,
          ...form.value
        }, { skipAuth: true } as any);
        submitted.value = true;
        ElMessage.success('提交成功！感谢您的真实填写与支持。');
        setTimeout(() => {
          window.close();
        }, 1500);
      }
    } catch (e: any) {
      // error already handled by request interceptor
    } finally {
      submitting.value = false;
    }
  });
};
</script>
<style scoped>
.bg-check-container {
  background-color: #fff;
  padding: 16px 20px;
  font-family: SimSun, "宋体", serif;
}

.bg-header {
  text-align: center;
  margin-bottom: 20px;
}

.header-title {
  font-size: 24px;
  font-weight: bold;
  letter-spacing: 2px;
  margin: 0;
}

.form-wrapper {
  max-width: 900px;
  margin: 0 auto;
}

.report-table {
  width: 100%;
  border-collapse: collapse;
  border: 1.5px solid #000;
  margin-bottom: 30px;
}

.report-table th, .report-table td {
  border: 1px solid #000;
  padding: 8px 12px;
  font-size: 14px;
  vertical-align: middle;
  text-align: left;
}

.report-table th {
  text-align: center;
  font-weight: bold;
}

.center-cell {
  text-align: center !important;
}

.content-cell {
  padding: 8px !important;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.form-row.align-top {
  align-items: flex-start;
}

.label {
  white-space: nowrap;
}

.flex-1 {
  flex: 1;
}

.eval-section {
  margin-top: 10px;
  margin-bottom: 4px;
}
.eval-section:first-child {
  margin-top: 0;
}

.vertical-radio {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.interview-header {
  margin-top: 20px;
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: bold;
}

.interview-table-wrapper {
  margin-bottom: 25px;
}

.interview-meta {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-weight: bold;
  font-size: 14px;
}

.meta-item {
  margin-left: 20px;
  display: flex;
  align-items: center;
}

.q-row td {
  background-color: #f9f9f9;
}

.a-row td {
  display: flex;
  align-items: flex-start;
}

.a-label {
  white-space: nowrap;
  margin-top: 4px;
  color: #666;
}

.form-q-input {
  flex: 1;
}

:deep(.noline-input .el-input__wrapper),
:deep(.noline-input .el-textarea__inner) {
  box-shadow: none !important;
  background-color: transparent;
  padding: 0 4px;
  border-radius: 0;
}

:deep(.noline-input.el-input), :deep(.noline-input .el-textarea__inner) {
  --el-input-border-color: transparent;
  --el-input-hover-border-color: transparent;
  --el-input-focus-border-color: transparent;
}

:deep(.inline-input) {
  width: 120px;
  margin-left: 5px;
}

:deep(.inline-input .el-input__wrapper) {
  box-shadow: none !important;
  border-bottom: 1px solid #000;
  border-radius: 0;
  padding: 0;
  height: 24px;
}

.form-actions {
  text-align: center;
  margin-top: 40px;
}

.submit-btn {
  width: 200px;
}

:deep(.el-radio__label) {
  font-size: 14px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

.success-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
}
</style>
