<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="employeeName">
        <el-input
          v-model="queryParams.employeeName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="工号" prop="workNo">
        <el-input
          v-model="queryParams.workNo"
          placeholder="请输入工号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="岗位" prop="post">
        <el-input
          v-model="queryParams.post"
          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
          v-if="route.query.pageType != 'view'"
          type="primary"
          plain
          @click="handleImport()"
        >
          <Icon icon="ep:plus" 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()"
          v-hasPermi="['hr:salary-month-record:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="primary"
          plain
          @click="taxHandleImport()"
          v-hasPermi="['hr:salary-month-tax:query']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导入所得税
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      ref="tableList"
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
      border
    >
      <el-table-column
        v-for="(item, index) in fieldList"
        :key="index"
        :fixed="index == 0"
        :prop="item.field"
        :label="item.name"
        :min-width="item.width"
        :formatter="fieldFormatter"
        show-overflow-tooltip
      >
        <template #default="scope">
          <!-- 为employeeName字段添加高亮和浮窗 -->
          <template v-if="item.field === 'employeeName'">
            <span
              class="employee-name-highlight cursor-pointer"
              @click="openEmployeeDrawer(scope.row)"
            >
              {{ fieldFormatter(scope.row, { property: item.field }) }}
            </span>
          </template>
          <!-- 其他字段保持原有的格式化方式 -->
          <template v-else>
            {{ fieldFormatter(scope.row, { property: item.field }, item) }}
          </template>
        </template>
      </el-table-column>
      <!--      <el-table-column label="状态  0待审核、1通过、2拒绝、3审核中 4:撤回 5 未提交  10 历史薪资 11核算完成" align="center" prop="checkStatus" />-->
      <!-- <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <template>
            <el-button
              link
              type="primary"
              @click="handleImport(scope.row)"
              v-hasPermi="['hr:salary-month-record:update']"
            >
              核算工资
            </el-button>
          </template>
        </template>
      </el-table-column> -->
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ExportFiledForm ref="formRef" @success="getList" />
  <hsImportForm ref="importFormRef" @success="getList" />
  <hsTaxImportForm ref="hsTaximportFormRef" @success="getList" />
  <!-- 员工薪资详情抽屉 -->
  <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?.postName || '--'
      }}</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 { nextTick } from 'vue'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { SalaryMonthRecordApi, SalaryMonthRecord } from '@/api/hr/salarymonthrecord'
import ExportFiledForm from './ExportFiledForm.vue'
import hsImportForm from './hsImportForm.vue'
import hsTaxImportForm from './hsTaxImportForm.vue'
import { DICT_TYPE } from '@/utils/dict'

