<template>
  <div>
    <CommonPage
      :operationBtnList="operationBtnList"
      :visibleDefaultButtons="visibleDefaultButtons"
      :showSearchForm="true"
      :show-pagination="true"
      :total="pageTotal"
      :current-page="currentPage"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <!-- 搜索区域 -->
      <template #searchForm>
        <SearchForm ref="searchFormRef" :config="searchConfig" />
      </template>

      <!-- 列表区域 -->
      <template #table>
        <!-- 制作薪资单管理列表 -->
        <el-table
          :data="tableData"
          height="400"
          border
          highlight-current-row
          style="width: 100%"
          v-loading="loading"
          ref="tableRef"
          row-key="salaryBizId"
          :reserve-selection="true"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" :reserve-selection="true" />
          <el-table-column
            v-for="(column, index) in workSalaryTableColumns"
            :key="index"
            :fixed="column.fixed"
            :prop="column.prop"
            :label="column.label"
            :width="column.width"
            :sortable="column.sortable"
            :formatter="column.formatter"
          />
          <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="{ row }">
              <el-popover placement="right" :width="200" trigger="click">
                <template #reference>
                  <el-icon>
                    <MoreFilled />
                  </el-icon>
                </template>
                <el-menu @select="handleSelect($event, row)" popper-class="custom-menu">
                  <el-menu-item
                    :index="item.value"
                    v-for="item in getOperateItems(row)"
                    :key="item.value"
                    >{{ item.label }}</el-menu-item
                  >
                </el-menu>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </CommonPage>
    <!-- 新增，修改，查看薪资单 -->
    <CommonDialog
      :dialogTitle="commonDialogTit"
      dialogWidth="80%"
      :openDialog="detailDialogVisible"
      :showAction="commonDialogType == 'view' ? false : true"
      :showClose="true"
      @close="detailDialogVisible = false"
      @confirm="handleConfirmSingleSalary"
    >
      <SearchForm
        ref="singleSalaryFormRef"
        :config="personSaleryFormConfig"
        v-model="personSaleryFormModel"
        @selectChange="handleFormSelectChange"
        @inputChange="handleFormInputChange"
      />
      <div class="statistics-container" v-if="personSaleryFormModel.apiSalaryRemittanceFzDTO">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
            <el-statistic
              :value="personSaleryFormModel.apiSalaryRemittanceFzDTO.totalAmount"
              :formatter="value => formatCurrency(value)"
            >
              <template #title>
                <div style="display: inline-flex; align-items: center">折合港币合计</div>
              </template>
            </el-statistic>
          </el-col>
        </el-row>
      </div>
      <div>
        <editTable
          ref="bankTableRef"
          :showAdd="commonDialogType == 'view' ? false : true"
          :showOperation="commonDialogType == 'view' ? false : true"
          addBtnTxt="添加打款账户"
          v-model:table-data="salaryRemittanceDTOList"
          :columns="bankTableColumns"
          row-id-key="signleId"
          @delete="handleBankDelete"
          @add="addSalaryRemittanceRecord"
          @selectChange="handleBankSelectChange"
          @cell-change="handleSingleSalaryCellChange"
        />
      </div>
    </CommonDialog>
    <!-- '批量制作薪资单 -->
    <CommonDialog
      dialogTitle="批量制作薪资单"
      dialogWidth="95%"
      :openDialog="multipAddSalaryDialog"
      @close="((multipAddSalaryDialog = false), resetAddReceivablesForm())"
      @confirm="handleConfirmAddSalary"
    >
      <editTable
        ref="editTableRef"
        addBtnTxt="添加薪资单"
        v-model:table-data="apiSalaryBatchAddDTOList"
        :columns="salaryTableColumns"
        row-id-key="multipleId"
        show-operation
        @delete="handleMultipDelete"
        @add="addSalaryRecord"
        @cell-change="handleSplitCellChange"
        @selectChange="handleSalarySelectChange"
      />
    </CommonDialog>
    <!-- 取消薪资单 -->
    <CommonDialog
      dialogTitle="取消薪资单"
      dialogWidth="80%"
      :openDialog="cancelDialogVisible"
      :showAction="true"
      :showClose="true"
      @close="cancelDialogVisible = false"
      @confirm="handleConfirmCancel"
    >
      <SearchForm ref="cancelFormRef" :config="cancelFormConfig" v-model="cancelFormModel" />
    </CommonDialog>
  </div>
</template>

