<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="日期" prop="salaryMonth">
        <el-date-picker
          v-model="queryParams.salaryMonth"
          type="month"
          value-format="YYYY-MM"
          placeholder="请选择日期"
          clearable
          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="openForm('create')"
          v-hasPermi="['erp:employee-salary:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:employee-salary:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap style="margin-top: 15px;">
    <!-- 增加空数据提示 -->
    <el-table 
      v-loading="loading" 
      :data="list" 
      :stripe="true" 
      :show-overflow-tooltip="true" 
      @row-click="handleRowClick"
      style="width: 100%;"
      empty-text="暂无符合条件的应付职工薪酬数据"
    >
      <el-table-column label="日期" align="center" prop="salaryMonth" width="120" />
      <el-table-column label="应付职工薪酬" align="right" prop="payableSalary" width="130">
        <template #default="scope">
          {{ formatMoney(scope.row.payableSalary) }}
        </template>
      </el-table-column>
      <el-table-column label="工资" align="right" prop="basicSalary" width="120">
        <template #default="scope">
          {{ formatMoney(scope.row.basicSalary) }}
        </template>
      </el-table-column>
      <el-table-column label="工资部门" align="left" prop="salaryDept" min-width="120">
        <template #default="scope">
          {{ scope.row.salaryDept || '-' }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="工资部门" align="right" prop="salaryDept" width="120">
        <template #default="scope">
          {{ formatMoney(scope.row.salaryDept) }}
        </template>
      </el-table-column> -->
      <el-table-column label="职工福利" align="right" prop="employeeWelfare" width="120">
        <template #default="scope">
          {{ formatMoney(scope.row.employeeWelfare) }}
        </template>
      </el-table-column>
      <el-table-column label="社保保险费" align="right" prop="socialInsurance" width="120">
        <template #default="scope">
          {{ formatMoney(scope.row.socialInsurance) }}
        </template>
      </el-table-column>
      <el-table-column label="奖金" align="right" prop="bonus" width="120">
        <template #default="scope">
          {{ formatMoney(scope.row.bonus) }}
        </template>
      </el-table-column>
      <el-table-column label="个人所得税" align="right" prop="personalIncomeTax" width="120">
        <template #default="scope">
          {{ formatMoney(scope.row.personalIncomeTax) }}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" prop="remark" min-width="120">
        <template #default="scope">
          {{ scope.row.remark || '-' }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
        sortable
      />
      <el-table-column label="操作" align="center" fixed="right" width="150">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:employee-salary:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:employee-salary:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页：优化v-model绑定，确保分页正常 -->
    <div style="margin-top: 15px; text-align: right;">
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="handlePagination"
        background
      />
    </div>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <EmployeeSalaryForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { EmployeeSalaryApi, EmployeeSalaryVO } from '@/api/erp/finance-alone/employeeSalary'
import EmployeeSalaryForm from './EmployeeSalaryForm.vue'
import { useMessage } from '@/hooks/web/useMessage'
import { useI18n } from '@/hooks/web/useI18n'

/** ERP 应付职工薪酬 列表 */
defineOptions({ name: 'ErpEmployeeSalary' })

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

const loading = ref(true) // 列表的加载中
const list = ref<EmployeeSalaryVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总条数（注意：是总条数不是总页数）
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  salaryMonth: undefined as string | undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const formRef = ref()

/** 格式化金额：修复类型兼容问题，支持字符串/数字类型 */
const formatMoney = (value: number | string | undefined | null) => {
  // 空值处理
  if (value === undefined || value === null || value === '') {
    return '0.00'
  }
  // 转换为数字后格式化
  const num = Number(value)
  return isNaN(num) ? '0.00' : num.toFixed(2)
}

/** 查询列表：增强调试和数据解析逻辑 */
const getList = async () => {
  loading.value = true
  try {
    console.log('查询参数：', JSON.parse(JSON.stringify(queryParams)))
    const response = await EmployeeSalaryApi.getEmployeeSalaryPage(queryParams)
    console.log('接口原始返回：', response)

    // 标准化数据解析：兼容不同的后端返回结构
    let resData = response
    if (response && response.code === 200 && response.data) {
      resData = response.data
    }

    // 赋值并打印，确认数据是否正确
    list.value = resData?.list ?? []
    total.value = resData?.total ?? resData?.totalCount ?? 0
    console.log('最终表格数据：', list.value)
    console.log('总条数：', total.value)

    // 空数据提示
    if (list.value.length === 0) {
      message.info('暂无符合条件的数据')
    }
  } catch (error) {
    console.error('获取列表失败：', error)
    message.error('获取应付职工薪酬列表失败，请重试')
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
  // 手动重置日期筛选条件
  queryParams.salaryMonth = undefined
  queryParams.pageNo = 1
  getList()
}

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

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await EmployeeSalaryApi.deleteEmployeeSalary(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('删除失败：', error)
    message.error('删除失败，请重试')
  }
}

/** 行点击操作 */
const handleRowClick = (row: EmployeeSalaryVO, column: any, event: MouseEvent) => {
  // 检查是否点击了按钮、链接或其他交互元素
  const target = event.target as HTMLElement
  if (
    target.tagName === 'BUTTON' ||
    target.tagName === 'A' ||
    target.tagName === 'I' ||
    target.tagName === 'svg' ||
    target.closest('button') ||
    target.closest('a') ||
    target.closest('.el-button') ||
    target.closest('.el-checkbox')
  ) {
    return
  }
  openForm('update', row.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await EmployeeSalaryApi.exportEmployeeSalary(queryParams)
    download.excel(data, '应付职工薪酬.xls')
    message.success('导出成功')
  } catch (error) {
    console.error('导出失败：', error)
    message.error('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

/** 分页回调：明确分页逻辑 */
const handlePagination = () => {
  getList()
}

/** 初始化 **/
onMounted(() => {
  console.log('页面初始化，开始获取列表数据')
  getList()
})
</script>

<style scoped>
/* 确保ContentWrap之间有间距，避免表格被遮挡 */
:deep(.el-table) {
  --el-table-header-text-color: #333;
  --el-table-row-hover-bg-color: #f5f7fa;
}
</style>