/** 每月薪资记录 列表 */
defineOptions({ name: 'HrSalaryMonthRecord' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()
const route = useRoute()
const list = ref<SalaryMonthRecord[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  // pageNo: 1,
  // pageSize: 10,
  employeeName: undefined,
  workNo: undefined,
  deptName: undefined,
  post: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
/**
 * 获取最新的薪资配置
 */
const loading = ref(false)
const lastData = ref([])
const tabType = ref('0')
const filterObj = ref({})
const currentPage = ref(1)
const pageSize = ref(10)
const sumData = ref(null)
const initStatusConfig = ref({})
const initDataConfig = ref({})
// 控制抽屉显示和选中员工的数据
const drawerVisible = ref(false)
const selectedEmployee = ref({})
const selectedEmployeeSalaryItems = ref([])
const companySalaryItems = ref([])
const employeeSalaryTitle = computed(() => {
  return `${new Date().getFullYear()}年${new Date().getMonth() + 1}月工资`
})
const postParams = computed(() => {
  const params = {}
  if (lastData.value) {
    params.srecordId = lastData.value.srecordId
  }

  params.type = tabType.value

  for (var key in filterObj.value) {
    params[key] = filterObj.value[key]
  }
  return params
})

const getLastData = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-line
    if (lastData.value) {
      return resolve(lastData.value)
    } else {
      loading.value = true
      SalaryMonthRecordApi.queryLastSalaryMonthRecord()
        .then((res) => {
          lastData.value = res.data
          loading.value = false
          resolve(lastData.value)
        })
        .catch(() => {
          loading.value = false
          reject && reject()
        })
    }
  })
}
const initList = {
  list: [
    {
      employeeId: '1953656263244386304',
      jobNumber: '10001',
      employeeName: '欧',
      deptName: '合肥子公司',
      post: '',
      actualWorkDay: 21.75,
      needWorkDay: 21.75,
      salary: [
        {
          id: null,
          code: 10,
          value: '0',
          isFixed: 0,
          name: '基本工资'
        },
        {
          id: null,
          code: 10101,
          value: '1000',
          isFixed: 0,
          name: '基本工资'
        },
        {
          id: null,
          code: 10102,
          value: '1000',
          isFixed: 0,
          name: '岗位工资'
        },
        {
          id: null,
          code: 10103,
          value: '1000',
          isFixed: 0,
          name: '职务工资'
        },
        {
          id: null,
          code: 20,
          value: '0',
          isFixed: 0,
          name: '津补贴'
        },
        {
          id: null,
          code: 20101,
          value: '0',
          isFixed: 0,
          name: '住房补贴'
        },
        {
          id: null,
          code: 20102,
          value: '0',
          isFixed: 0,
          name: '高温津贴'
        },
        {
          id: null,
          code: 20103,
          value: '0',
          isFixed: 0,
          name: '交通补贴'
        },
        {
          id: null,
          code: 20104,
          value: '0',
          isFixed: 0,
          name: '餐补'
        },
        {
          id: null,
          code: 30,
          value: '0',
          isFixed: 0,
          name: '浮动工资'
        },
        {
          id: null,
          code: 30101,
          value: '0',
          isFixed: 0,
          name: '绩效工资'
        },
        {
          id: null,
          code: 40,
          value: '0',
          isFixed: 0,
          name: '奖金'
        },
        {
          id: null,
          code: 40101,
          value: '0',
          isFixed: 0,
          name: '季度奖'
        },
        {
          id: null,
          code: 40102,
          value: '0',
          isFixed: 0,
          name: '全勤奖'
        },
        {
          id: null,
          code: 40103,
          value: '0',
          isFixed: 0,
          name: '推荐奖'
        },
        {
          id: null,
          code: 50,
          value: '0',
          isFixed: 0,
          name: '提成工资'
        },
        {
          id: null,
          code: 50101,
          value: '0',
          isFixed: 0,
          name: '销售提成'
        },
        {
          id: null,
          code: 60,
          value: '0',
          isFixed: 0,
          name: '计件工资'
        },
        {
          id: null,
          code: 60101,
          value: '120',
          isFixed: 0,
          name: '计件工资'
        },
        {
          id: null,
          code: 70,
          value: '0',
          isFixed: 0,
          name: '计时工资'
        },
        {
          id: null,
          code: 70101,
          value: '3800',
          isFixed: 0,
          name: '计时工资'
        },
        {
          id: null,
          code: 80,
          value: '0',
          isFixed: 0,
          name: '工龄/司龄工资'
        },
        {
          id: null,
          code: 80101,
          value: '0',
          isFixed: 0,
          name: '工龄工资'
        },
        {
          id: null,
          code: 80102,
          value: '500',
          isFixed: 0,
          name: '司龄工资'
        },
        {
          id: null,
          code: 90,
          value: '0',
          isFixed: 0,
          name: '职称工资'
        },
        {
          id: null,
          code: 90101,
          value: '0',
          isFixed: 0,
          name: '职称工资'
        },
        {
          id: null,
          code: 90102,
          value: '0',
          isFixed: 0,
          name: '技能工资'
        },
        {
          id: null,
          code: 90103,
          value: '0',
          isFixed: 0,
          name: '学历工资'
        },
        {
          id: null,
          code: 100,
          value: '0',
          isFixed: 0,
          name: '代扣代缴'
        },
        {
          id: null,
          code: 100101,
          value: '0',
          isFixed: 0,
          name: '个人社保'
        },
        {
          id: null,
          code: 100102,
          value: '0',
          isFixed: 0,
          name: '个人公积金'
        },
        {
          id: null,
          code: 110,
          value: '0',
          isFixed: 0,
          name: '企业社保'
        },
        {
          id: null,
          code: 110101,
          value: '0',
          isFixed: 0,
          name: '企业社保'
        },
        {
          id: null,
          code: 120,
          value: '0',
          isFixed: 0,
          name: '企业公积金'
        },
        {
          id: null,
          code: 120101,
          value: '0',
          isFixed: 0,
          name: '企业公积金'
        },
        {
          id: null,
          code: 130,
          value: '0',
          isFixed: 0,
          name: '税前补发'
        },
        {
          id: null,
          code: 130101,
          value: '0',
          isFixed: 0,
          name: '税前补发'
        },
        {
          id: null,
          code: 140,
          value: '0',
          isFixed: 0,
          name: '税前补扣'
        },
        {
          id: null,
          code: 140101,
          value: '0',
          isFixed: 0,
          name: '税前补扣'
        },
        {
          id: null,
          code: 150,
          value: '0',
          isFixed: 0,
          name: '税后补发'
        },
        {
          id: null,
          code: 150101,
          value: '0',
          isFixed: 0,
          name: '税后补发'
        },
        {
          id: null,
          code: 160,
          value: '0',
          isFixed: 0,
          name: '税后补扣'
        },
        {
          id: null,
          code: 160101,
          value: '0',
          isFixed: 0,
          name: '党费'
        },
        {
          id: null,
          code: 160102,
          value: '0',
          isFixed: 0,
          name: '工会费'
        },
        {
          id: null,
          code: 160103,
          value: '0',
          isFixed: 0,
          name: '补充医疗'
        },
        {
          id: null,
          code: 170,
          value: '0',
          isFixed: 0,
          name: '特殊计税项'
        },
        {
          id: null,
          code: 170101,
          value: '0',
          isFixed: 0,
          name: '商业保险金'
        },
        {
          id: null,
          code: 180,
          value: '0',
          isFixed: 1,
          name: '加班工资'
        },
        {
          id: null,
          code: 180101,
          value: '0',
          isFixed: 1,
          name: '加班工资'
        },
        {
          id: null,
          code: 190,
          value: '0',
          isFixed: 1,
          name: '考勤扣款明细'
        },
        {
          id: null,
          code: 190101,
          value: '0',
          isFixed: 1,
          name: '迟到扣款'
        },
        {
          id: null,
          code: 190102,
          value: '0',
          isFixed: 1,
          name: '早退扣款'
        },
        {
          id: null,
          code: 190103,
          value: '0',
          isFixed: 1,
          name: '旷工扣款'
        },
        {
          id: null,
          code: 190104,
          value: '0',
          isFixed: 1,
          name: '假期扣款'
        },
        {
          id: null,
          code: 190105,
          value: '0',
          isFixed: 1,
          name: '缺卡扣款'
        },
        {
          id: null,
          code: 190106,
          value: '0',
          isFixed: 1,
          name: '综合扣款'
        },
        {
          id: null,
          code: 200,
          value: '0',
          isFixed: 1,
          name: '考勤扣款合计'
        },
        {
          id: null,
          code: 200101,
          value: '0',
          isFixed: 1,
          name: '考勤扣款合计'
        },
        {
          id: null,
          code: 210,
          value: '0',
          isFixed: 1,
          name: '应发工资'
        },
        {
          id: null,
          code: 210101,
          value: '7420',
          isFixed: 1,
          name: '应发工资'
        },
        {
          id: null,
          code: 220,
          value: '0',
          isFixed: 1,
          name: '应税工资'
        },
        {
          id: null,
          code: 220101,
          value: '2420',
          isFixed: 1,
          name: '应税工资'
        },
        {
          id: null,
          code: 230,
          value: '0',
          isFixed: 1,
          name: '个人所得税'
        },
        {
          id: null,
          code: 230101,
          value: '72.60',
          isFixed: 1,
          name: '个人所得税'
        },
        {
          id: null,
          code: 240,
          value: '0',
          isFixed: 1,
          name: '实发工资'
        },
        {
          id: null,
          code: 240101,
          value: '7347.40',
          isFixed: 1,
          name: '实发工资'
        },
        {
          id: null,
          code: 250,
          value: '0',
          isFixed: 1,
          name: '上月个税累计信息'
        },
        {
          id: null,
          code: 250101,
          value: '0',
          isFixed: 1,
          name: '累计收入额（截至上月）'
        },
        {
          id: null,
          code: 250102,
          value: '0',
          isFixed: 1,
          name: '累计减除费用（截至上月）'
        },
        {
          id: null,
          code: 250103,
          value: '0',
          isFixed: 1,
          name: '累计专项扣除（截至上月）'
        },
        {
          id: null,
          code: 250105,
          value: '0',
          isFixed: 1,
          name: '累计已预缴税额'
        },
        {
          id: null,
          code: 260,
          value: '0',
          isFixed: 1,
          name: '个税专项附加扣除累计'
        },
        {
          id: null,
          code: 260101,
          value: '0',
          isFixed: 1,
          name: '累计子女教育'
        },
        {
          id: null,
          code: 260102,
          value: '0',
          isFixed: 1,
          name: '累计住房租金'
        },
        {
          id: null,
          code: 260103,
          value: '0',
          isFixed: 1,
          name: '累计住房贷款利息'
        },
        {
          id: null,
          code: 260104,
          value: '0',
          isFixed: 1,
          name: '累计赡养老人'
        },
        {
          id: null,
          code: 260105,
          value: '0',
          isFixed: 1,
          name: '累计继续教育'
        },
        {
          id: null,
          code: 270,
          value: '0',
          isFixed: 1,
          name: '个税累计信息'
        },
        {
          id: null,
          code: 270101,
          value: '7420',
          isFixed: 1,
          name: '累计收入额'
        },
        {
          id: null,
          code: 270102,
          value: '5000',
          isFixed: 1,
          name: '累计减除费用'
        },
        {
          id: null,
          code: 270103,
          value: '0',
          isFixed: 1,
          name: '累计专项扣除'
        },
        {
          id: null,
          code: 270104,
          value: '0',
          isFixed: 1,
          name: '累计专项附加扣除'
        },
        {
          id: null,
          code: 270105,
          value: '2420',
          isFixed: 1,
          name: '累计应纳税所得额'
        },
        {
          id: null,
          code: 270106,
          value: '72.60',
          isFixed: 1,
          name: '累计应纳税额'
        },
        {
          id: '0',
          code: 1,
          value: '21.75',
          isFixed: 1,
          name: '计薪天数'
        },
        {
          id: '0',
          code: 2,
          value: '21.75',
          isFixed: 1,
          name: '实际计薪天数'
        }
      ],
      isDel: null,
      sempRecordId: '1953662919097323520'
    }
  ],
  totalRow: 1,
  pageSize: 15,
  pageNumber: 1,
  orders: [],
  extraData: {
    salaryOption: [
      {
        code: 10,
        value: '0'
      },
      {
        code: 10101,
        value: 1000.0
      },
      {
        code: 10102,
        value: 1000.0
      },
      {
        code: 10103,
        value: 1000.0
      },
      {
        code: 20,
        value: '0'
      },
      {
        code: 20101,
        value: '0'
      },
      {
        code: 20102,
        value: '0'
      },
      {
        code: 20103,
        value: '0'
      },
      {
        code: 20104,
        value: '0'
      },
      {
        code: 30,
        value: '0'
      },
      {
        code: 30101,
        value: '0'
      },
      {
        code: 40,
        value: '0'
      },
      {
        code: 40101,
        value: '0'
      },
      {
        code: 40102,
        value: '0'
      },
      {
        code: 40103,
        value: '0'
      },
      {
        code: 50,
        value: '0'
      },
      {
        code: 50101,
        value: '0'
      },
      {
        code: 60,
        value: '0'
      },
      {
        code: 60101,
        value: 120.0
      },
      {
        code: 70,
        value: '0'
      },
      {
        code: 70101,
        value: 3800.0
      },
      {
        code: 80,
        value: '0'
      },
      {
        code: 80101,
        value: '0'
      },
      {
        code: 80102,
        value: 500.0
      },
      {
        code: 90,
        value: '0'
      },
      {
        code: 90101,
        value: '0'
      },
      {
        code: 90102,
        value: '0'
      },
      {
        code: 90103,
        value: '0'
      },
      {
        code: 100,
        value: '0'
      },
      {
        code: 100101,
        value: '0'
      },
      {
        code: 100102,
        value: '0'
      },
      {
        code: 110,
        value: '0'
      },
      {
        code: 110101,
        value: '0'
      },
      {
        code: 120,
        value: '0'
      },
      {
        code: 120101,
        value: '0'
      },
      {
        code: 130,
        value: '0'
      },
      {
        code: 130101,
        value: '0'
      },
      {
        code: 140,
        value: '0'
      },
      {
        code: 140101,
        value: '0'
      },
      {
        code: 150,
        value: '0'
      },
      {
        code: 150101,
        value: '0'
      },
      {
        code: 160,
        value: '0'
      },
      {
        code: 160101,
        value: '0'
      },
      {
        code: 160102,
        value: '0'
      },
      {
        code: 160103,
        value: '0'
      },
      {
        code: 170,
        value: '0'
      },
      {
        code: 170101,
        value: '0'
      },
      {
        code: 180,
        value: '0'
      },
      {
        code: 180101,
        value: '0'
      },
      {
        code: 190,
        value: '0'
      },
      {
        code: 190101,
        value: '0'
      },
      {
        code: 190102,
        value: '0'
      },
      {
        code: 190103,
        value: '0'
      },
      {
        code: 190104,
        value: '0'
      },
      {
        code: 190105,
        value: '0'
      },
      {
        code: 190106,
        value: '0'
      },
      {
        code: 200,
        value: '0'
      },
      {
        code: 200101,
        value: '0'
      },
      {
        code: 210,
        value: '0'
      },
      {
        code: 210101,
        value: 7420.0
      },
      {
        code: 220,
        value: '0'
      },
      {
        code: 220101,
        value: 2420.0
      },
      {
        code: 230,
        value: '0'
      },
      {
        code: 230101,
        value: 72.6
      },
      {
        code: 240,
        value: '0'
      },
      {
        code: 240101,
        value: 7347.4
      },
      {
        code: 250,
        value: '0'
      },
      {
        code: 250101,
        value: '0'
      },
      {
        code: 250102,
        value: '0'
      },
      {
        code: 250103,
        value: '0'
      },
      {
        code: 250105,
        value: '0'
      },
      {
        code: 260,
        value: '0'
      },
      {
        code: 260101,
        value: '0'
      },
      {
        code: 260102,
        value: '0'
      },
      {
        code: 260103,
        value: '0'
      },
      {
        code: 260104,
        value: '0'
      },
      {
        code: 260105,
        value: '0'
      },
      {
        code: 270,
        value: '0'
      },
      {
        code: 270101,
        value: 7420.0
      },
      {
        code: 270102,
        value: 5000.0
      },
      {
        code: 270103,
        value: '0'
      },
      {
        code: 270104,
        value: '0'
      },
      {
        code: 270105,
        value: 2420.0
      },
      {
        code: 270106,
        value: 72.6
      }
    ]
  },
  firstPage: true,
  lastPage: true,
  totalPage: 1
}
/**
 * 列表数据
 */