<script setup name="WordReferenceSalary">
import CommonPage from '@/components/commonPage'
import CommonDialog from '@/components/commonDialog'
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { MoreFilled } from '@element-plus/icons-vue'
import { exportReceivedFortune } from '@/api/financial/commission'
import {
  getSalaryList,
  batchAddSalary,
  calculatePaidAmount,
  getExchangeRate,
  grossAmountApi,
  updateSalaryDetail,
  calculateTotalAmountApi,
  editSingleSalaryApi,
  addSingleSalaryApi,
  cancelSalaryApi,
  delSalaryApi,
  submitCheckApi
} from '@/api/salary'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import { loadDicts, getDictLabel } from '@/utils/useDict'
import { safeDownload } from '@/utils/safeDownload'
import { formatCurrency } from '@/utils/number'
import editTable from '@/components/Table/editTable.vue'
// 添加表格引用
const tableRef = ref()
// 存储所有选中的行数据（用于跨页保持选择）
const allSelectedRows = ref(new Map())
const selectedRows = ref([])
const multipAddSalaryDialog = ref(false)
const addRecordRef = ref(null)
const apiSalaryBatchAddDTOList = ref([{}]) //批量新增薪资单
const salaryRemittanceDTOList = ref([{}]) //银行数据
const editTableRef = ref(null)
const bankTableRef = ref(null)
const singleSalaryFormRef = ref(null)
const personSaleryFormModel = ref({ apiSalaryRemittanceFzDTO: {} })
const commonDialogTit = ref('')
const commonDialogType = ref('')
const cancelDialogVisible = ref(false)
const cancelFormRef = ref(null)
const cancelFormModel = ref({})

