<template>
  <div class="app-container">
    <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>
        <!-- 统计数据 -->
        <div class="statistics-container">
          <el-row :gutter="16">
            <el-col :xs="24" :sm="12" :md="6" class="text-center mb-4">
              <el-statistic
                title="总金额"
                :value="statisticInfo.totalAmount"
                :formatter="value => formatCurrency(value, '', 4)"
              />
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" class="text-center mb-4">
              <el-statistic title="总人数" :value="statisticInfo.brokerCount" />
            </el-col>
          </el-row>
        </div>
        <el-table
          :data="tableData"
          @selection-change="handleSelectionChange"
          v-loading="loading"
          ref="tableRef"
          row-key="fortuneAccountBizId"
          :reserve-selection="true"
          :border="true"
        >
          <el-table-column type="selection" width="55" :reserve-selection="true" />
          <el-table-column prop="broker" label="转介人" min-width="120" sortable />
          <el-table-column prop="team" label="所属团队" min-width="120" sortable />
          <el-table-column prop="hkdAmount" label="出账金额" width="120" sortable>
            <template #default="scope">
              {{ formatCurrency(scope.row.hkdAmount, '', 4) }}
            </template>
          </el-table-column>
          <el-table-column prop="currency" label="出账币种" width="120" sortable>
            <template #default="scope">
              <dict-tag :options="currencyTypeOptions" :value="scope.row.currency" />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="出账状态" width="150" sortable>
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ convertStatusToDict(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="fortuneAccountDate"
            label="出账日"
            min-width="150"
            show-overflow-tooltip
          />
          <!-- <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip /> -->
          <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 dropdownItems"
                    :key="item.value"
                    >{{ item.label }}</el-menu-item
                  >
                </el-menu>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </CommonPage>
    <!-- 拆分出账 -->
    <CommonDialog
      dialogTitle="拆分出账"
      dialogWidth="90%"
      confirmText="批量保存"
      :openDialog="showBillingFlag"
      :showAction="true"
      :showClose="true"
      @close="showBillingFlag = false"
      @confirm="handleBillConfirm"
    >
      <!-- 统计数据 -->
      <div class="statistics-container">
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="6" class="text-center mb-4">
            <el-statistic
              title="原币种总金额"
              :value="currentRow.hkdAmount"
              :formatter="value => formatCurrency(value, '', 4)"
            />
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" class="text-center mb-4">
            <el-statistic
              title="剩余原币种总金额"
              :value="billStatistic.beSplitAmount"
              :formatter="value => formatCurrency(value, '', 4)"
            />
          </el-col>
        </el-row>
      </div>
      <el-button
        style="margin: 10px 0"
        @click="handleAddBill"
        :loading="addBillLoading"
        type="primary"
        :icon="Plus"
        >新增拆分</el-button
      >
      <el-table
        v-loading="billLoading"
        :data="billTableList"
        border
        ref="billTableRef"
        height="450px"
      >
        <el-table-column
          label="序号 "
          width="55"
          align="center"
          type="index"
          fixed="left"
        ></el-table-column>
        <el-table-column label="发放编号" prop="salarySplitNo" width="150" fixed="left">
          <template #default="scope">
            <el-input
              v-model="scope.row.salarySplitNo"
              placeholder="请输入"
              clearable
              :disabled="true"
            />
          </template>
        </el-table-column>
        <el-table-column label="转介人" prop="brokerName" width="150">
          <template #default="scope">
            <el-input
              v-model="scope.row.brokerName"
              placeholder="请输入"
              clearable
              :disabled="true"
            />
          </template>
        </el-table-column>
        <el-table-column label="转介人内部编号" prop="internalNumber" width="150">
          <template #default="scope">
            <el-input
              v-model="scope.row.internalNumber"
              placeholder="请输入"
              clearable
              :disabled="true"
            />
          </template>
        </el-table-column>
        <el-table-column label="出账机构" prop="billOrg" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.billOrg" placeholder="请输入" clearable />
          </template>
        </el-table-column>
        <el-table-column label="原币种金额" prop="fromAmount" width="150">
          <template #default="scope">
            <!--等生产没问题再删除  @input="val => (scope.row.fromAmount = amountInput.filterInput(val, 4))"
              @blur="billInputBlur('fromAmount', scope.row)" -->
            <el-input
              v-model="scope.row.fromAmount"
              placeholder="请输入"
              clearable
              @clear="clearInput('fromAmount', scope.row)"
              @input="val => handleFromAmountInput(val, scope.row)"
              @blur="handleFromAmountBlur(scope.row)"
              :formatter="value => inputThousands(value)"
              :parser="value => value.replace(/\$\s?|(,*)/g, '')"
            />
          </template>
        </el-table-column>
        <el-table-column label="目标币种" prop="toCurrency" width="150">
          <template #default="scope">
            <el-select
              v-model="scope.row.toCurrency"
              style="width: 100%"
              placeholder="请选择"
              clearable
              @clear="clearInput('toCurrency', scope.row)"
              @change="changeToCurrency(scope.row)"
            >
              <el-option
                v-for="item in bx_currency_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <!--等生产没问题再删除 @blur="billInputBlur('exchangeRate', scope.row)"
              @input="val => (scope.row.exchangeRate = amountInput.filterInput(val, 4))" -->
        <el-table-column label="汇率" prop="exchangeRate" width="150">
          <template #default="scope">
            <el-input
              v-model="scope.row.exchangeRate"
              placeholder="请输入"
              clearable
              @clear="clearInput('exchangeRate', scope.row)"
              @input="val => handleExchangeRateInput(val, scope.row)"
              @blur="handleExchangeRateBlur(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="目标金额" prop="toAmount" width="150">
          <template #default="scope">
            <el-input
              v-model="scope.row.toAmount"
              placeholder="请输入"
              clearable
              :disabled="true"
              @input="val => (scope.row.toAmount = amountInput.filterInput(val, 4))"
              :formatter="value => inputThousands(value)"
              :parser="value => value.replace(/\$\s?|(,*)/g, '')"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.remark" type="textarea" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <div class="btnCon">
              <el-button
                size="small"
                type="danger"
                @click="handleDeleteBill(scope.row, scope.$index)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </CommonDialog>
    <!-- 弹窗-->
    <CommonDialog
      dialogTitle="出账完成"
      dialogWidth="80%"
      :openDialog="billingCompleteDialogVisible"
      :showAction="false"
      :showClose="true"
      @close="billingCompleteDialogVisible = false"
    >
      <div style="text-align: center">
        <el-icon size="48" color="#67C23A">
          <SuccessFilled />
        </el-icon>
        <p style="margin-top: 16px; font-size: 16px">出账操作已完成！</p>
      </div>
    </CommonDialog>
    <CommonDialog
      dialogTitle="修订记录"
      dialogWidth="80%"
      :openDialog="showReviseRecord"
      :showAction="false"
      :showClose="true"
      @close="showReviseRecord = false"
    >
      <el-table :data="reviseList" border>
        <el-table-column prop="createTime" label="修订时间" align="center" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="修订人" prop="userName" align="center" width="150">
        </el-table-column>

        <el-table-column label="修订内容" prop="editContent" align="center"></el-table-column>
      </el-table>
    </CommonDialog>
    <!-- 设置薪资日 -->
    <CommonDialog
      dialogTitle="设置薪资日"
      dialogWidth="80%"
      :openDialog="showSalarySetting"
      :showAction="true"
      :showClose="true"
      @close="showSalarySetting = false"
      @confirm = "salaryDataSetting"
    >
     <el-date-picker
        v-model="fortuneAccountDate"
        type="date"
        placeholder="选择薪资日"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      />
    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import CommonPage from '@/components/commonPage'
import CommonDialog from '@/components/commonDialog'
import { Plus } from '@element-plus/icons-vue'
import {
  getReferrerFortuneList,
  salaryStatistics,
  salarySplitList,
  billSplitRemaining,
  borkerDetail,
  billSplitRate,
  billBatchSave,
  billCalculateToAmount,
  updatePolicyFortuneAccount
} from '@/api/financial/commission'
import { formatCurrency, inputThousands } from '@/utils/number'
import { generateId } from '@/utils/common'
import { ElMessageBox, ElMessage } from 'element-plus'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import { usePositiveDecimal } from '@/utils/usePositiveDecimal'
import { debounce } from 'lodash-es'

const amountInput = usePositiveDecimal(4) // 默认2位小数
const { proxy } = getCurrentInstance()
const { bx_currency_type } = proxy.useDict('bx_currency_type')
const searchFormRef = ref(null)
const searchParams = ref({})
const searchConfig = ref([
  {
    type: 'select',
    prop: 'brokerBizIdList',
    label: '转介人',
    api: '/insurance/base/api/userSaleExpand/page',
    keywordField: 'realName',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入转介人名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'clientUserBizId',
    labelKey: 'realName',
    multiple: true,
    transform: res => {
      return res?.data.records || []
    }
  },
  {
    type: 'daterange',
    prop: 'payoutDate',
    label: '出账日（实）',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间'
  },
  {
    type: 'select',
    prop: 'statusList',
    label: '出账状态',
    dictType: 'csf_expected_fortune_status',
    multiple: true,
    defaultValue: ['6'] //默认查询待出账，已检核的数据
  }
])
// 添加表格引用
const tableRef = ref()
// 存储所有选中的行数据（用于跨页保持选择）
const allSelectedRows = ref(new Map())
const isSearch = ref(false)
const statisticInfo = ref({
  totalAmount: 0,
  brokerCount: 0
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])
const showReviseRecord = ref(false)
const showSalarySetting = ref(false)
const fortuneAccountDate = ref()
const reviseList = ref([])
const currencyTypeOptions = ref([])

// 对话框相关
const billingCompleteDialogVisible = ref(false)
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
let showBillingFlag = ref(false)
let currentRow = ref(null)
let billTableList = ref([{ salarySplitNo: '1' }])
let billLoading = ref(false)
let billPageTotal = ref(0)
let billCurrentPage = ref(1)
let billPageSize = ref(999)
let billStatistic = ref({ beSplitAmount: 0, beSplitCurrency: 0 })
let saleInfo = ref({})
let addBillLoading = ref(false)
let submitBillLoading = ref(false)
// 存储每行的防抖函数（原币种金额）
const debounceChangeRateMap = new WeakMap()
// 存储每行的防抖函数（汇率）
const debounceChangeToAmountMap = new WeakMap()
// 表格操作菜单
const dropdownItems = [
  { label: '拆分出账', value: 'splitBilling' },
  { label: '设置出账日', value: 'settingSalaryDate' },
  // { label: '查看记录', value: 'viewRecord' }
]
//=============拆分出账开始================
const clearInput = (key, row) => {
  if (key == 'toCurrency') {
    row.exchangeRate = '0.00'
    row.toAmount = '0.00'
  } else if (key == 'exchangeRate') {
    row.toAmount = '0.00'
  } else if (key == 'fromAmount') {
    row.toAmount = '0.00'
  }
}
const getDebouncedChangeRate = row => {
  if (!debounceChangeRateMap.has(row)) {
    const debounced = debounce(r => {
      changeRate(r)
    }, 500)
    debounceChangeRateMap.set(row, debounced)
  }
  return debounceChangeRateMap.get(row)
}

const getDebouncedChangeToAmount = row => {
  if (!debounceChangeToAmountMap.has(row)) {
    const debounced = debounce(r => {
      changeToAmount(r)
    }, 500)
    debounceChangeToAmountMap.set(row, debounced)
  }
  return debounceChangeToAmountMap.get(row)
}

// 原币种金额输入处理
const handleFromAmountInput = (val, row) => {
  row.fromAmount = amountInput.filterInput(val, 4)
  getDebouncedChangeRate(row)(row)
}

// 原币种金额失焦处理
const handleFromAmountBlur = row => {
  const debounced = debounceChangeRateMap.get(row)
  if (debounced) debounced.cancel()
  changeRate(row)
}

// 汇率输入处理
const handleExchangeRateInput = (val, row) => {
  row.exchangeRate = amountInput.filterInput(val, 4)
  getDebouncedChangeToAmount(row)(row)
}

// 汇率失焦处理
const handleExchangeRateBlur = row => {
  const debounced = debounceChangeToAmountMap.get(row)
  if (debounced) debounced.cancel()
  changeToAmount(row)
}
const billInputBlur = (type, row) => {
  if (type == 'fromAmount') {
    if (row.fromAmount) {
      changeRate(row)
    }
  } else if (type == 'exchangeRate') {
    if (row.exchangeRate) {
      changeToAmount(row)
    }
  }
}
// 改变汇率
const changeRate = async (row, type) => {
  try {
    if (row.toCurrency) {
      const params = {
        fortuneAccountBizId: currentRow.value.fortuneAccountBizId, //出账记录业务id（关联出账记录表）
        fromCurrency: currentRow.value.currency, //原币种
        fromAmount: row.fromAmount || '0.00', //原币种金额
        toCurrency: row.toCurrency //目标币种
      }
      const response = await billSplitRate(params)

      if (response.data) {
        if (type == 'toCurrency') {
          row.exchangeRate = response.data.exchangeRate ? response.data.exchangeRate.toFixed(4) : ''
        }
        if (response.data.convertedAmount > 0) {
          row.toAmount = Number(response.data.convertedAmount).toFixed(4)
        } else {
          row.toAmount = '0.00'
        }
      }
    } else {
    }
  } catch (error) {
    ElMessage.error('获取汇率失败')
  }
}
//改变目标金额
const changeToAmount = async row => {
  try {
    if (row.exchangeRate && row.fromAmount) {
      const params = {
        fromAmount: row.fromAmount, //原币种金额
        exchangeRate: row.exchangeRate //汇率
      }
      const response = await billCalculateToAmount(params)

      if (response.data) {
        row.toAmount = Number(response.data.toAmount).toFixed(4)
      }
    }
  } catch (error) {
    ElMessage.error('获取目标金额失败')
  }
}
const handleBillConfirm = async () => {
  submitBillLoading.value = true
  billTableList.value = billTableList.value.map(item => {
    item.brokerBizId = currentRow.value.brokerBizId
    return item
  })
  try {
    const params = {
      fortuneAccountBizId: currentRow.value.fortuneAccountBizId,
      apiSalarySplitBatchSaveDtoList: billTableList.value
    }
    const response = await billBatchSave(params)

    if (response.code == 200) {
      ElMessage.success('拆分出账新增保存成功')
      showBillingFlag.value = false
      submitBillLoading.value = false
    }
  } catch (error) {
    submitBillLoading.value = false
    ElMessage.error('拆分出账新增保存失败')
  }
}
const changeToCurrency = row => {
  if (row.toCurrency) {
    changeRate(row, 'toCurrency')
  } else {
    row.exchangeRate = ''
    row.toAmount = ''
  }
}
const handleBillSizeChange = val => {
  billPageSize.value = val
  getSplitTableList()
}
const handleBillCurrentChange = val => {
  billCurrentPage.value = val
  getSplitTableList()
}
// 新增拆分出账
const handleAddBill = async () => {
  addBillLoading.value = true
  try {
    const params = {
      fortuneAccountBizId: currentRow.value.fortuneAccountBizId, //出账记录业务id（关联出账记录表）
      fromAmountList: billTableList.value.map(item => {
        return item.fromAmount
      })
    }
    const response = await billSplitRemaining(params)
    console.log('====================================')
    console.log('新增拆分', response)
    console.log('====================================')
    if (response.data) {
      if (response.data.fromAmount > 0) {
        billTableList.value.push({
          brokerName: currentRow.value.broker,
          fromAmount: Number(response.data.fromAmount).toFixed(4),
          internalNumber: saleInfo.value.internalNumber ? saleInfo.value.internalNumber : '',
          id: generateId()
        })
        addBillLoading.value = false
        billPageTotal.value = billTableList.value.length
      } else {
        addBillLoading.value = false
        ElMessage.error('剩余金额不足,不能新增拆分出账')
      }
    }
  } catch (error) {
    addBillLoading.value = false
    ElMessage.error('获取剩余金额失败')
  }
}
// 删除拆分出账
const handleDeleteBill = (row, index) => {
  console.log('====================================')
  console.log('删除拆分', row)
  console.log('====================================')
  ElMessageBox.confirm('确定删除此行？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      billTableList.value.splice(index, 1)
    })
    .catch(() => {})
}
// 获取数据列表
const getSplitTableList = async (searchParams = {}) => {
  billLoading.value = true
  try {
    const params = {
      ...searchParams,
      pageNo: billCurrentPage.value,
      pageSize: billPageSize.value,
      fortuneAccountBizId: currentRow.value.fortuneAccountBizId
    }
    const userSale = await borkerDetail(currentRow.value.brokerBizId)
    if (userSale.data) {
      saleInfo.value = userSale.data
    }
    const response = await salarySplitList(params)

    if (response.data.page) {
      billTableList.value = response.data.page.records
      if (billTableList.value.length == 0) {
        billTableList.value = [
          {
            brokerName: currentRow.value.broker,
            fromAmount: Number(currentRow.value.hkdAmount).toFixed(4),
            internalNumber: userSale.data ? userSale.data.internalNumber : '',
            id: generateId(),
            exchangeRate: '0.00',
            toAmount: '0.00'
          }
        ]
        billPageTotal.value = billTableList.value.length
      } else {
        billTableList.value = billTableList.value.map(item => {
          item.brokerName = currentRow.value.broker
          item.internalNumber = userSale.data ? userSale.data.internalNumber : ''
          return item
        })
        billPageTotal.value = response.data.page.total
      }

      billLoading.value = false
      showBillingFlag.value = true
    }
    if (response.data.statisticsDto) {
      billStatistic.value = response.data.statisticsDto
    }
  } catch (error) {
    billLoading.value = false
    // ElMessage.error('获取数据失败')
  }
}
//=============拆分出账结束================
const handleSelect = (e, row) => {
  console.log('选中行:', e, row)
  currentRow.value = row
  if (e === 'splitBilling') {
    billPageSize.value = 10
    billCurrentPage.value = 1
    billTableList.value = []
    getSplitTableList()
  }else if(e==='settingSalaryDate'){
    console.log('更新薪资数据')
    fortuneAccountDate.value=  currentRow.value.fortuneAccountDate || ''
    showSalarySetting.value = true;
  }
}

