<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <!-- <el-button
          type="primary"
          plain
          @click="handleImport"
          v-hasPermi="['hr:salary-month-record:update']"
        >
          薪资核算
        </el-button> -->
        <!--        <el-button-->
        <!--          type="success"-->
        <!--          plain-->
        <!--          @click="handleExport"-->
        <!--          :loading="exportLoading"-->
        <!--          v-hasPermi="['hr:salary-month-record:export']"-->
        <!--        >-->
        <!--          <Icon icon="ep:download" class="mr-5px" /> 导出-->
        <!--        </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <!--      <el-table-column type="selection" width="55" />-->
      <el-table-column label="标题" align="center" prop="title" min-width="100px" >
        <template #default="scope">
            <span
              class="employee-name-highlight cursor-pointer"
              @click="openEmployeeDrawer(scope.row)"
            >
              {{ scope.row.title }}
            </span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="所属公司">
        <template #default="scope">
          {{ deptList.find((dept) => dept.id === scope.row.companyId)?.name }}
        </template>
      </el-table-column>
      <el-table-column label="年" align="center" prop="year" />
      <el-table-column label="月" align="center" prop="month" />
      <el-table-column label="应发工资" align="center" prop="expectedPaySalary" />
      <el-table-column label="实发工资" align="center" prop="realPaySalary" />
      <el-table-column label="个人所得税" align="center" prop="personalTax" />
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 员工薪资详情抽屉 -->
  <el-drawer
    v-model="drawerVisible"
    title="员工薪资详情"
    size="60%"
    direction="rtl"
    :destroy-on-close="true"
  >
    <el-descriptions title="员工信息" :column="2" border class="mt-4">
      <el-descriptions-item label="员工姓名">{{
          selectedEmployee?.employeeName
        }}</el-descriptions-item>
      <el-descriptions-item label="部门">{{ selectedEmployee?.deptName }}</el-descriptions-item>
      <el-descriptions-item label="岗位">{{ selectedEmployee?.post || '--' }}</el-descriptions-item>
      <el-descriptions-item label="工号">{{ selectedEmployee?.workNo }}</el-descriptions-item>
      <el-descriptions-item label="身份证">{{ selectedEmployee?.idNumber }}</el-descriptions-item>
      <el-descriptions-item label="银行卡">{{ selectedEmployee?.bankCard }}</el-descriptions-item>
      <el-descriptions-item label="开户行">{{ selectedEmployee?.bankName }}</el-descriptions-item>
      <el-descriptions-item label="联系方式">{{ selectedEmployee?.mobile }}</el-descriptions-item>
      <el-descriptions-item label="家庭住址">{{ selectedEmployee?.address }}</el-descriptions-item>
    </el-descriptions>
    <el-descriptions :title="employeeSalaryTitle" :column="2" border class="mt-4">
      <el-descriptions-item
        v-for="item in selectedEmployeeSalaryItems"
        :key="item.field"
        :label="item.name"
      >
        {{ item.value }}
      </el-descriptions-item>
    </el-descriptions>