// 批量薪资单表格配置
const salaryTableColumns = ref([
  {
    prop: 'brokerBizId',
    label: '姓名',
    editType: 'select',
    api: '/csf/api/salary/broker/list', // 接口地址 这个是get请求，目前表格是post请求，所以需要在完善一下表格的请求方式以及请求参数
    method: 'get', // ← 指定请求方式为 GET
    valueKey: 'brokerBizId', // 选项 value 字段名
    labelKey: 'broker', // 选项 label 字段名
    preload: true, // 初始化时自动加载
    width: 150,
    requestParams: { name: '' }, // 固定参数
    // 远程搜索配置
    filterable: true,
    keywordField: 'name',
    onChangeExtraFields: {
      brokerName: 'broker', // 将选项原始对象的 broker 字段赋值给行数据的 brokerName
      monthList: 'monthList', // 存储月份列表，供月份列使用
      splitRatio: 'internalNumber' // 新增：将原始数据的 internalNumber 赋给 splitRatio
    }
    // debounceWait: 300
  },
  {
    editType: 'select',
    prop: 'month',
    label: '薪资月份',
    // options: [],//根据选择得转介人数据动态获取
    // placeholder: monthList.value.length > 0 ? '请选择月份' : '请先选择转介人',
    width: 150,
    // 动态选项，依赖行数据中的 monthList
    options: row => {
      const list = row.monthList || []
      return list.map(m => ({ value: m, label: m })) // 格式：{ value, label }
    }
    // rules: [{ required: true, message: '必填项', trigger: 'blur' }]
  },

  {
    prop: 'splitRatio',
    label: '内部编号',
    editType: 'input',
    // required: true,
    placeholder: '请输入内部编号',
    width: 150,
    disabled: true
  },

  {
    editType: 'input',
    prop: 'grossAmount',
    label: '应发金额',
    inputType: 'decimalNumber',
    // required: true,
    width: 150
  },
  {
    prop: 'mpfAmount',
    label: 'MPF事项',
    editType: 'input',
    // required: true,
    placeholder: '请输入MPF事项',
    width: 150
  },
  {
    editType: 'input',
    prop: 'otherAmount',
    label: '其他调整总金额',
    inputType: 'decimalNumber',
    // required: true,
    width: 150
  },
  {
    prop: 'otherRemark',
    label: '备注',
    editType: 'input',
    // required: true,
    placeholder: '请输入备注',
    width: 150
  },
  {
    editType: 'input',
    prop: 'paidAmount',
    label: '实发金额',
    inputType: 'decimalNumber',
    // required: true,
    width: 150
  },
  {
    prop: 'bank1',
    label: '收款银行1',
    editType: 'select',
    api: '/base/api/bank/page', // 接口地址
    valueKey: 'bankBizId', // 选项 value 字段名
    labelKey: 'bankName', // 选项 label 字段名
    preload: true, // 初始化时自动加载
    width: 150,
    requestParams: { pageNo: 1, pageSize: 20 }, // 固定参数
    // 远程搜索配置
    filterable: true,
    keywordField: 'queryContent'
    // debounceWait: 300
  },
  {
    prop: 'accountEndNo1',
    label: '账户尾号1',
    editType: 'input',
    // required: true,
    placeholder: '请输入',
    width: 150
  },
  {
    editType: 'select',
    prop: 'currency1',
    label: '币种1',
    dictType: 'bx_currency_type',
    width: 150
    // rules: [{ required: true, message: '必填项', trigger: 'blur' }]
  },
  {
    editType: 'input',
    prop: 'amount1',
    label: '发放金额1',
    inputType: 'decimalNumber',
    // required: true,
    width: 150
  },
  {
    editType: 'input',
    prop: 'exchangeRate1',
    label: '汇率1',
    inputType: 'decimal',
    // required: true,
    width: 150
  },
  {
    prop: 'remark1',
    label: '备注1',
    editType: 'input',
    // required: true,
    placeholder: '请输入',
    width: 180
  },
  {
    prop: 'bank2',
    label: '收款银行2',
    editType: 'select',
    api: '/base/api/bank/page', // 接口地址
    valueKey: 'bankBizId', // 选项 value 字段名
    labelKey: 'bankName', // 选项 label 字段名
    preload: true, // 初始化时自动加载
    width: 150,
    requestParams: { pageNo: 1, pageSize: 20 }, // 固定参数
    // 远程搜索配置
    filterable: true,
    keywordField: 'queryContent'
    // debounceWait: 300
  },
  {
    prop: 'accountEndNo2',
    label: '账户尾号2',
    editType: 'input',
    // required: true,
    placeholder: '请输入',
    width: 150
  },
  {
    editType: 'select',
    prop: 'currency2',
    label: '币种2',
    width: 150,
    dictType: 'bx_currency_type'
    // rules: [{ required: true, message: '必填项', trigger: 'blur' }]
  },
  {
    editType: 'input',
    prop: 'amount2',
    label: '发放金额2',
    inputType: 'decimalNumber',
    // required: true,
    width: 150
  },
  {
    editType: 'input',
    prop: 'exchangeRate2',
    label: '汇率2',
    inputType: 'decimal',
    // required: true,
    width: 150
  },
  {
    prop: 'remark2',
    label: '备注2',
    editType: 'input',
    // required: true,
    placeholder: '请输入',
    width: 180
  }
])
//单个薪资单的表格配置
const bankTableColumns = ref([
  {
    prop: 'bank',
    label: '收款银行',
    editType: 'select',
    api: '/base/api/bank/page', // 接口地址
    valueKey: 'bankBizId', // 选项 value 字段名
    labelKey: 'bankName', // 选项 label 字段名
    preload: true, // 初始化时自动加载
    requestParams: { pageNo: 1, pageSize: 20 }, // 固定参数
    // 远程搜索配置
    filterable: true,
    keywordField: 'queryContent'
    // debounceWait: 300
  },
  {
    prop: 'accountEndNo',
    label: '账户尾号',
    editType: 'input',
    // required: true,
    placeholder: '请输入',
    width: 150
  },
  {
    editType: 'select',
    prop: 'currency',
    label: '币种',
    dictType: 'bx_currency_type',
    width: 150
    // rules: [{ required: true, message: '必填项', trigger: 'blur' }]
  },
  {
    editType: 'input',
    prop: 'amount',
    label: '发放金额',
    inputType: 'decimalNumber',
    // required: true,
    width: 150
  },
  {
    editType: 'input',
    prop: 'exchangeRate',
    label: '汇率',
    inputType: 'decimal',
    // required: true,
    width: 150
  },
  {
    prop: 'remark',
    label: '备注',
    editType: 'input',
    // required: true,
    placeholder: '请输入',
    width: 180
  }
])
//单个薪资单的表单配置
const personSaleryFormConfig = ref([
  {
    prop: 'brokerBizId',
    label: '姓名',
    type: 'select',
    api: '/csf/api/salary/broker/list', // 接口地址 这个是get请求，目前表格是post请求，所以需要在完善一下表格的请求方式以及请求参数
    method: 'get', // ← 指定请求方式为 GET
    valueKey: 'brokerBizId', // 选项 value 字段名
    labelKey: 'broker', // 选项 label 字段名
    preload: true, // 初始化时自动加载
    requestParams: { name: '' }, // 固定参数
    // 远程搜索配置
    filterable: true,
    keywordField: 'name',
    onChangeExtraFields: {
      brokerName: 'broker', // 将选项原始对象的 broker 字段赋值给行数据的 brokerName
      monthList: 'monthList', // 存储月份列表，供月份列使用
      splitRatio: 'internalNumber' // 新增：将原始数据的 internalNumber 赋给 splitRatio
    },
    rules: [{ required: true, message: '姓名必填', trigger: 'blur' }]
    // debounceWait: 300
  },
  {
    type: 'select',
    prop: 'month',
    label: '薪资月份',
    // 动态选项，依赖行数据中的 monthList
    options: row => {
      const list = row.monthList || []
      return list.map(m => ({ value: m, label: m })) // 格式：{ value, label }
    },
    rules: [{ required: true, message: '薪资月份必填', trigger: 'blur' }]
  },

  {
    prop: 'splitRatio',
    label: '内部编号',
    type: 'input',
    // required: true,
    placeholder: '请输入内部编号',
    customDisable: true,
    disabled: true
  },

  {
    type: 'input',
    prop: 'grossAmount',
    label: '应发金额',
    inputType: 'decimalNumber'
    // required: true,
  },
  {
    prop: 'mpfAmount',
    label: 'MPF事项',
    type: 'input',
    // required: true,
    placeholder: '请输入MPF事项'
  },
  {
    type: 'input',
    prop: 'otherAmount',
    label: '其他调整总金额',
    inputType: 'decimalNumber'
    // required: true,
  },
  {
    prop: 'otherRemark',
    label: '其他调整备注',
    type: 'input',
    // required: true,
    placeholder: '请输入'
  },
  {
    prop: 'remark',
    label: '备注',
    type: 'input',
    // required: true,
    placeholder: '请输入备注'
  },
  {
    type: 'input',
    prop: 'paidAmount',
    label: '实发金额',
    inputType: 'decimalNumber'
    // required: true,
  }
])
//单个薪资单的表单配置
const cancelFormConfig = ref([
  {
    prop: 'cancelRemark',
    label: '备注',
    type: 'input',
    // required: true,
    placeholder: '请输入备注',
    span: 12
  }
])
// 提交核对
const handleSubmitCheck = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要核对的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确认完成 ${selectedRows.value.length} 条记录的核对操作吗？`,
      '提示',
      { type: 'warning' }
    )
    console.log(selectedRows.value)
    const arr = selectedRows.value.map(item => item.salaryBizId).join(',')

    // 调用出账API
    await submitCheckApi({ salaryBizId: arr })
    clearAllSelection()
    const params = searchFormRef.value.getFormData()
    loadTableData(params)
    ElMessage.success('核对操作成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('核对操作失败')
    }
  }
}
//==============表格复选框开始===========
// 选择行变化
const handleSelectionChange = selection => {
  selectedRows.value = selection
  // 更新全局选中状态
  updateAllSelectedRows()
}
// 更新全局选中状态
const updateAllSelectedRows = () => {
  // 更新当前页的选中状态
  tableData.value.forEach(row => {
    const isSelected = selectedRows.value.some(
      selectedRow => selectedRow.salaryBizId === row.salaryBizId
    )

    if (isSelected) {
      allSelectedRows.value.set(row.salaryBizId, row)
    } else {
      allSelectedRows.value.delete(row.salaryBizId)
    }
  })
}
// 设置当前页的选中状态
const setCurrentPageSelection = () => {
  if (!tableRef.value) return

  // 清除当前页的选择
  // tableRef.value.clearSelection()

  // 设置当前页应该选中的行
  tableData.value.forEach(row => {
    console.log('====================================')
    console.log('(allSelectedRows.value', allSelectedRows.value)
    console.log('====================================')
    if (allSelectedRows.value.has(row.salaryBizId)) {
      tableRef.value.toggleRowSelection(row, true)
    }
  })
}
// 清空所有选择
const clearAllSelection = () => {
  allSelectedRows.value.clear()
  selectedRows.value = []
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
}
//==============表格复选框结束===========
const addSalaryRecord = () => {
  apiSalaryBatchAddDTOList.value.push({
    multipleId: Date.now() + Math.random() // 或使用 uuid
  })
}
const addSalaryRemittanceRecord = () => {
  salaryRemittanceDTOList.value.push({
    signleId: Date.now() + Math.random() // 或使用 uuid
  })
}
const handleSalarySelectChange = async ({ prop, value, col, rowIndex, options }) => {
  const currentRow = apiSalaryBatchAddDTOList.value[rowIndex]
  if (!currentRow) return
  let needUpdate = false
  const updatedRow = { ...currentRow }

  //计算应发金额
  if (prop === 'month' || prop === 'brokerBizId') {
    if (currentRow.brokerBizId && currentRow.month) {
      try {
        let params = {
          brokerBizId: currentRow.brokerBizId,
          month: currentRow.month
        }
        const res = await grossAmountApi(params)
        updatedRow.grossAmount = res.data
        updatedRow.mpfAmount = 0
        updatedRow.otherAmount = 0
        updatedRow.paidAmount = res.data

        needUpdate = true
      } catch (error) {
        console.log('应发金额计算失败', error)
        ElMessage.error('应发金额计算失败')
      }
    }
  }
  if (prop === 'currency1' || prop === 'currency2') {
    if (value) {
      try {
        let params = {
          fromCurrency: value,
          toCurrency: 'HKD'
        }
        const res = await getExchangeRate(params)
        if (prop === 'currency1') {
          updatedRow.exchangeRate1 = res.data
        } else if (prop === 'currency2') {
          updatedRow.exchangeRate2 = res.data
        }
        needUpdate = true
      } catch (error) {
        console.log('汇率计算失败', error)
        ElMessage.error('汇率计算失败')
      }
    }
  }
  if (needUpdate) {
    // 更新表格数据（整体替换，触发视图更新）
    const newData = [...apiSalaryBatchAddDTOList.value]
    newData[rowIndex] = updatedRow
    apiSalaryBatchAddDTOList.value = newData
  }
}
const handleSplitCellChange = async ({ row, col, newValue, oldValue, rowIndex, prop }) => {
  console.log('单元格改变', row, col, newValue, oldValue, rowIndex, prop)

  const currentRow = apiSalaryBatchAddDTOList.value[rowIndex]
  if (!currentRow) return
  let needUpdate = false
  const updatedRow = { ...currentRow }
  //计算实发金额
  if (prop === 'grossAmount' || prop === 'mpfAmount' || prop === 'otherAmount') {
    if (currentRow.grossAmount && currentRow.mpfAmount && currentRow.otherAmount) {
      try {
        let params = {
          grossAmount: currentRow.grossAmount,
          mpfAmount: currentRow.mpfAmount,
          otherAmount: currentRow.otherAmount
        }
        const res = await calculatePaidAmount(params)
        updatedRow.paidAmount = res.data
        needUpdate = true
      } catch (error) {
        console.log('实发金额计算失败', error)
        ElMessage.error('实发金额计算失败')
      }
    }
  }
  // 如果用户手动修改了 hkdAmount，不做反向联动（符合需求）
  if (needUpdate) {
    // 更新表格数据（整体替换，触发视图更新）
    const newData = [...apiSalaryBatchAddDTOList.value]
    newData[rowIndex] = updatedRow
    apiSalaryBatchAddDTOList.value = newData
  }
}

// 弹窗表单重置
const resetAddReceivablesForm = () => {
  // addRecordRef.value.resetForm()
}

const handleConfirmAddSalary = async () => {
  // 调用组件的校验方法
  const isValid = await editTableRef.value.validateAndShow()
  if (isValid) {
    try {
      let params = {
        apiSalaryBatchAddDTOList: apiSalaryBatchAddDTOList.value
      }
      const res = await batchAddSalary(params)
      multipAddSalaryDialog.value = false
      ElMessage.success('批量添加薪资单成功')
      const searchParams = searchFormRef.value.getFormData()
      loadTableData(searchParams)
    } catch (error) {
      multipAddSalaryDialog.value = true
      console.log('批量添加薪资单错误', error)
      ElMessage.error('批量添加薪资单失败')
    }
  }
}
// 单个薪资单下拉框改变
const handleBankSelectChange = async ({ prop, value, col, rowIndex }) => {
  const currentRow = salaryRemittanceDTOList.value[rowIndex]
  if (!currentRow) return
  let needUpdate = false
  const updatedRow = { ...currentRow }

  if (prop === 'currency') {
    if (value) {
      try {
        let params = {
          fromCurrency: value,
          toCurrency: 'HKD'
        }
        const res = await getExchangeRate(params)
        updatedRow.exchangeRate = res.data
        needUpdate = true
      } catch (error) {
        console.log('汇率计算失败', error)
        ElMessage.error('汇率计算失败')
      }
    }
  }
  if (needUpdate) {
    // 更新表格数据（整体替换，触发视图更新）
    const newData = [...salaryRemittanceDTOList.value]
    newData[rowIndex] = updatedRow
    salaryRemittanceDTOList.value = newData
  }
  //计算折合港币总金额，改变币种汇率也会改变，所以等表格更新完在更新折合港币总金额
  if (prop === 'currency') {
    if (value) {
      if (currentRow.amount && currentRow.exchangeRate && currentRow.currency) {
        try {
          let calculateTotalAmountDTOList = JSON.parse(
            JSON.stringify(salaryRemittanceDTOList.value)
          )
          let params = calculateTotalAmountDTOList.reduce((acc, item) => {
            if (item.amount && item.exchangeRate && item.currency) {
              acc.push({ ...item })
            }
            return acc
          }, [])
          const res = await calculateTotalAmountApi({ calculateTotalAmountDTOList: params })
          personSaleryFormModel.value.apiSalaryRemittanceFzDTO.totalAmount = res.data
        } catch (error) {
          console.log('折合港币总金额计算失败', error)
          ElMessage.error('折合港币总金额计算失败')
        }
      }
    }
  }
}
// 单个薪资单输入框改变
const handleSingleSalaryCellChange = async ({ row, col, newValue, oldValue, rowIndex, prop }) => {
  // console.log('单元格改变', row, col, newValue, oldValue, rowIndex, prop)

  const currentRow = salaryRemittanceDTOList.value[rowIndex]
  if (!currentRow) return
  let needUpdate = false
  const updatedRow = { ...currentRow }

  // 如果用户手动修改了 hkdAmount，不做反向联动（符合需求）
  if (needUpdate) {
    // 更新表格数据（整体替换，触发视图更新）
    const newData = [...salaryRemittanceDTOList.value]
    newData[rowIndex] = updatedRow
    salaryRemittanceDTOList.value = newData
  }
  //计算折合港币总金额，改变币种汇率也会改变，所以等表格更新完在更新折合港币总金额
  if (prop === 'amount' || prop === 'exchangeRate') {
    if (currentRow.amount && currentRow.exchangeRate && currentRow.currency) {
      try {
        let calculateTotalAmountDTOList = JSON.parse(JSON.stringify(salaryRemittanceDTOList.value))
        let params = calculateTotalAmountDTOList.reduce((acc, item) => {
          if (item.amount && item.exchangeRate && item.currency) {
            acc.push({ ...item })
          }
          return acc
        }, [])
        const res = await calculateTotalAmountApi({ calculateTotalAmountDTOList: params })
        personSaleryFormModel.value.apiSalaryRemittanceFzDTO.totalAmount = res.data
      } catch (error) {
        console.log('折合港币总金额计算失败', error)
        ElMessage.error('折合港币总金额计算失败')
      }
    }
  }
}
// 单个薪资单的新增，修改
const handleConfirmSingleSalary = async () => {
  let formData = await singleSalaryFormRef.value.validate()
  try {
    if (formData.apiSalaryRemittanceFzDTO) {
      formData.apiSalaryRemittanceFzDTO.salaryRemittanceDTOList = JSON.parse(
        JSON.stringify(salaryRemittanceDTOList.value)
      )
    }
    if (commonDialogType.value == 'edit') {
      const res = await editSingleSalaryApi(formData)
      ElMessage.success('薪资单修改成功')
      detailDialogVisible.value = false
    } else if (commonDialogType.value == 'add') {
      const res = await addSingleSalaryApi(formData)
      ElMessage.success('薪资单新增成功')
    }
    detailDialogVisible.value = false
    const searchParams = searchFormRef.value.getFormData()
    loadTableData(searchParams)
  } catch (error) {
    if (commonDialogType.value == 'edit') {
      ElMessage.error('薪资单修改失败')
    } else if (commonDialogType.value == 'add') {
      ElMessage.error('薪资单新增失败')
    }
    detailDialogVisible.value = true
    if (error.message && error.message.includes('Validation')) {
      ElMessage.error('必填项不能为空')
    }
  }
}

const searchFormRef = ref(null)
const searchParams = ref({})
const searchConfig = ref([
  {
    type: 'input',
    prop: 'brokerName',
    label: '转介人'
  },
  {
    type: 'month',
    prop: 'month',
    label: '薪资年月',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间'
  },
  {
    type: 'select',
    prop: 'status',
    label: '薪资单状态',
    // multiple: true,
    dictType: 'salary_status'
  }
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const loading = ref(false)

// 动态生成操作菜单项（根据行数据）
const getOperateItems = row => {
  const items = []

  // 条件：isPart == 1 时不显示分期出账（使用宽松相等，兼容字符串 '1'）
  // if (row.type == 1) {
  //   items.push({ label: '设置状态', value: 'setStatus' })
  //   items.push({ label: '更新数据', value: 'updateData' })
  // }

  // 始终显示的菜单项（保持原始顺序）
  items.push({ label: '修改薪资单', value: 'salaryEdit' })
  items.push({ label: '查看薪资单', value: 'salaryView' })
  items.push({ label: '取消薪资单', value: 'salaryCancel' })

  return items
}
const handleFormInputChange = async (prop, value, item) => {
  console.log('表单输入框改变', prop, value, item)
  await nextTick()
  //计算实发金额
  if (prop === 'grossAmount' || prop === 'mpfAmount' || prop === 'otherAmount') {
    if (
      personSaleryFormModel.value.grossAmount &&
      personSaleryFormModel.value.mpfAmount &&
      personSaleryFormModel.value.otherAmount
    ) {
      try {
        let params = {
          grossAmount: personSaleryFormModel.value.grossAmount,
          mpfAmount: personSaleryFormModel.value.mpfAmount,
          otherAmount: personSaleryFormModel.value.otherAmount
        }
        const res = await calculatePaidAmount(params)
        personSaleryFormModel.value.paidAmount = res.data
      } catch (error) {
        console.log('实发金额计算失败', error)
        ElMessage.error('实发金额计算失败')
      }
    }
  }
}
const handleFormSelectChange = async (prop, value, item) => {
  console.log('表单选中项改变', prop, value, item)
  await nextTick()
  //计算应发金额
  if (prop === 'month' || prop === 'brokerBizId') {
    if (personSaleryFormModel.value.brokerBizId && personSaleryFormModel.value.month) {
      try {
        let params = {
          brokerBizId: personSaleryFormModel.value.brokerBizId,
          month: personSaleryFormModel.value.month
        }
        const res = await grossAmountApi(params)
        personSaleryFormModel.value.grossAmount = res.data
        personSaleryFormModel.value.mpfAmount = 0
        personSaleryFormModel.value.otherAmount = 0
        personSaleryFormModel.value.paidAmount = res.data
      } catch (error) {
        console.log('应发金额计算失败', error)
        ElMessage.error('应发金额计算失败')
      }
    }
  }
}
//设置单个薪资单的表单编辑状态
const setSignleSalaryFormStatus = () => {
  personSaleryFormConfig.value = personSaleryFormConfig.value.map(item => {
    if (
      (commonDialogType.value == 'add' || commonDialogType.value == 'edit') &&
      !item.customDisable
    ) {
      item.disabled = false
    } else {
      item.disabled = true
    }
    return item
  })
  bankTableColumns.value = bankTableColumns.value.map(item => {
    if (commonDialogType.value == 'add' || commonDialogType.value == 'edit') {
      item.disabled = false
    } else {
      item.disabled = true
    }
    return item
  })
}
const handleSingleAdd = () => {
  commonDialogTit.value = '增加薪资单'
  commonDialogType.value = 'add'
  personSaleryFormModel.value = { apiSalaryRemittanceFzDTO: {} }
  salaryRemittanceDTOList.value = []
  setSignleSalaryFormStatus()
  detailDialogVisible.value = true
}
const handleSelect = (e, row) => {
  console.log('选中行:', e, row)
  selectedRow.value = row
  if (e === 'salaryEdit') {
    commonDialogTit.value = '修改薪资单'
    commonDialogType.value = 'edit'
    setSignleSalaryFormStatus()
    updateSalary(row)
  } else if (e === 'salaryView') {
    commonDialogTit.value = '查看薪资单'
    commonDialogType.value = 'view'
    setSignleSalaryFormStatus()
    updateSalary(row)
  } else if (e === 'salaryCancel') {
    cancelDialogVisible.value = true
    cancelFormModel.value = JSON.parse(JSON.stringify(row))
  }
}
const handleConfirmCancel = async () => {
  let formData = await cancelFormRef.value.validate()
  try {
    await cancelSalaryApi(formData)
    ElMessage.success('薪资单取消成功')
    cancelDialogVisible.value = false
    const searchParams = searchFormRef.value.getFormData()
    loadTableData(searchParams)
  } catch (error) {
    ElMessage.error('取消薪资单失败')
    cancelDialogVisible.value = true
    if (error.message && error.message.includes('Validation')) {
      ElMessage.error('必填项不能为空')
    }
  }
}

const handleMultipDelete = async row => {
  try {
    // 弹出确认框
    await ElMessageBox.confirm('确定要删除该记录吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 用户点击确定 → 执行删除逻辑
    const index = apiSalaryBatchAddDTOList.value.findIndex(
      item => item.multipleId == row.multipleId
    )
    if (index !== -1) {
      apiSalaryBatchAddDTOList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    // 用户取消或关闭弹窗，不做任何操作
    console.log('取消删除')
  }
}
const handleBankDelete = async row => {
  try {
    // 弹出确认框
    await ElMessageBox.confirm('确定要删除该记录吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    if (row.salaryRemittanceBizId) {
      await delSalaryApi(row.salaryRemittanceBizId)
    }

    // 用户点击确定 → 执行删除逻辑
    const index = salaryRemittanceDTOList.value.findIndex(item => item.signleId == row.signleId)
    if (index !== -1) {
      salaryRemittanceDTOList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    // 用户取消或关闭弹窗，不做任何操作
    console.log('取消删除')
  }
}
const selectedRow = ref(null)

// 表格数据
const tableData = ref([])

// 按钮事件处理
const handleAdd = () => {
  multipAddSalaryDialog.value = true
  if (addRecordRef.value) {
    addRecordRef.value.resetForm()
  }
  apiSalaryBatchAddDTOList.value = [{}]
}

const handleExport = async () => {
  ElMessage.info('导出待开发')
  return
  // 获取搜索参数
  const params = searchFormRef.value?.getFormData() || {}
  const response = await exportReceivedFortune(params)
  // 文件名设置为应收款导出_yyyy-MM-dd hh:mm:ss.xlsx,不需要-，用字符串
  const fileName = `应收款导出_${new Date().toLocaleString().replace(/\//g, '').replace(/:/g, '').replace(/\s/g, '')}.xlsx`
  await safeDownload(response, fileName, 'application/vnd.ms-excel;charset=utf-8')
}

const handleReset = () => {
  // 重置搜索表单
  searchFormRef.value.resetForm()
  searchParams.value = {}
  clearAllSelection()
  console.log('表单已重置')
  loadTableData()
}

const handleQuery = () => {
  currentPage.value = 1
  clearAllSelection()
  const params = searchFormRef.value.getFormData()
  loadTableData(params)
}

const visibleDefaultButtons = ref(['add', 'reset', 'query'])
// 按钮配置
const operationBtnList = ref([
  { key: 'add', direction: 'left', label: '批量制作薪资单', click: handleAdd },
  { key: 'singleAdd', direction: 'left', label: '制作薪资单', click: handleSingleAdd },
  { key: 'check', direction: 'left', label: '提交核对', type: 'warning', click: handleSubmitCheck },
  // { key: 'import', direction: 'left', click: handleImport },
  // { key: 'export', direction: 'right', click: handleExport },
  { key: 'reset', direction: 'right', click: handleReset },
  { key: 'query', direction: 'right', click: handleQuery }
])

// 分页事件
const handleSizeChange = val => {
  pageSize.value = val
  const params = searchFormRef.value.getFormData()
  loadTableData(params)
}

const handleCurrentChange = val => {
  currentPage.value = val
  const params = searchFormRef.value.getFormData()
  loadTableData(params)
}

// 加载表格数据
const loadTableData = async searchParams => {
  loading.value = true
  try {
    const params = {
      ...searchParams,
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
    const response = await getSalaryList(params)
    tableData.value = response.data.records || []
    pageTotal.value = response.data.total || 0
    pageSize.value = response.data.size || 50
    // 数据加载完成后，设置当前页的选中状态
    nextTick(() => {
      setCurrentPageSelection()
    })
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}
// 获取入账状态,字典值转化方法
onMounted(async () => {
  try {
    await loadDicts(['salary_status'])

    loadTableData()
  } catch (error) {
    console.error('字典加载失败', error)
  } finally {
    loading.value = false
  }
})
// 格式化函数（每次渲染都会调用，所以能拿到最新字典）
const formatStatus = (row, column) => {
  return getDictLabel('salary_status', row.status) // 实时查缓存
}
const detailDialogVisible = ref(false)
const workSalaryTableColumns = ref([
  {
    prop: 'salaryNo',
    label: '发放编号',
    sortable: true,
    width: '150',
    fixed: 'left',
    formatter: row => row.salaryNo || '-'
  },
  {
    prop: 'salaryBizId',
    label: '业务编号',
    sortable: true,
    width: '220',
    formatter: row => row.salaryBizId || '-'
  },
  {
    prop: 'brokerName',
    label: '转介人',
    sortable: true,
    width: '100',
    formatter: row => row.brokerName || '-'
  },
  {
    prop: 'internalNumber',
    label: '内部编号',
    sortable: true,
    width: '150',
    formatter: row => row.internalNumber || '-'
  },
  {
    prop: 'teamName',
    label: '所属团队',
    sortable: true,
    width: '130',
    formatter: row => row.teamName || '-'
  },
  {
    prop: 'paidAmount',
    label: '发放金额',
    sortable: true,
    width: '150',
    formatter: row => formatCurrency(row.paidAmount || 0)
  },
  {
    prop: 'currencyList',
    label: '发放币种',
    sortable: true,
    width: '150',
    formatter: row => row.currencyList || '-'
  },
  {
    prop: 'month',
    label: '出账月（实）',
    sortable: true,
    width: '120',
    formatter: row => row.month || '-'
  },
  {
    prop: 'status',
    label: '薪资单状态',
    sortable: true,
    width: '120',
    formatter: row => formatStatus(row) || '-'
  },
  {
    prop: 'creatorName',
    label: '制作人',
    sortable: true,
    width: '120',
    formatter: row => row.creatorName || '-'
  },
  {
    prop: 'createTime',
    label: '制作时间',
    sortable: true,
    width: '180',
    formatter: row => row.createTime || '-'
  }
])
const updateSalary = async row => {
  try {
    const response = await updateSalaryDetail(row.salaryBizId)
    personSaleryFormModel.value = response.data
    if (personSaleryFormModel.value.apiSalaryRemittanceFzDTO) {
      salaryRemittanceDTOList.value =
        personSaleryFormModel.value.apiSalaryRemittanceFzDTO.salaryRemittanceDTOList.map(item => {
          return {
            ...item,
            signleId: Date.now() + Math.random()
          }
        })
    }
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取薪资单详情失败:', error)
    ElMessage.error('获取薪资单详情失败')
  }
}
</script>

<style scoped lang="scss">
/* 使用 :deep 穿透 scoped 样式，保证对 el-table__row 生效 */
:deep(.estimated-row) {
  background-color: #f0f9ff; /* 浅蓝色，可根据需要修改 */
}
</style>