const salaryDataSetting = async (e)=>{
  try{
      const params = {
        fortuneAccountBizId : currentRow.value.fortuneAccountBizId,
        fortuneAccountDate:fortuneAccountDate.value
      };
      const response = await updatePolicyFortuneAccount(params)
      if(response.code==200){
        showSalarySetting.value = false;
        ElMessage.success('修改成功')
        getList()
      }
  }catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('修改失败')
  }
 
}
// 分页事件
const handleSizeChange = val => {
  pageSize.value = val
  getList()
}
const handleCurrentChange = val => {
  currentPage.value = val
  getList()
}

// 设置当前页的选中状态
const setCurrentPageSelection = () => {
  if (!tableRef.value) return

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

  // 设置当前页应该选中的行
  tableData.value.forEach(row => {
    if (allSelectedRows.value.has(row.fortuneAccountBizId)) {
      tableRef.value.toggleRowSelection(row, true)
    }
  })
}
// 获取所有选中的行（包含跨页选择的）
const getAllSelectedRows = () => {
  return Array.from(allSelectedRows.value.values())
}
// 更新全局选中状态
const updateAllSelectedRows = () => {
  // 更新当前页的选中状态
  tableData.value.forEach(row => {
    const isSelected = selectedRows.value.some(
      selectedRow => selectedRow.fortuneAccountBizId === row.fortuneAccountBizId
    )

    if (isSelected) {
      allSelectedRows.value.set(row.fortuneAccountBizId, row)
    } else {
      allSelectedRows.value.delete(row.fortuneAccountBizId)
    }
  })
  // 当勾选项发生变化的时候，拿到最新的统计数据
  getStatistics()
}
const getStatistics = async () => {
  try {
    let fortuneAccountIdList = getAllSelectedRows().map(item => item.id)
    if (fortuneAccountIdList.length > 0) {
      // 调用接口获取来佣列表
      const res = await salaryStatistics({
        fortuneAccountIdList: fortuneAccountIdList
      })
      if (res.data) {
        statisticInfo.value = res.data
      }
    } else {
      isSearch.value = false
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('统计失败')
  }
}
// 清空所有选择
const clearAllSelection = () => {
  allSelectedRows.value.clear()
  selectedRows.value = []
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
}

// 获取数据列表
const getList = async (searchParams = {}) => {
  loading.value = true
  try {
    const params = {
      ...searchParams,
      accountDateStart: searchParams.payoutDate?.[0] || undefined,
      accountDateEnd: searchParams.payoutDate?.[1] || undefined,
      payoutDate: undefined,
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
    const response = await getReferrerFortuneList(params)

    if (response.data.page) {
      tableData.value = response.data.page.records
      pageTotal.value = response.data.page.total
      loading.value = false
    }
    if (response.data.statisticsVO) {
      statisticInfo.value = response.data.statisticsVO
    }

    // 数据加载完成后，设置当前页的选中状态
    nextTick(() => {
      setCurrentPageSelection()
    })
  } catch (error) {
    loading.value = false
    // ElMessage.error('获取数据失败')
  }
  // tableData.value = [{}]
}
getList()

const getStatusType = status => {
  const types = {
    0: 'warning',
    1: 'success',
    2: 'info'
  }
  return types[status] || 'info'
}

// 查询
const handleQuery = () => {
  const params = searchFormRef.value.getFormData()
  console.log('父组件发起查询:', params)
  clearAllSelection()
  getList(params)
}

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

// 选择行变化
const handleSelectionChange = selection => {
  selectedRows.value = selection
  // 更新全局选中状态
  updateAllSelectedRows()
}

// 完成出账
const completeBilling = 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.fortuneAccountBizId)

    // 调用出账API
    await fetchCompletePolicyFortune(arr)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('出账操作失败')
    }
  }
}

