<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="员工库" prop="libraryId">
        <el-select v-model="queryParams.libraryId" placeholder="请选择员工库" clearable>
          <el-option
            v-for="lib in libraryList"
            :key="lib.libraryId"
            :label="lib.libraryName"
            :value="lib.libraryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="员工编号" prop="employeeNumber">
        <el-input
          v-model="queryParams.employeeNumber"
          placeholder="请输入员工编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="employeeName">
        <el-input
          v-model="queryParams.employeeName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCardNumber">
        <el-input
          v-model="queryParams.idCardNumber"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="employeeStatus">
        <el-select v-model="queryParams.employeeStatus" placeholder="请选择状态" clearable>
          <el-option label="在职" value="ACTIVE" />
          <el-option label="离职" value="INACTIVE" />
          <el-option label="临时" value="TEMPORARY" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['credit:employee:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['credit:employee:import']"
        >导入ERP</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Camera"
          @click="handleOcr"
          v-hasPermi="['credit:employee:ocr']"
        >OCR识别</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['credit:employee:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['credit:employee:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Edit"
          :disabled="multiple"
          @click="handleBatchUpdate"
          v-hasPermi="['credit:employee:edit']"
        >批量修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Switch"
          :disabled="multiple"
          @click="handleBatchTransfer"
          v-hasPermi="['credit:employee:edit']"
        >批量转移</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="employeeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="员工编号" align="center" prop="employeeNumber" />
      <el-table-column label="姓名" align="center" prop="employeeName" />
      <el-table-column label="身份证号" align="center" prop="idCardNumber" :show-overflow-tooltip="true" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" min-width= '120' />
      <el-table-column label="部门" align="center" prop="department" min-width="100" />
      <el-table-column label="职位" align="center" prop="position" />
      <el-table-column label="入职日期" align="center" prop="hireDate" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.hireDate) }}
        </template>
      </el-table-column>
      <el-table-column label="工资单位" align="center" prop="salaryUnit" :show-overflow-tooltip="true" min-width='200' />
      <el-table-column label="薪资信息" align="center" min-width="150">
        <template #default="scope">
          <div v-if="scope.row.monthlySalary">
            <el-tag type="success" size="small">月薪: {{ scope.row.monthlySalary }}元</el-tag>
          </div>
          <div v-else-if="scope.row.dailySalary">
            <el-tag type="warning" size="small">日薪: {{ scope.row.dailySalary }}元</el-tag>
          </div>
          <div v-else-if="scope.row.hourlySalary">
            <el-tag type="info" size="small">时薪: {{ scope.row.hourlySalary }}元</el-tag>
          </div>
          <div v-else>
            <el-tag type="info" size="small">未设置</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="是否临时" align="center" prop="isTemporary" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.isTemporary" type="warning">是</el-tag>
          <el-tag v-else type="success">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="employeeStatus" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.employeeStatus === 'ACTIVE'" type="success">在职</el-tag>
          <el-tag v-else-if="scope.row.employeeStatus === 'INACTIVE'" type="danger">离职</el-tag>
          <el-tag v-else type="warning">其他</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['credit:employee:query']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['credit:employee:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['credit:employee:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改员工对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="employeeRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="员工库" prop="libraryId">
              <el-select v-model="form.libraryId" placeholder="请选择员工库">
                <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="employeeNumber">
              <el-input v-model="form.employeeNumber" placeholder="请输入员工编号">
                <template #append>
                  <el-button @click="handleGenerateEmployeeNumber" :disabled="!form.libraryId">
                    <el-icon><Refresh /></el-icon>
                    生成
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="employeeName">
              <el-input v-model="form.employeeName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCardNumber">
              <el-input v-model="form.idCardNumber" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="employeeStatus">
              <el-select v-model="form.employeeStatus" placeholder="请选择状态">
                <el-option label="在职" value="ACTIVE" />
                <el-option label="离职" value="INACTIVE" />
                <el-option label="临时" value="TEMPORARY" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-select v-model="form.department" placeholder="请选择部门" clearable filterable allow-create>
                <el-option
                  v-for="dept in deptList"
                  :key="dept.deptId"
                  :label="dept.deptName"
                  :value="dept.deptName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-select v-model="form.position" placeholder="请选择职位" clearable filterable allow-create>
                <el-option
                  v-for="post in postList"
                  :key="post.postId"
                  :label="post.postName"
                  :value="post.postName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入职日期" prop="hireDate">
              <el-date-picker
                v-model="form.hireDate"
                type="date"
                placeholder="选择入职日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否临时" prop="isTemporary">
              <el-select v-model="form.isTemporary" placeholder="请选择">
                <el-option label="是" :value="true" />
                <el-option label="否" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工资单位" prop="salaryUnit">
              <el-select 
                v-model="form.salaryUnit" 
                placeholder="请选择工资单位" 
                multiple 
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="option in salaryUnitOptions"
                  :key="option"
                  :label="option"
                  :value="option"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="薪资类型" prop="salaryType">
              <el-select v-model="form.salaryType" placeholder="请选择薪资类型" @change="handleSalaryTypeChange">
                <el-option label="月薪" value="monthly" />
                <el-option label="日薪" value="daily" />
                <el-option label="小时薪" value="hourly" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="薪资金额" prop="salaryAmount">
              <el-input 
                v-model="form.salaryAmount" 
                :placeholder="getSalaryPlaceholder()" 
                type="number"
                min="0"
                step="0.01"
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入ERP对话框 -->
    <el-dialog title="导入ERP文件" v-model="importOpen" width="400px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="员工库">
          <el-select v-model="importLibraryId" placeholder="请选择员工库">
            <el-option
              v-for="lib in libraryList"
              :key="lib.libraryId"
              :label="lib.libraryName"
              :value="lib.libraryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件">
          <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :auto-upload="false"
            :on-change="handleFileChange"
            drag
          >
            <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">只能上传xlsx/xls文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitImport">确 定</el-button>
          <el-button @click="importOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- OCR识别对话框 -->
    <el-dialog title="OCR识别员工信息" v-model="ocrOpen" width="400px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="员工库">
          <el-select v-model="ocrLibraryId" placeholder="请选择员工库">
            <el-option
              v-for="lib in libraryList"
              :key="lib.libraryId"
              :label="lib.libraryName"
              :value="lib.libraryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            ref="ocrUploadRef"
            :limit="1"
            accept=".jpg, .jpeg, .png"
            :auto-upload="false"
            :on-change="handleOcrFileChange"
            drag
          >
            <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">只能上传jpg/png图片</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitOcr">识 别</el-button>
          <el-button @click="ocrOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 员工详情对话框 -->
    <el-dialog title="员工详情" v-model="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="员工编号">{{ detailData.employeeNumber }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ detailData.employeeName }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ detailData.idCardNumber }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailData.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="部门">{{ detailData.department }}</el-descriptions-item>
        <el-descriptions-item label="职位">{{ detailData.position }}</el-descriptions-item>
        <el-descriptions-item label="入职日期">{{ formatDate(detailData.hireDate) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="detailData.employeeStatus === 'ACTIVE'" type="success">在职</el-tag>
          <el-tag v-else-if="detailData.employeeStatus === 'INACTIVE'" type="danger">离职</el-tag>
          <el-tag v-else type="warning">其他</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="工资单位" :span="2">{{ detailData.salaryUnit || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="薪资信息" :span="2">
          <div v-if="detailData.monthlySalary">
            <el-tag type="success" size="large">月薪: {{ detailData.monthlySalary }}元</el-tag>
          </div>
          <div v-else-if="detailData.dailySalary">
            <el-tag type="warning" size="large">日薪: {{ detailData.dailySalary }}元</el-tag>
          </div>
          <div v-else-if="detailData.hourlySalary">
            <el-tag type="info" size="large">时薪: {{ detailData.hourlySalary }}元</el-tag>
          </div>
          <div v-else>
            <el-tag type="info" size="large">未设置薪资</el-tag>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="是否临时">
          <el-tag v-if="detailData.isTemporary" type="warning">是</el-tag>
          <el-tag v-else type="success">否</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="员工库">{{ detailData.libraryName || '暂无' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(detailData.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDateTime(detailData.updateTime) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 批量修改对话框 -->
    <el-dialog title="批量修改员工信息" v-model="batchUpdateOpen" width="600px" append-to-body>
      <el-form ref="batchUpdateRef" :model="batchUpdateForm" :rules="batchUpdateRules" label-width="100px">
        <el-form-item label="修改字段" prop="updateField">
          <el-select v-model="batchUpdateForm.updateField" placeholder="请选择要修改的字段" @change="handleUpdateFieldChange">
            <el-option label="部门" value="department" />
            <el-option label="职位" value="position" />
            <el-option label="员工状态" value="employeeStatus" />
            <el-option label="联系电话" value="contactPhone" />
            <el-option label="日薪" value="dailySalary" />
            <el-option label="月薪" value="monthlySalary" />
            <el-option label="小时薪资" value="hourlySalary" />
          </el-select>
        </el-form-item>
        <el-form-item label="新值" prop="updateValue">
          <el-select v-if="batchUpdateForm.updateField === 'department'" v-model="batchUpdateForm.updateValue" placeholder="请选择部门" clearable filterable allow-create>
            <el-option
              v-for="dept in deptList"
              :key="dept.deptId"
              :label="dept.deptName"
              :value="dept.deptName"
            />
          </el-select>
          <el-select v-else-if="batchUpdateForm.updateField === 'position'" v-model="batchUpdateForm.updateValue" placeholder="请选择职位" clearable filterable allow-create>
            <el-option
              v-for="post in postList"
              :key="post.postId"
              :label="post.postName"
              :value="post.postName"
            />
          </el-select>
          <el-select v-else-if="batchUpdateForm.updateField === 'employeeStatus'" v-model="batchUpdateForm.updateValue" placeholder="请选择状态">
            <el-option label="在职" value="ACTIVE" />
            <el-option label="离职" value="INACTIVE" />
            <el-option label="临时" value="TEMPORARY" />
          </el-select>
          <el-input v-else v-model="batchUpdateForm.updateValue" :placeholder="getUpdateValuePlaceholder()" />
        </el-form-item>
        <el-form-item>
          <el-alert
            :title="`将对选中的 ${ids.length} 个员工进行批量修改`"
            type="warning"
            show-icon
            :closable="false"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitBatchUpdate">确 定</el-button>
          <el-button @click="batchUpdateOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量转移对话框 -->
    <el-dialog title="批量转移员工" v-model="batchTransferOpen" width="500px" append-to-body>
      <el-form ref="batchTransferRef" :model="batchTransferForm" :rules="batchTransferRules" label-width="100px">
        <el-form-item label="目标员工库" prop="targetLibraryId">
          <el-select v-model="batchTransferForm.targetLibraryId" placeholder="请选择目标员工库">
            <el-option
              v-for="lib in libraryList"
              :key="lib.libraryId"
              :label="lib.libraryName"
              :value="lib.libraryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-alert
            :title="`将把选中的 ${ids.length} 个员工转移到目标员工库`"
            type="warning"
            show-icon
            :closable="false"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitBatchTransfer">确 定</el-button>
          <el-button @click="batchTransferOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Employee">
import { 
  listEmployees, 
  getEmployee, 
  createEmployee, 
  updateEmployee, 
  deleteEmployee,
  batchUpdateEmployees,
  batchDeleteEmployees,
  batchTransferEmployees,
  importErpFile,
  extractEmployeeByOcr,
  exportEmployees,
  listEmployeeLibraries,
  getDeptList,
  getPostList,
  generateEmployeeNumber
} from "@/api/credit/employee";
import { UploadFilled, Refresh } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();

const employeeList = ref([]);
const libraryList = ref([]);
const deptList = ref([]);
const postList = ref([]);
const salaryUnitOptions = ref([
  '主要工作单位',
  '兼职单位',
  '项目合作单位',
  '劳务派遣单位',
  '咨询服务单位',
  '临时工作单位'
]);
const open = ref(false);
const importOpen = ref(false);
const ocrOpen = ref(false);
const detailOpen = ref(false);
const batchUpdateOpen = ref(false);
const batchTransferOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const importLibraryId = ref(null);
const ocrLibraryId = ref(null);
const importFile = ref(null);
const ocrFile = ref(null);
const detailData = ref({});

// 批量操作表单
const batchUpdateForm = ref({
  updateField: null,
  updateValue: null
});

const batchTransferForm = ref({
  targetLibraryId: null
});

const batchUpdateRules = ref({
  updateField: [
    { required: true, message: "请选择修改字段", trigger: "change" }
  ],
  updateValue: [
    { required: true, message: "请输入新值", trigger: "blur" }
  ]
});

const batchTransferRules = ref({
  targetLibraryId: [
    { required: true, message: "请选择目标员工库", trigger: "change" }
  ]
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    libraryId: null,
    employeeNumber: null,
    employeeName: null,
    idCardNumber: null,
    employeeStatus: null
  },
  rules: {
    libraryId: [
      { required: true, message: "员工库不能为空", trigger: "change" }
    ],
    employeeNumber: [
      { required: true, message: "员工编号不能为空", trigger: "blur" },
      { validator: validateEmployeeNumber, trigger: "blur" }
    ],
    employeeName: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    idCardNumber: [
      { required: true, message: "身份证号不能为空", trigger: "blur" }
    ],
    contactPhone: [
      { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    employeeStatus: [
      { required: true, message: "员工状态不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询员工列表 */
function getList() {
  loading.value = true;
  listEmployees(queryParams.value).then(response => {
    employeeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

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

/** 查询部门列表 */
function getDeptData() {
  getDeptList().then(response => {
    deptList.value = response.data || [];
  });
}

/** 查询职位列表 */
function getPostData() {
  getPostList({ pageNum: 1, pageSize: 100 }).then(response => {
    postList.value = response.rows || [];
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    employeeId: null,
    libraryId: null,
    employeeNumber: null,
    employeeName: null,
    idCardNumber: null,
    contactPhone: null,
    department: null,
    position: null,
    hireDate: null,
    employeeStatus: "ACTIVE",
    salaryUnit: [], // 改为数组
    salaryType: null, // 薪资类型
    salaryAmount: null, // 薪资金额
    isTemporary: false,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("employeeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.employeeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加员工";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _employeeId = row.employeeId || ids.value[0];
  getEmployee(_employeeId).then(response => {
    // 后端返回的DTO字段名与前端表单字段名不同，需要正确映射
    const employeeData = response.data;
    
    // 映射后端DTO字段名到前端表单字段名
    form.value = {
      employeeId: employeeData.employeeId,
      libraryId: employeeData.libraryId,
      employeeNumber: employeeData.employeeNumber,
      employeeName: employeeData.name, // DTO中是name，表单中是employeeName
      idCardNumber: employeeData.idCard, // DTO中是idCard，表单中是idCardNumber
      contactPhone: employeeData.phoneNumber, // DTO中是phoneNumber，表单中是contactPhone
      department: employeeData.department,
      position: employeeData.position,
      employeeStatus: employeeData.status || "ACTIVE", // DTO中是status，表单中是employeeStatus
      salaryUnit: employeeData.salaryUnits || [], // DTO中是数组，表单中也是数组（多选）
      isTemporary: employeeData.isTemporary || false,
      hireDate: employeeData.hireDate,
      createTime: employeeData.createTime,
      updateTime: employeeData.updateTime
    };
    
    // 处理薪资数据 - 将后端的具体薪资字段转换为前端的薪资类型和金额
    if (employeeData.monthlySalary) {
      form.value.salaryType = 'monthly';
      form.value.salaryAmount = employeeData.monthlySalary;
    } else if (employeeData.dailySalary) {
      form.value.salaryType = 'daily';
      form.value.salaryAmount = employeeData.dailySalary;
    } else if (employeeData.hourlySalary) {
      form.value.salaryType = 'hourly';
      form.value.salaryAmount = employeeData.hourlySalary;
    } else {
      form.value.salaryType = null;
      form.value.salaryAmount = null;
    }
    
    // 处理日期格式 - 如果是ISO格式，转换为YYYY-MM-DD
    if (form.value.hireDate) {
      const date = new Date(form.value.hireDate);
      if (!isNaN(date.getTime())) {
        form.value.hireDate = date.toISOString().split('T')[0];
      }
    }
    
    open.value = true;
    title.value = "修改员工";
  }).catch(error => {
    console.error('获取员工信息失败:', error);
    proxy.$modal.msgError("获取员工信息失败");
  });
}

/** 查看详情 */
function handleView(row) {
  getEmployee(row.employeeId).then(response => {
    const employeeData = response.data;
    
    // 映射DTO字段到详情显示字段
    detailData.value = {
      employeeId: employeeData.employeeId,
      libraryId: employeeData.libraryId,
      libraryName: employeeData.libraryName, // 员工库名称
      employeeNumber: employeeData.employeeNumber,
      employeeName: employeeData.name, // DTO中是name
      idCardNumber: employeeData.idCard, // DTO中是idCard
      contactPhone: employeeData.phoneNumber, // DTO中是phoneNumber
      department: employeeData.department,
      position: employeeData.position,
      employeeStatus: employeeData.status, // DTO中是status
      salaryUnit: employeeData.salaryUnits ? employeeData.salaryUnits.join(', ') : '', // DTO中是数组，显示时用逗号分隔
      monthlySalary: employeeData.monthlySalary, // 月薪
      dailySalary: employeeData.dailySalary, // 日薪
      hourlySalary: employeeData.hourlySalary, // 时薪
      isTemporary: employeeData.isTemporary || false,
      hireDate: employeeData.hireDate,
      createTime: employeeData.createTime,
      updateTime: employeeData.updateTime
    };
    
    detailOpen.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["employeeRef"].validate(valid => {
    if (valid) {
      // 如果没有员工工号且不是修改模式，自动生成
      if (!form.value.employeeNumber && !form.value.employeeId && form.value.libraryId) {
        generateEmployeeNumber(form.value.libraryId).then(response => {
          if (response.data) {
            form.value.employeeNumber = response.data;
            submitEmployeeData();
          } else {
            proxy.$modal.msgError("员工工号生成失败，请手动输入");
          }
        }).catch(error => {
          console.error('生成员工工号失败:', error);
          proxy.$modal.msgError("员工工号生成失败，请手动输入");
        });
      } else {
        submitEmployeeData();
      }
    }
  });
}

/** 提交员工数据 */
function submitEmployeeData() {
  // 将前端表单字段映射为后端DTO期望的字段
  const submitData = {
    employeeId: form.value.employeeId,
    libraryId: form.value.libraryId,
    employeeNumber: form.value.employeeNumber,
    name: form.value.employeeName, // 表单中是employeeName，DTO中是name
    idCard: form.value.idCardNumber, // 表单中是idCardNumber，DTO中是idCard
    phoneNumber: form.value.contactPhone, // 表单中是contactPhone，DTO中是phoneNumber
    department: form.value.department,
    position: form.value.position,
    status: form.value.employeeStatus, // 表单中是employeeStatus，DTO中是status
    salaryUnits: form.value.salaryUnit || [], // 表单中是数组，DTO中也是数组
    hireDate: form.value.hireDate,
    isTemporary: form.value.isTemporary
  };
  
  // 根据薪资类型设置对应的薪资字段，并清空其他薪资字段
  // 重置所有薪资字段
  submitData.monthlySalary = null;
  submitData.dailySalary = null;
  submitData.hourlySalary = null;
  
  if (form.value.salaryType && form.value.salaryAmount) {
    const salaryAmount = parseFloat(form.value.salaryAmount);
    if (!isNaN(salaryAmount) && salaryAmount > 0) {
      switch (form.value.salaryType) {
        case 'monthly':
          submitData.monthlySalary = salaryAmount;
          break;
        case 'daily':
          submitData.dailySalary = salaryAmount;
          break;
        case 'hourly':
          submitData.hourlySalary = salaryAmount;
          break;
      }
    }
  }
  
  if (form.value.employeeId != null) {
    updateEmployee(submitData).then(response => {
      proxy.$modal.msgSuccess("修改成功");
      open.value = false;
      getList();
    });
  } else {
    createEmployee(submitData).then(response => {
      proxy.$modal.msgSuccess("新增成功");
      open.value = false;
      getList();
    });
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _employeeIds = row.employeeId || ids.value;
  proxy.$modal.confirm('是否确认删除选中的员工数据？').then(function() {
    return deleteEmployee(_employeeIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 批量修改按钮操作 */
function handleBatchUpdate() {
  if (ids.value.length === 0) {
    proxy.$modal.msgError("请选择要修改的员工");
    return;
  }
  
  batchUpdateForm.value = {
    updateField: null,
    updateValue: null
  };
  batchUpdateOpen.value = true;
}

/** 批量转移按钮操作 */
function handleBatchTransfer() {
  if (ids.value.length === 0) {
    proxy.$modal.msgError("请选择要转移的员工");
    return;
  }
  
  batchTransferForm.value = {
    targetLibraryId: null
  };
  batchTransferOpen.value = true;
}

/** 修改字段变化处理 */
function handleUpdateFieldChange() {
  batchUpdateForm.value.updateValue = null;
}

/** 获取更新值的占位符 */
function getUpdateValuePlaceholder() {
  const field = batchUpdateForm.value.updateField;
  const placeholders = {
    contactPhone: '请输入联系电话',
    dailySalary: '请输入日薪金额',
    monthlySalary: '请输入月薪金额',
    hourlySalary: '请输入小时薪资'
  };
  return placeholders[field] || '请输入新值';
}

/** 提交批量修改 */
function submitBatchUpdate() {
  proxy.$refs["batchUpdateRef"].validate(valid => {
    if (valid) {
      const updateFields = {};
      updateFields[batchUpdateForm.value.updateField] = batchUpdateForm.value.updateValue;
      
      const requestData = {
        employeeIds: ids.value,
        updateFields: updateFields
      };
      
      proxy.$modal.confirm(`确认对选中的 ${ids.value.length} 个员工进行批量修改？`).then(() => {
        return batchUpdateEmployees(requestData);
      }).then(response => {
        proxy.$modal.msgSuccess(response.msg || "批量修改成功");
        batchUpdateOpen.value = false;
        getList();
      }).catch(error => {
        console.error('批量修改失败:', error);
      });
    }
  });
}

/** 提交批量转移 */
function submitBatchTransfer() {
  proxy.$refs["batchTransferRef"].validate(valid => {
    if (valid) {
      const requestData = {
        employeeIds: ids.value,
        targetLibraryId: batchTransferForm.value.targetLibraryId
      };
      
      proxy.$modal.confirm(`确认将选中的 ${ids.value.length} 个员工转移到目标员工库？`).then(() => {
        return batchTransferEmployees(requestData);
      }).then(response => {
        proxy.$modal.msgSuccess(response.msg || "批量转移成功");
        batchTransferOpen.value = false;
        getList();
      }).catch(error => {
        console.error('批量转移失败:', error);
      });
    }
  });
}

/** 导入按钮操作 */
function handleImport() {
  importLibraryId.value = null;
  importFile.value = null;
  importOpen.value = true;
}

/** 文件选择 */
function handleFileChange(file) {
  importFile.value = file.raw;
}

/** 提交导入 */
function submitImport() {
  if (!importLibraryId.value) {
    proxy.$modal.msgError("请选择员工库");
    return;
  }
  if (!importFile.value) {
    proxy.$modal.msgError("请选择文件");
    return;
  }
  
  const formData = new FormData();
  formData.append('file', importFile.value);
  formData.append('libraryId', importLibraryId.value);
  
  importErpFile(formData).then(response => {
    proxy.$modal.msgSuccess("导入成功");
    importOpen.value = false;
    getList();
  });
}

/** OCR识别按钮操作 */
function handleOcr() {
  ocrLibraryId.value = null;
  ocrFile.value = null;
  ocrOpen.value = true;
}

/** OCR文件选择 */
function handleOcrFileChange(file) {
  ocrFile.value = file.raw;
}

/** 提交OCR识别 */
function submitOcr() {
  if (!ocrLibraryId.value) {
    proxy.$modal.msgError("请选择员工库");
    return;
  }
  if (!ocrFile.value) {
    proxy.$modal.msgError("请选择图片");
    return;
  }
  
  const formData = new FormData();
  formData.append('file', ocrFile.value);
  formData.append('libraryId', ocrLibraryId.value);
  
  extractEmployeeByOcr(formData).then(response => {
    proxy.$modal.msgSuccess("识别成功");
    ocrOpen.value = false;
    
    // 重置表单
    reset();
    
    // OCR返回的数据可能使用不同的字段名，需要适配
    const ocrData = response.data;
    
    // 设置基本信息
    form.value.libraryId = ocrLibraryId.value;
    
    // 映射OCR识别的字段到表单字段
    if (ocrData.employeeName || ocrData.name) {
      form.value.employeeName = ocrData.employeeName || ocrData.name;
    }
    if (ocrData.idCardNumber || ocrData.idCard) {
      form.value.idCardNumber = ocrData.idCardNumber || ocrData.idCard;
    }
    if (ocrData.contactPhone || ocrData.phoneNumber) {
      form.value.contactPhone = ocrData.contactPhone || ocrData.phoneNumber;
    }
    if (ocrData.employeeNumber) {
      form.value.employeeNumber = ocrData.employeeNumber;
    }
    if (ocrData.department) {
      form.value.department = ocrData.department;
    }
    if (ocrData.position) {
      form.value.position = ocrData.position;
    }
    if (ocrData.salaryUnit) {
      // 如果OCR返回的是字符串，转换为数组；如果已经是数组，直接使用
      if (typeof ocrData.salaryUnit === 'string') {
        form.value.salaryUnit = ocrData.salaryUnit.split(',').map(item => item.trim());
      } else if (Array.isArray(ocrData.salaryUnit)) {
        form.value.salaryUnit = ocrData.salaryUnit;
      }
    }
    
    // 处理日期格式
    if (ocrData.hireDate) {
      const date = new Date(ocrData.hireDate);
      if (!isNaN(date.getTime())) {
        form.value.hireDate = date.toISOString().split('T')[0];
      }
    }
    
    // 设置默认值
    if (!form.value.employeeStatus) {
      form.value.employeeStatus = "ACTIVE";
    }
    if (form.value.isTemporary === undefined || form.value.isTemporary === null) {
      form.value.isTemporary = false;
    }
    
    open.value = true;
    title.value = "添加员工（OCR识别）";
  }).catch(error => {
    console.error('OCR识别失败:', error);
    proxy.$modal.msgError("OCR识别失败");
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('credit/employee/export', {
    ...queryParams.value
  }, `employee_${new Date().getTime()}.xlsx`);
}

/** 格式化日期 */
function formatDate(date) {
  if (!date) return '';
  return proxy.parseTime(date, '{y}-{m}-{d}');
}

/** 格式化日期时间 */
function formatDateTime(dateTime) {
  if (!dateTime) return '';
  return proxy.parseTime(dateTime, '{y}-{m}-{d} {h}:{i}:{s}');
}

/** 获取薪资金额占位符 */
function getSalaryPlaceholder() {
  const salaryType = form.value.salaryType;
  const placeholders = {
    monthly: '请输入月薪金额',
    daily: '请输入日薪金额',
    hourly: '请输入小时薪金额'
  };
  return placeholders[salaryType] || '请输入薪资金额';
}

/** 薪资类型变化处理 */
function handleSalaryTypeChange() {
  // 清空薪资金额，让用户重新输入
  form.value.salaryAmount = null;
  
  // 根据薪资类型给出提示
  const salaryType = form.value.salaryType;
  if (salaryType) {
    const typeNames = {
      monthly: '月薪',
      daily: '日薪', 
      hourly: '时薪'
    };
    console.log(`已选择${typeNames[salaryType]}，请输入对应金额`);
  }
}

/** 验证员工工号是否重复 */
function validateEmployeeNumber(rule, value, callback) {
  if (!value) {
    callback();
    return;
  }
  
  // 如果是修改模式且工号没有变化，跳过验证
  if (form.value.employeeId && form.value.employeeNumber === value) {
    callback();
    return;
  }
  
  // 检查工号是否已存在
  listEmployees({ employeeNumber: value, pageNum: 1, pageSize: 1 }).then(response => {
    if (response.rows && response.rows.length > 0) {
      // 如果是修改模式，检查是否是当前员工
      const existingEmployee = response.rows[0];
      if (form.value.employeeId && existingEmployee.employeeId === form.value.employeeId) {
        callback();
      } else {
        callback(new Error('员工工号已存在'));
      }
    } else {
      callback();
    }
  }).catch(() => {
    callback();
  });
}

/** 生成员工工号 */
function handleGenerateEmployeeNumber() {
  if (!form.value.libraryId) {
    proxy.$modal.msgError("请先选择员工库");
    return;
  }
  
  generateEmployeeNumber(form.value.libraryId).then(response => {
    if (response) {
      form.value.employeeNumber = response.msg;
    //  proxy.$modal.msgSuccess("员工工号生成成功");
    } else {
      proxy.$modal.msgError("员工工号生成失败");
    }
  }).catch(error => {
    console.error('生成员工工号失败:', error);
    proxy.$modal.msgError("员工工号生成失败");
  });
}

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