const getList = () => {
  loading.value = true
  const params = {
    sRecordId: route.query.srecordId,
    page: currentPage.value,
    limit: pageSize.value,
    ...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
        })
      })
      list.value = listdata
      total.value = resData.totalRow || resData.total

      const extraData = resData.extraData || {}
      const salaryOption = extraData.salaryOption

      const sumData = {}
      salaryOption.forEach((sItem) => {
        sumData[sItem.code] = sItem.value
      })
      sumData.value = sumData

      if (total.value > 0) {
        // getTabNum()
      }
      // nextTick(() => {
      //   const warpDom = document.querySelector('.el-table__body-wrapper')
      //   warpDom.scrollTop = 1
      //   if (warpDom.scrollLeft != 0) {
      //     warpDom.scrollLeft = warpDom.scrollLeft - 1
      //   }
      // })
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}
const tabList = [
  {
    label: '计薪人数',
    name: '0',
    num: 0
  },
  {
    label: '新入职',
    name: '1',
    num: 0
  },
  {
    label: '离职',
    name: '2',
    num: 0
  },
  {
    label: '转正',
    name: '3',
    num: 0
  },
  {
    label: '调岗',
    name: '4',
    num: 0
  }
]
const getTabNum = () => {
  SalaryMonthRecordApi.queryEmployeeChangeNum()
    .then((res) => {
      const data = res.data || {}
      tabList.forEach((item) => {
        if (item.name != 'all') {
          item.num = data[parseInt(item.name)] || 0
        }
      })
    })
    .catch(() => {})
}
/**
 * 获取表头
 */
