<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>员工数据验证</span>
        </div>
      </template>
      
      <el-form :model="validateForm" ref="validateRef" :rules="validateRules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="员工库" prop="libraryId">
              <el-select v-model="validateForm.libraryId" placeholder="请选择员工库" @change="handleLibraryChange">
                <el-option
                  v-for="lib in libraryList"
                  :key="lib.libraryId"
                  :label="lib.libraryName"
                  :value="lib.libraryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="验证类型" prop="validationType">
              <el-select v-model="validateForm.validationType" placeholder="请选择验证类型">
                <el-option label="数据完整性验证" value="COMPLETENESS" />
                <el-option label="数据格式验证" value="FORMAT" />
                <el-option label="重复数据验证" value="DUPLICATE" />
                <el-option label="全面验证" value="COMPREHENSIVE" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24">
            <el-form-item label="验证规则">
              <el-checkbox-group v-model="validateForm.rules">
                <el-checkbox label="idCard">身份证号格式</el-checkbox>
                <el-checkbox label="phoneNumber">手机号格式</el-checkbox>
                <el-checkbox label="bankAccount">银行卡号格式</el-checkbox>
                <el-checkbox label="requiredFields">必填字段检查</el-checkbox>
                <el-checkbox label="duplicateCheck">重复数据检查</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="handleValidate" :loading="validating">开始验证</el-button>
              <el-button @click="resetForm">重置</el-button>
              <el-button type="success" @click="handleExportReport" :disabled="!validationResult" v-hasPermi="['credit:employee:export']">导出报告</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 验证结果 -->
    <el-card class="box-card" v-if="validationResult" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>验证结果</span>
          <el-tag :type="validationResult.success ? 'success' : 'danger'" style="margin-left: 10px">
            {{ validationResult.success ? '验证通过' : '验证失败' }}
          </el-tag>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="6">
          <el-statistic title="总记录数" :value="validationResult.totalRecords" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="有效记录" :value="validationResult.validRecords" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="无效记录" :value="validationResult.invalidRecords" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="通过率" :value="validationResult.passRate" suffix="%" />
        </el-col>
      </el-row>

      <!-- 错误详情 -->
      <div v-if="validationResult.errors && validationResult.errors.length > 0" style="margin-top: 20px;">
        <h4>错误详情</h4>
        <el-table :data="validationResult.errors" max-height="400">
          <el-table-column label="员工编号" prop="employeeNumber" width="120" />
          <el-table-column label="姓名" prop="employeeName" width="100" />
          <el-table-column label="错误类型" prop="errorType" width="120">
            <template #default="scope">
              <el-tag :type="getErrorTypeTag(scope.row.errorType)">{{ getErrorTypeName(scope.row.errorType) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="字段" prop="fieldName" width="100" />
          <el-table-column label="错误描述" prop="errorMessage" :show-overflow-tooltip="true" />
          <el-table-column label="建议" prop="suggestion" :show-overflow-tooltip="true" />
        </el-table>
      </div>

      <!-- 重复数据 -->
      <div v-if="validationResult.duplicates && validationResult.duplicates.length > 0" style="margin-top: 20px;">
        <h4>重复数据</h4>
        <el-table :data="validationResult.duplicates" max-height="400">
          <el-table-column label="重复字段" prop="duplicateField" width="120" />
          <el-table-column label="重复值" prop="duplicateValue" width="150" />
          <el-table-column label="重复记录数" prop="count" width="120" />
          <el-table-column label="涉及员工" prop="employees" :show-overflow-tooltip="true">
            <template #default="scope">
              <span>{{ scope.row.employees.map(emp => `${emp.name}(${emp.employeeNumber})`).join(', ') }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 数据质量分析 -->
      <div v-if="validationResult.qualityAnalysis" style="margin-top: 20px;">
        <h4>数据质量分析</h4>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card>
              <el-statistic title="完整性得分" :value="validationResult.qualityAnalysis.completenessScore" suffix="/100" />
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card>
              <el-statistic title="准确性得分" :value="validationResult.qualityAnalysis.accuracyScore" suffix="/100" />
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card>
              <el-statistic title="一致性得分" :value="validationResult.qualityAnalysis.consistencyScore" suffix="/100" />
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 临时员工同步 -->
    <el-card class="box-card" v-if="tempEmployees.length > 0" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>临时员工同步</span>
          <el-button type="primary" size="small" @click="handleSyncTemp" style="margin-left: 10px;">同步选中</el-button>
        </div>
      </template>
      
      <el-table :data="tempEmployees" @selection-change="handleTempSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="员工编号" prop="employeeNumber" width="120" />
        <el-table-column label="姓名" prop="employeeName" width="100" />
        <el-table-column label="身份证号" prop="idCardNumber" width="150" :show-overflow-tooltip="true" />
        <el-table-column label="手机号" prop="contactPhone" width="120" />
        <el-table-column label="部门" prop="department" width="120" />
        <el-table-column label="职位" prop="position" width="120" />
        <el-table-column label="日薪" prop="dailySalary" width="80">
          <template #default="scope">
            <span>{{ scope.row.dailySalary }}元</span>
          </template>
        </el-table-column>
        <el-table-column label="薪资单位" prop="salaryUnit" width="120" :show-overflow-tooltip="true" />
        <el-table-column label="员工状态" prop="employeeStatus" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.employeeStatus === 'ACTIVE' ? 'success' : 'info'">
              {{ scope.row.employeeStatus === 'ACTIVE' ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入职日期" prop="hireDate" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.hireDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createBy" width="100" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup name="EmployeeValidate">
import { 
  validateEmployeeData, 
  syncTempEmployees, 
  listEmployeeLibraries,
  listEmployees
} from "@/api/credit/employee";
import { parseTime } from "@/utils/ruoyi";

const { proxy } = getCurrentInstance();

const libraryList = ref([]);
const validating = ref(false);
const validationResult = ref(null);
const tempEmployees = ref([]);
const selectedTempIds = ref([]);

const data = reactive({
  validateForm: {
    libraryId: null,
    validationType: 'COMPREHENSIVE',
    rules: ['idCard', 'phoneNumber', 'requiredFields', 'duplicateCheck']
  },
  validateRules: {
    libraryId: [
      { required: true, message: "请选择员工库", trigger: "change" }
    ],
    validationType: [
      { required: true, message: "请选择验证类型", trigger: "change" }
    ]
  }
});

const { validateForm, validateRules } = toRefs(data);

/** 查询员工库列表 */
function getLibraryList() {
  listEmployeeLibraries({ pageNum: 1, pageSize: 100 }).then(response => {
    libraryList.value = response.rows;
  });
}

/** 查询临时员工 */
function getTempEmployees() {
  if (!validateForm.value.libraryId) return;
  
  listEmployees({
    libraryId: validateForm.value.libraryId,
    isTemporary: true,
    pageNum: 1,
    pageSize: 100
  }).then(response => {
    tempEmployees.value = response.rows;
  });
}

/** 员工库变更 */
function handleLibraryChange() {
  validationResult.value = null;
  getTempEmployees();
}

/** 开始验证 */
function handleValidate() {
  proxy.$refs["validateRef"].validate(valid => {
    if (valid) {
      validating.value = true;
      validateEmployeeData(validateForm.value).then(response => {
        validationResult.value = response.data;
        validating.value = false;
        proxy.$modal.msgSuccess("验证完成");
      }).catch(() => {
        validating.value = false;
      });
    }
  });
}

/** 重置表单 */
function resetForm() {
  proxy.resetForm("validateRef");
  validationResult.value = null;
  tempEmployees.value = [];
}

/** 导出报告 */
function handleExportReport() {
  if (!validationResult.value) return;
  
  const reportData = {
    ...validationResult.value,
    libraryId: validateForm.value.libraryId,
    validationType: validateForm.value.validationType,
    exportTime: new Date().toISOString()
  };
  
  proxy.download('credit/employee/validation/export', reportData, `validation_report_${new Date().getTime()}.xlsx`);
}

/** 临时员工选择 */
function handleTempSelectionChange(selection) {
  selectedTempIds.value = selection.map(item => item.employeeId);
}

/** 同步临时员工 */
function handleSyncTemp() {
  if (selectedTempIds.value.length === 0) {
    proxy.$modal.msgError("请选择要同步的临时员工");
    return;
  }
  
  proxy.$modal.confirm('是否确认同步选中的临时员工？').then(function() {
    return syncTempEmployees(selectedTempIds.value);
  }).then(() => {
    getTempEmployees();
    proxy.$modal.msgSuccess("同步成功");
  }).catch(() => {});
}

/** 获取错误类型标签 */
function getErrorTypeTag(errorType) {
  const tagMap = {
    'FORMAT_ERROR': 'danger',
    'MISSING_REQUIRED': 'warning',
    'DUPLICATE_DATA': 'info',
    'INVALID_VALUE': 'danger'
  };
  return tagMap[errorType] || 'info';
}

/** 获取错误类型名称 */
function getErrorTypeName(errorType) {
  const nameMap = {
    'FORMAT_ERROR': '格式错误',
    'MISSING_REQUIRED': '缺少必填项',
    'DUPLICATE_DATA': '重复数据',
    'INVALID_VALUE': '无效值'
  };
  return nameMap[errorType] || errorType;
}

onMounted(() => {
  getLibraryList();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  margin-bottom: 20px;
}
</style>