<!--    <el-descriptions title="公司成本" :column="2" border class="mt-4" style="margin-top: 60px">-->
<!--      <el-descriptions-item v-for="item in companySalaryItems" :key="item.field" :label="item.name">-->
<!--        {{ item.value }}-->
<!--      </el-descriptions-item>-->
<!--    </el-descriptions>-->
  </el-drawer>
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { SalaryMonthRecordApi, SalaryMonthRecord } from '@/api/hr/salarymonthrecord'
import { DICT_TYPE } from '@/utils/dict'
import * as DeptApi from '@/api/system/dept'
const router = useRouter()
/** 每月薪资记录 列表 */
defineOptions({ name: 'HrSalaryMonthRecord' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<SalaryMonthRecord[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  title: undefined,
  companyId: undefined,
  year: undefined,
  month: undefined,
  num: undefined,
  startTime: [],
  endTime: [],
  personalInsuranceAmount: undefined,
  personalProvidentFundAmount: undefined,
  corporateInsuranceAmount: undefined,
  corporateProvidentFundAmount: undefined,
  expectedPaySalary: undefined,
  personalTax: undefined,
  realPaySalary: undefined,
  optionHead: undefined,
  examineRecordId: undefined,
  checkStatus: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const deptList = ref<DeptApi.DeptVO[]>([]) // 员工列表
const companyOptions = ref([])
const fieldList = ref([])
const getTableHeader = async () => {
  loading.value = true
  SalaryMonthRecordApi.querySalaryOptionHead()
    .then((res) => {
      loading.value = false
      const defaultTables = [
        { field: 'employeeName', name: '姓名', width: 100 },
        { field: 'workNo', name: '工号', width: 100 },
        { field: 'deptName', name: '部门', width: 100 },
        { field: 'post', name: '岗位', width: 100 },
        { field: 'statusName', name: '状态', width: 100 },
        { field: 'projectName', name: '所属项目', width: 100 }
      ]

      const otherTables = res.map((item) => {
        return {
          field: item.code.toString(),
          name: item.name,
          isFixed: item.isFixed === 1,
          width: 150
        }
      })

      const lastTables = [
        { field: 'remark', name: '备注', width: 100 },
        { field: 'idNumber', name: '身份证', width: 150 },
        { field: 'bankCard', name: '银行卡', width: 150 },
        { field: 'bankName', name: '开户行', width: 150 },
        { field: 'mobile', name: '联系方式', width: 150 },
        { field: 'address', name: '家庭住址', width: 180 }
      ]
      otherTablesRef.value = otherTables // 保存otherTables引用
      fieldList.value = defaultTables.concat(otherTables).concat(lastTables)
    })
    .catch((error) => {
      console.log(error)

      loading.value = false
    })
}
// 打开员工详情抽屉
const drawerVisible = ref(false)
const selectedEmployee = ref({})
const selectedEmployeeSalaryItems = ref([])
const companySalaryItems = ref([])
const otherTablesRef = ref([])
const openEmployeeDrawer = (row) => {
  const params = {
    sRecordId: row.id,
    page: 1,
    limit: 1,
    employeeId: row.employeeId,
    ...queryParams
  }
  SalaryMonthRecordApi.querySalaryPageList(params)
    .then((res) => {
      console.log(res)
      const resData = res
      const listdata = resData.list
      listdata.forEach((item) => {
        const salary = item.salary || []
        salary.forEach((sItem) => {
          item[sItem.code] = sItem.value
        })
      })
      loading.value = false
      selectedEmployee.value = listdata[0]
      selectedEmployeeSalaryItems.value = otherTablesWithValues(listdata[0])
      companySalaryItems.value = companyOtherTablesWithValues(listdata[0])
      drawerVisible.value = true
    })
    .catch(() => {
      loading.value = false
    })

}
// 为当前行提取otherTables字段和对应的值
const otherTablesWithValues = (row) => {
  const result = []
  // 定义需要展示的工资字段名称列表
  const requiredFields = [
    '基本工资',
    '加班工资',
    '计时工资',
    '计件工资',
    '绩效奖励',
    '高温津贴',
    '电脑补贴',
    '餐补',
    '房补',
    '岗位工资',
    '考勤扣款',
    '质量处罚',
    '公积金补贴',
    '春节往返交通补贴',
    '新员工介绍费',
    '社保扣款',
    '所得税',
    '应发工资',
    '实发工资'
  ]

  otherTablesRef.value.forEach((table) => {
    // 只保留名称在requiredFields列表中的字段
    if (requiredFields.includes(table.name)) {
      const value = row[table.field]
      result.push({
        field: table.field,
        name: table.name,
        value: isEmpty(value) ? '--' : Number(value).toFixed(2)
      })
    }
  })
  return result
}
const companyOtherTablesWithValues = (row) => {
  const result = []
  // 定义需要展示的工资字段名称列表
  const requiredFields = ['保险补贴', '公司承担社保', '管理费', '开票7%', '公司成本合计']

  fieldList.value.forEach((table) => {
    // 只保留名称在requiredFields列表中的字段
    if (requiredFields.includes(table.name)) {
      const value = row[table.field]
      result.push({
        field: table.field,
        name: table.name,
        value: isEmpty(value) ? '--' : Number(value).toFixed(2)
      })
    }
  })
  return result
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SalaryMonthRecordApi.queryEmployeeHistorySalaryList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}


/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SalaryMonthRecordApi.deleteSalaryMonthRecord(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
    // currentRow.value = {}
  } catch {}
}
const handleComplete = async (id: number) => {
  try {
    // 完成的二次确认
    await message.confirm('确认完成核算?')
    // 发起完成
    await SalaryMonthRecordApi.completeSalaryMonthRecord(id)
    message.success(t('common.updateSuccess'))
    // 刷新列表
    await getList()
    // currentRow.value = {}
  } catch {}
}

/** 批量删除每月薪资记录 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await SalaryMonthRecordApi.deleteSalaryMonthRecordList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: SalaryMonthRecord[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SalaryMonthRecordApi.exportSalaryMonthRecord(queryParams)
    download.excel(data, '每月薪资记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
/** 初始化 **/
onMounted(async () => {
  await getTableHeader()
  await getList()
  // 加载部门树
  deptList.value = await DeptApi.getSimpleDeptList()
})
</script>
<style scoped>
.employee-name-highlight {
  font-weight: 500;
  color: #409eff;
}

.cursor-pointer {
  cursor: pointer;
}

.p-2 {
  padding: 8px;
}

.font-bold {
  font-weight: 600;
}

.mb-2 {
  margin-bottom: 8px;
}

.grid {
  display: grid;
}

.grid-cols-2 {
  grid-template-columns: 1fr 1fr;
}

.gap-2 {
  gap: 8px;
}

.text-sm {
  font-size: 12px;
}

.text-gray-600 {
  color: #606266;
}

.ml-1 {
  margin-left: 4px;
}
</style>
<style>
.el-drawer__body {
  padding-top: 0 !important;
}

.el-drawer__header {
  margin-bottom: 10px !important;
}
</style>
