<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 label="所属公司" prop="companyId">
        <el-select
          v-model="queryParams.companyId"
          filterable
          placeholder="请选择所属公司"
          class="!w-240px"
        >
          <el-option
            v-for="company in companyOptions"
            :key="company.id"
            :label="company.name"
            :value="company.id"
          />
        </el-select>
      </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="openForm('create')"
          v-hasPermi="['hr:salary-month-record:create']"
        >
          <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"-->
        <!--          :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="150px" />
      <el-table-column prop="name" label="所属公司" width="150px">
        <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="num" />
      <el-table-column label="应发工资" align="center" prop="expectedPaySalary" />
      <el-table-column label="实发工资" align="center" prop="realPaySalary" />
      <el-table-column label="个人所得税" align="center" prop="personalTax" width="120px" />
      <el-table-column label="状态" align="center" prop="checkStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.HR_CHECK_STATUS" :value="scope.row.checkStatus" />
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="taskStatus" width="100" fixed="right">
        <template #default="scope">
          <!-- <span v-if="scope.row.taskStatus == 0">待审批</span> -->
          <el-tag type="primary" v-if="scope.row.taskStatus == 0">待审批</el-tag>
          <dict-tag
            v-else
            :type="DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS"
            :value="scope.row.taskStatus"
          />
        </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="250px" fixed="right">
        <template #default="scope">
          <!-- v-if="scope.row.taskStatus === 0" -->
          <el-button
            v-if="scope.row.taskStatus === 0"
            link
            type="primary"
            @click="handleSubmit(scope.row)"
          >
            提交审核
          </el-button>
          <!-- v-if="scope.row.processInstanceId" -->
          <el-button
            v-if="scope.row.processInstanceId"
            link
            type="primary"
            @click="handleProcessDetail(scope.row)"
          >
            查看审批
          </el-button>
          <template v-if="scope.row.checkStatus === 0 || scope.row.checkStatus === 4">
            <el-button
              link
              type="primary"
              @click="handleImport(scope.row)"
              v-hasPermi="['hr:salary-month-record:update']"
            >
              核算工资
            </el-button>
          </template>
          <template v-if="scope.row.checkStatus === 11">
            <el-button
              link
              type="primary"
              @click="handleImport(scope.row, 'view')"
              v-hasPermi="['hr:salary-month-record:update']"
            >
              查看
            </el-button>
          </template>
          <template v-if="scope.row.checkStatus !== 11 && scope.row.taskStatus == 2">
            <el-button
              link
              type="primary"
              @click="handleComplete(scope.row.id)"
              v-hasPermi="['hr:salary-month-record:update']"
            >
              完成
            </el-button>
          </template>
          <template v-if="scope.row.checkStatus === 0">
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['hr:salary-month-record:delete']"
            >
              删除
            </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>

  <!-- 表单弹窗：添加/修改 -->
  <SalaryMonthRecordForm ref="formRef" @success="getList" />
  <hsImportForm ref="importFormRef" @success="getList" />
</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 SalaryMonthRecordForm from './SalaryMonthRecordForm.vue'
import { InspectionTasksApi, InspectionTasksVO } from '@/api/device/inspectiontasks'
import hsImportForm from './hsImportForm.vue'
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 handleSubmit = async (row: InspectionTasksVO) => {
  await message.confirm(`您确定提交【${row.title}】审核吗？`)
  loading.value = true
  try {
    await InspectionTasksApi.salaryMonthRecordInspectionItemTasks({ id: row.id })
    message.success('提交审核成功！')
    await getList()
  } finally {
    loading.value = false
  }
}
/** 查看审批 */
const handleProcessDetail = (row: InspectionTasksVO) => {
  router.push({
    name: 'BpmProcessInstanceDetail',
    query: {
      id: row.processInstanceId,
      path: '/hr/salary/salary-month-record',
      srecordId: row.srecordId
    }
  })
}

// 获取参保人员选项
const getCompanyOptions = async () => {
  try {
    const deptData = await DeptApi.getCompanyList()
    companyOptions.value = deptData
  } catch (error) {
    console.error('获取人员列表失败', error)
  }
}
/** 查询列表 */
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 handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

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

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
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
  }
}
const importFormRef = ref()
const handleImport = (row, type) => {
  router.push({
    name: 'salarysubs',
    query: {
      srecordId: row.srecordId,
      companyId: row.companyId,
      pageType: type
    }
  })
  // importFormRef.value.open(row)
}
/** 初始化 **/
onMounted(async () => {
  await getList()
  await getCompanyOptions()
  // 加载部门树
  deptList.value = await DeptApi.getSimpleDeptCompanyList()
})
</script>
