<template>
  <div class="ocr-employee-extractor">
    <el-row :gutter="20">
      <!-- 文件上传区域 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>合同文件上传</span>
          </template>
          
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            drag
            :action="uploadAction"
            :headers="uploadHeaders"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :file-list="fileList"
            accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 PDF、Word、图片格式，文件大小不超过 10MB
              </div>
            </template>
          </el-upload>

          <div v-if="extracting" class="extraction-progress">
            <el-progress :percentage="extractionProgress" :status="extractionStatus" />
            <p class="progress-text">{{ extractionText }}</p>
          </div>
        </el-card>
      </el-col>

      <!-- OCR结果展示 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>OCR识别结果</span>
              <el-button 
                type="primary" 
                :disabled="!hasExtractedData"
                @click="handleConfirmExtraction"
              >
                确认提取
              </el-button>
            </div>
          </template>

          <div v-if="!extractedData.length" class="no-data">
            <el-empty description="暂无识别结果" />
          </div>

          <div v-else>
            <el-alert
              title="提示"
              description="请检查并调整OCR识别的员工信息，确认无误后点击确认提取"
              type="info"
              :closable="false"
              class="mb-3"
            />

            <el-table :data="extractedData" stripe>
              <el-table-column label="员工姓名" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.employeeName" placeholder="请输入员工姓名" />
                </template>
              </el-table-column>
              <el-table-column label="岗位" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.position" placeholder="请输入岗位" />
                </template>
              </el-table-column>
              <el-table-column label="薪资标准" align="center">
                <template #default="scope">
                  <el-input-number 
                    v-model="scope.row.salaryStandard" 
                    :precision="2" 
                    placeholder="请输入薪资标准" 
                  />
                </template>
              </el-table-column>
              <el-table-column label="薪资单位" align="center">
                <template #default="scope">
                  <el-select v-model="scope.row.salaryUnit" placeholder="请选择薪资单位">
                    <el-option label="小时制" value="HOURLY" />
                    <el-option label="日薪制" value="DAILY" />
                    <el-option label="月薪制" value="MONTHLY" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="100">
                <template #default="scope">
                  <el-button 
                    link 
                    type="danger" 
                    icon="Delete" 
                    @click="handleRemoveEmployee(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="extraction-actions">
              <el-button type="success" @click="handleAddEmployee">添加员工</el-button>
              <el-button type="warning" @click="handleBatchAdjust">批量调整</el-button>
              <el-button type="info" @click="handleImportFromJson">从JSON导入</el-button>
              <el-button @click="handleClearAll">清空所有</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 手动添加员工对话框 -->
    <el-dialog title="手动添加员工" v-model="addEmployeeDialogVisible" width="500px">
      <el-form ref="addEmployeeFormRef" :model="addEmployeeForm" :rules="addEmployeeRules" label-width="100px">
        <el-form-item label="员工姓名" prop="employeeName">
          <el-input v-model="addEmployeeForm.employeeName" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="岗位" prop="position">
          <el-input v-model="addEmployeeForm.position" placeholder="请输入岗位" />
        </el-form-item>
        <el-form-item label="薪资标准" prop="salaryStandard">
          <el-input-number v-model="addEmployeeForm.salaryStandard" :precision="2" placeholder="请输入薪资标准" />
        </el-form-item>
        <el-form-item label="薪资单位" prop="salaryUnit">
          <el-select v-model="addEmployeeForm.salaryUnit" placeholder="请选择薪资单位">
            <el-option label="小时制" value="HOURLY" />
            <el-option label="日薪制" value="DAILY" />
            <el-option label="月薪制" value="MONTHLY" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAddEmployee">确 定</el-button>
          <el-button @click="addEmployeeDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量调整对话框 -->
    <el-dialog title="批量调整薪资" v-model="batchAdjustDialogVisible" width="400px">
      <el-form ref="batchAdjustFormRef" :model="batchAdjustForm" :rules="batchAdjustRules" label-width="100px">
        <el-form-item label="调整方式" prop="adjustType">
          <el-radio-group v-model="batchAdjustForm.adjustType">
            <el-radio label="multiply">按倍数调整</el-radio>
            <el-radio label="add">按金额调整</el-radio>
            <el-radio label="set">设置固定值</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="调整值" prop="adjustValue">
          <el-input-number v-model="batchAdjustForm.adjustValue" :precision="2" placeholder="请输入调整值" />
        </el-form-item>
        <el-form-item label="薪资单位" prop="salaryUnit">
          <el-select v-model="batchAdjustForm.salaryUnit" placeholder="请选择薪资单位">
            <el-option label="保持不变" value="" />
            <el-option label="小时制" value="HOURLY" />
            <el-option label="日薪制" value="DAILY" />
            <el-option label="月薪制" value="MONTHLY" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitBatchAdjust">确 定</el-button>
          <el-button @click="batchAdjustDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 从JSON导入对话框 -->
    <el-dialog title="从JSON导入员工数据" v-model="importJsonDialogVisible" width="600px">
      <el-form label-width="100px">
        <el-form-item label="JSON数据">
          <el-input
            v-model="jsonImportData"
            type="textarea"
            :rows="10"
            placeholder="请粘贴员工JSON数据，支持单个对象或对象数组"
          />
        </el-form-item>
        <el-form-item>
          <el-alert
            title="数据格式说明"
            description="支持包含employeeName、position、salaryUnit、dailySalary等字段的JSON对象"
            type="info"
            :closable="false"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitImportJson">导 入</el-button>
          <el-button @click="importJsonDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { extractEmployeeInfoFromOCR } from "@/api/digitalCredit/contractEmployee";