const fieldList = ref([])
const otherTablesRef = ref([])
const lastTables = ref([])
const getTableHeader = () => {
  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: 'postName', 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 fieldFormatter = (row, column, item) => {
  const requiredFields = [
    '工资基数',
    '出勤基数',
    '基本工资',
    '加班工资',
    '计时工资',
    '计件工资',
    '绩效奖励',
    '高温津贴',
    '电脑补贴',
    '餐补',
    '房补',
    '岗位工资',
    '考勤扣款',
    '质量处罚',
    '公积金补贴',
    '春节往返交通补贴',
    '新员工介绍费',
    '应发工资',
    '社保扣款',
    '所得税',
    '实发工资',
    '保险补贴',
    '公司承担社保',
    '管理费',
    '开票7%',
    '公司成本合计'
  ]
  let value = row[column.property]
  if (item && requiredFields.includes(item.name) && !isEmpty(value)) {
    value = Number(value).toFixed(2)
  }
  return isEmpty(value) ? '--' : value
}
// 为当前行提取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.queryHistorySalaryList(queryParams)
//     list.value = data.list
//     total.value = data.total
//   } finally {
//     loading.value = false
//   }
// }
const getExamineData = (lastData) => {
  // 审核信息
  const params = {
    label: 4 // 4 薪资
  }

  if (lastData.value.checkStatus == 2 || lastData.value.checkStatus == 13) {
    params.recordId = lastData.value.examineRecordId
  }

  this.initWkFlowData(
    {
      params,
      fieldForm: lastData
    },
    (res) => {
      const resData = res.resData
      this.examineData = resData.examineId ? resData : null
    }
  )
}

/** 搜索按钮操作 */
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'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } 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 formRef = ref()
const handleExport = () => {
  formRef.value.open(fieldList.value, list.value)
}
/** 导出按钮操作 */
// const handleExport = async () => {
//   try {
//     // 导出的二次确认
//     await message.exportConfirm()
//
//     // 发起导出（前端实现）
//     exportLoading.value = true
//
//     // 获取当前日期作为文件名的一部分
//     const now = new Date()
//     const year = now.getFullYear()
//     const month = String(now.getMonth() + 1).padStart(2, '0')
//     const day = String(now.getDate()).padStart(2, '0')
//     const fileName = `${year}${month}${day}_薪资表.csv`
//
//     // 处理导出数据
//     const exportData = list.value.map((row) => {
//       const exportRow = {}
//       fieldList.value.forEach((field) => {
//         const value = fieldFormatter(row, { property: field.field })
//         exportRow[field.name] = value
//       })
//       return exportRow
//     })
//
//     // 调用前端导出函数
//     exportToCSV(exportData, fileName)
//
//     message.success('导出成功')
//   } catch (error) {
//     message.error('导出失败')
//     console.error('导出失败:', error)
//   } finally {
//     exportLoading.value = false
//   }
// }

// 前端导出CSV函数
const exportToCSV = (data, fileName) => {
  // 获取表头（所有字段的name）
  const headers = fieldList.value.map((field) => field.name)

  // 创建CSV内容
  let csvContent = ''

  // 添加表头行，需要用BOM头解决Excel打开时的中文乱码问题
  csvContent += '\uFEFF' + headers.map((h) => escapeCSVField(h)).join(',') + '\n'

  // 添加数据行
  data.forEach((row) => {
    const rowData = headers.map((header) => {
      // 找到对应的字段值
      const value = row[header] || ''
      return escapeCSVField(String(value))
    })
    csvContent += rowData.join(',') + '\n'
  })

  // 创建Blob对象，使用text/csv格式
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })

  // 创建下载链接并触发下载
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(link.href)
}

// 处理CSV字段的转义，确保包含逗号、引号或换行符的内容能被正确解析
const escapeCSVField = (field) => {
  if (field.includes(',') || field.includes('"') || field.includes('\n')) {
    // 如果字段包含逗号、引号或换行符，需要用双引号包围，并将内部的双引号转义为两个双引号
    return '"' + field.replace(/"/g, '""') + '"'
  }
  return field
}
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open(route.query.srecordId, route.query.companyId)
}

const hsTaximportFormRef = ref()
const taxHandleImport = () => {
  hsTaximportFormRef.value.open(route.query.srecordId, route.query.companyId)
}

// 打开员工详情抽屉
const openEmployeeDrawer = (row) => {
  selectedEmployee.value = row
  selectedEmployeeSalaryItems.value = otherTablesWithValues(row)
  companySalaryItems.value = companyOtherTablesWithValues(row)
  drawerVisible.value = true
}
/** 初始化 **/
onMounted(() => {
  getTableHeader()
  getList()
})
</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>
