<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="库名称" prop="libraryName">
        <el-input
          v-model="queryParams.libraryName"
          placeholder="请输入员工库名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="libraryStatus">
        <el-select v-model="queryParams.libraryStatus" placeholder="请选择状态" clearable>
          <el-option label="启用" value="ACTIVE" />
          <el-option label="禁用" value="INACTIVE" />
        </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="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['credit:employee:edit']"
        >修改</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>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="libraryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" min-width="55" align="center" />
      <el-table-column label="库名称" align="center" prop="libraryName" />
      <el-table-column label="描述" align="center" prop="description" min-width='100' />
      <el-table-column label="员工数量" align="center" prop="totalEmployees" />
      <el-table-column label="状态" align="center" prop="libraryStatus">
        <template #default="scope">
          <el-tag :type="scope.row.libraryStatus === 'ACTIVE' ? 'success' : 'danger'">
            {{ scope.row.libraryStatus === 'ACTIVE' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="200" >
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleViewEmployees(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="600px" append-to-body>
      <el-form ref="libraryRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="库名称" prop="libraryName">
              <el-input v-model="form.libraryName" placeholder="请输入员工库名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入描述" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="状态" prop="libraryStatus">
              <el-radio-group v-model="form.libraryStatus">
                <el-radio label="ACTIVE">启用</el-radio>
                <el-radio label="INACTIVE">禁用</el-radio>
              </el-radio-group>
            </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>

    <!-- 查看员工库员工对话框 -->
    <el-dialog :title="employeeDialogTitle" v-model="employeeDialogOpen" width="1200px" append-to-body>
      <div class="employee-search-form">
        <el-form :model="employeeQueryParams" :inline="true" label-width="80px">
          <el-form-item label="员工编号" prop="employeeNumber">
            <el-input
              v-model="employeeQueryParams.employeeNumber"
              placeholder="请输入员工编号"
              clearable
              style="width: 180px"
              @keyup.enter="getEmployeeList"
            />
          </el-form-item>
          <el-form-item label="姓名" prop="employeeName">
            <el-input
              v-model="employeeQueryParams.employeeName"
              placeholder="请输入姓名"
              clearable
              style="width: 180px"
              @keyup.enter="getEmployeeList"
            />
          </el-form-item>
          <el-form-item label="状态" prop="employeeStatus">
            <el-select v-model="employeeQueryParams.employeeStatus" placeholder="请选择状态" clearable style="width: 120px">
              <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="getEmployeeList">搜索</el-button>
            <el-button icon="Refresh" @click="resetEmployeeQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table v-loading="employeeLoading" :data="employeeList" max-height="400">
        <el-table-column label="员工编号" align="center" prop="employeeNumber" width="120" />
        <el-table-column label="姓名" align="center" prop="employeeName" width="120" />
        <el-table-column label="身份证号" align="center" prop="idCardNumber" :show-overflow-tooltip="true" width="180" />
        <el-table-column label="联系电话" align="center" prop="contactPhone" width="130" />
        <el-table-column label="部门" align="center" prop="department" width="120" />
        <el-table-column label="职位" align="center" prop="position" width="120" />
        <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" 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="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="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>

      <pagination
        v-show="employeeTotal > 0"
        :total="employeeTotal"
        v-model:page="employeeQueryParams.pageNum"
        v-model:limit="employeeQueryParams.pageSize"
        @pagination="getEmployeeList"
        style="margin-top: 20px"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="employeeDialogOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EmployeeLibrary">
import { listEmployeeLibraries, createEmployeeLibrary, updateEmployeeLibrary, deleteEmployeeLibrary, listEmployees } from "@/api/credit/employee";

const { proxy } = getCurrentInstance();

const libraryList = ref([]);
const employeeList = ref([]);
const open = ref(false);
const employeeDialogOpen = ref(false);
const loading = ref(true);
const employeeLoading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const employeeTotal = ref(0);
const title = ref("");
const employeeDialogTitle = ref("");
const currentLibrary = ref({});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    libraryName: null,
    libraryStatus: null
  },
  employeeQueryParams: {
    pageNum: 1,
    pageSize: 10,
    libraryId: null,
    employeeNumber: null,
    employeeName: null,
    employeeStatus: null
  },
  rules: {
    libraryName: [
      { required: true, message: "员工库名称不能为空", trigger: "blur" }
    ],
    libraryStatus: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ]
  }
});

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

/** 查看员工按钮操作 */
function handleViewEmployees(row) {
  currentLibrary.value = row;
  employeeDialogTitle.value = `${row.libraryName} - 员工列表`;
  employeeQueryParams.value.libraryId = row.libraryId;
  employeeQueryParams.value.pageNum = 1;
  employeeQueryParams.value.employeeNumber = null;
  employeeQueryParams.value.employeeName = null;
  employeeQueryParams.value.employeeStatus = null;
  employeeDialogOpen.value = true;
  getEmployeeList();
}

/** 查询员工列表 */
function getEmployeeList() {
  employeeLoading.value = true;
  listEmployees(employeeQueryParams.value).then(response => {
    employeeList.value = response.rows;
    employeeTotal.value = response.total;
    employeeLoading.value = false;
  }).catch(() => {
    employeeLoading.value = false;
  });
}

/** 重置员工查询 */
function resetEmployeeQuery() {
  employeeQueryParams.value.employeeNumber = null;
  employeeQueryParams.value.employeeName = null;
  employeeQueryParams.value.employeeStatus = null;
  employeeQueryParams.value.pageNum = 1;
  getEmployeeList();
}

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

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

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

// 表单重置
function reset() {
  form.value = {
    libraryId: null,
    libraryName: null,
    description: null,
    libraryStatus: "ACTIVE"
  };
  proxy.resetForm("libraryRef");
}

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

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

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

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

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _libraryId = row.libraryId || ids.value;
  // 复制完整的行数据，确保所有字段都被正确设置
  form.value = {
    libraryId: row.libraryId,
    libraryName: row.libraryName,
    description: row.description,
    libraryStatus: row.libraryStatus || 'ACTIVE'
  };
  open.value = true;
  title.value = "修改员工库";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["libraryRef"].validate(valid => {
    if (valid) {
      if (form.value.libraryId != null) {
        updateEmployeeLibrary(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        createEmployeeLibrary(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _libraryIds = row.libraryId || ids.value;
  proxy.$modal.confirm('是否确认删除员工库编号为"' + _libraryIds + '"的数据项？').then(function() {
    return deleteEmployeeLibrary(_libraryIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

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

<style scoped>
.employee-search-form {
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 6px;
  margin-bottom: 16px;
}

.employee-search-form .el-form-item {
  margin-bottom: 12px;
}

.dialog-footer {
  text-align: right;
}
</style>