import { getToken } from "@/utils/auth";

const emit = defineEmits(['extract-complete']);

const { proxy } = getCurrentInstance();

// 上传配置
const uploadAction = ref(import.meta.env.VITE_APP_BASE_API + "/credit/contract-employee/ocr-extract");
const uploadHeaders = ref({ Authorization: "Bearer " + getToken() });

// 文件列表
const fileList = ref([]);

// 提取状态
const extracting = ref(false);
const extractionProgress = ref(0);
const extractionStatus = ref('');
const extractionText = ref('');

// 提取结果
const extractedData = ref([]);
const hasExtractedData = computed(() => extractedData.value.length > 0);

// 对话框状态
const addEmployeeDialogVisible = ref(false);
const batchAdjustDialogVisible = ref(false);

// 表单数据
const addEmployeeForm = ref({
  employeeName: '',
  position: '',
  salaryStandard: 0,
  salaryUnit: 'DAILY'
});

const batchAdjustForm = ref({
  adjustType: 'multiply',
  adjustValue: 1,
  salaryUnit: ''
});

// 表单验证规则
const addEmployeeRules = {
  employeeName: [{ required: true, message: "员工姓名不能为空", trigger: "blur" }],
  position: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
  salaryStandard: [{ required: true, message: "薪资标准不能为空", trigger: "blur" }],
  salaryUnit: [{ required: true, message: "薪资单位不能为空", trigger: "change" }]
};

const batchAdjustRules = {
  adjustValue: [{ required: true, message: "调整值不能为空", trigger: "blur" }]
};

/** 上传前检查 */
function beforeUpload(file) {
  const isValidType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/jpg', 'image/png'].includes(file.type);
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isValidType) {
    proxy.$modal.msgError('上传文件只能是 PDF、Word 或图片格式!');
    return false;
  }
  if (!isLt10M) {
    proxy.$modal.msgError('上传文件大小不能超过 10MB!');
    return false;
  }

  // 开始提取进度
  startExtraction();
  return true;
}

/** 开始提取进度模拟 */
function startExtraction() {
  extracting.value = true;
  extractionProgress.value = 0;
  extractionStatus.value = '';
  extractionText.value = '正在上传文件...';

  const progressInterval = setInterval(() => {
    if (extractionProgress.value < 90) {
      extractionProgress.value += Math.random() * 10;
      if (extractionProgress.value < 30) {
        extractionText.value = '正在上传文件...';
      } else if (extractionProgress.value < 60) {
        extractionText.value = '正在进行OCR识别...';
      } else {
        extractionText.value = '正在解析员工信息...';
      }
    }
  }, 500);

  // 存储定时器ID以便清除
  window.extractionInterval = progressInterval;
}