import { listType } from '@/api/system/dict/type'
const dictLists = ref([])
// 获取出账状态字典值
const getDictLists = () => {
  return new Promise((resolve, reject) => {
    listType({ typeList: ['csf_expected_fortune_status', 'bx_currency_type'] })
      .then(res => {
        if (res.code === 200 && res.data) {
          const dictData = res.data.find(item => item.dictType === 'csf_expected_fortune_status')
          dictLists.value = dictData?.dictItemList || []
          console.log('获取到的字典数据:', dictLists.value)
          // 处理币种字典值
          const currencyData = res.data.find(item => item.dictType === 'bx_currency_type')
          if (currencyData) {
            currencyData?.dictItemList.forEach(item => {
              item.value = item.itemValue
              item.label = item.itemLabel
            })
          }
          currencyTypeOptions.value = currencyData?.dictItemList || []
          resolve(dictLists.value, currencyTypeOptions.value)
        } else {
          dictLists.value = []
          currencyTypeOptions.value = []
          resolve([], [])
        }
      })
      .catch(error => {
        console.error('获取状态列表失败:', error)
        dictLists.value = []
        reject(error)
      })
  })
}
getDictLists()

// 返回数据中状态需要转换为字典值
const convertStatusToDict = status => {
  const dictItem = dictLists.value.find(item => item.itemValue == status)
  return dictItem?.itemLabel ?? status
}