/** 上传成功 */
function handleUploadSuccess(response, file) {
  clearInterval(window.extractionInterval);
  
  if (response.code === 200) {
    extractionProgress.value = 100;
    extractionStatus.value = 'success';
    extractionText.value = 'OCR识别完成';
    
    // 模拟提取的员工数据
    extractedData.value = response.data.extractedEmployees || [
      {
        employeeName: '张三',
        position: '保安员',
        salaryStandard: 200,
        salaryUnit: 'DAILY'
      },
      {
        employeeName: '李四',
        position: '保安队长',
        salaryStandard: 250,
        salaryUnit: 'DAILY'
      }
    ];
    
    proxy.$modal.msgSuccess('OCR识别成功，共识别到 ' + extractedData.value.length + ' 名员工信息');
  } else {
    extractionProgress.value = 100;
    extractionStatus.value = 'exception';
    extractionText.value = 'OCR识别失败';
    proxy.$modal.msgError(response.msg || 'OCR识别失败');
  }
  
  setTimeout(() => {
    extracting.value = false;
  }, 2000);
}

/** 上传失败 */
function handleUploadError(error) {
  clearInterval(window.extractionInterval);
  extracting.value = false;
  extractionProgress.value = 100;
  extractionStatus.value = 'exception';
  extractionText.value = 'OCR识别失败';
  proxy.$modal.msgError('文件上传失败');
}

/** 确认提取 */
function handleConfirmExtraction() {
  if (extractedData.value.length === 0) {
    proxy.$modal.msgWarning("没有可提取的员工信息");
    return;
  }
  
  // 验证数据完整性
  const invalidData = extractedData.value.find(item => 
    !item.employeeName || !item.position || !item.salaryStandard || !item.salaryUnit
  );
  
  if (invalidData) {
    proxy.$modal.msgWarning("请完善所有员工信息");
    return;
  }
  
  emit('extract-complete', {
    employees: extractedData.value,
    source: 'OCR'
  });
  
  proxy.$modal.msgSuccess("员工信息提取成功");
  
  // 清空数据
  extractedData.value = [];
  fileList.value = [];
}

/** 删除员工 */
function handleRemoveEmployee(index) {
  extractedData.value.splice(index, 1);
}

/** 添加员工 */
function handleAddEmployee() {
  addEmployeeForm.value = {
    employeeName: '',
    position: '',
    salaryStandard: 0,
    salaryUnit: 'DAILY'
  };
  addEmployeeDialogVisible.value = true;
}

/** 提交添加员工 */
function submitAddEmployee() {
  proxy.$refs["addEmployeeFormRef"].validate(valid => {
    if (valid) {
      extractedData.value.push({ ...addEmployeeForm.value });
      addEmployeeDialogVisible.value = false;
      proxy.$modal.msgSuccess("员工添加成功");
    }
  });
}

/** 批量调整 */
function handleBatchAdjust() {
  if (extractedData.value.length === 0) {
    proxy.$modal.msgWarning("没有可调整的员工信息");
    return;
  }
  batchAdjustDialogVisible.value = true;
}

/** 提交批量调整 */
function submitBatchAdjust() {
  proxy.$refs["batchAdjustFormRef"].validate(valid => {
    if (valid) {
      extractedData.value.forEach(employee => {
        switch (batchAdjustForm.value.adjustType) {
          case 'multiply':
            employee.salaryStandard *= batchAdjustForm.value.adjustValue;
            break;
          case 'add':
            employee.salaryStandard += batchAdjustForm.value.adjustValue;
            break;
          case 'set':
            employee.salaryStandard = batchAdjustForm.value.adjustValue;
            break;
        }
        
        if (batchAdjustForm.value.salaryUnit) {
          employee.salaryUnit = batchAdjustForm.value.salaryUnit;
        }
      });
      
      batchAdjustDialogVisible.value = false;
      proxy.$modal.msgSuccess("批量调整成功");
    }
  });
}

/** 清空所有 */
function handleClearAll() {
  proxy.$modal.confirm('确认清空所有员工信息？').then(() => {
    extractedData.value = [];
    proxy.$modal.msgSuccess("清空成功");
  }).catch(() => {});
}
</script>

<style scoped>
.ocr-employee-extractor {
  padding: 20px;
}

.mb-3 {
  margin-bottom: 12px;
}

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

.upload-demo {
  width: 100%;
}

.extraction-progress {
  margin-top: 20px;
  text-align: center;
}

.progress-text {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.no-data {
  text-align: center;
  padding: 40px 0;
}

.extraction-actions {
  margin-top: 20px;
  text-align: center;
}

.extraction-actions .el-button {
  margin: 0 5px;
}
</style>