// 完成出账
import { completePolicyFortune } from '@/api/financial/commission'
const fetchCompletePolicyFortune = async row => {
  try {
    const res = await completePolicyFortune({
      fortuneAccountBizIdList: row
    })
    console.log(res)
    if (res.code === 200) {
      // 显示完成弹窗
      billingCompleteDialogVisible.value = true
      getList()
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {}
}

const visibleDefaultButtons = ref(['reset', 'query'])
// 按钮配置
const operationBtnList = ref([
  {
    key: 'reset',
    direction: 'right',
    click: handleReset
  },
  {
    key: 'query',
    direction: 'right',
    click: handleQuery
  },
  {
    key: 'custom',
    label: '完成出账',
    icon: 'Check',
    type: 'warning',
    direction: 'right',
    size: 'default',
    click: completeBilling
  }
])

const formatAmount = value => {
  if (value === null || value === undefined || value === '') {
    return ''
  }
  // 转换为数字
  let num = typeof value === 'number' ? value : parseFloat(value)
  if (isNaN(num)) {
    return '' // 无效值返回空字符串
  }
  // 保留两位小数
  let fixed = num.toFixed(2)
  // 拆分整数和小数部分
  let parts = fixed.split('.')
  // 整数部分添加千位分隔符
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  return parts.join('.')
}
// 解析器（配合 formatter，保持数据一致性）
const parseAmount = value => {
  if (!value) return null
  // 移除千位分隔符
  const cleaned = value.replace(/,/g, '')
  const num = parseFloat(cleaned)
  return isNaN(num) ? null : num
}
</script>

<style scoped></style>
