<template>
  <div class="financial-income-page">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="保单号">
              <el-input v-model="searchForm.policyNo" placeholder="请输入保单号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="对账公司">
              <el-select
                v-model="searchForm.reconciliationCompany"
                placeholder="请选择对账公司"
                clearable
              >
                <el-option
                  v-for="item in companyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入账日期">
              <el-date-picker
                v-model="searchForm.incomeDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预计入账日期">
              <el-date-picker
                v-model="searchForm.expectedDate"
                type="date"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="比对状态" prop="status">
              <el-select v-model="searchForm.status" placeholder="请选择状态">
                <el-option
                  v-for="item in dictLists"
                  :key="item.itemValue"
                  :label="item.itemLabel"
                  :value="item.itemValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <div class="search-buttons">
              <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="RefreshLeft" @click="resetForm">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <div class="action-area">
      <el-button type="primary" :icon="Plus" @click="handleAdd">新增入账</el-button>

      <!-- 导入区域 -->
      <el-card class="import-card">
        <div class="import-content">
          <div class="import-actions">
            <FileUpload
              :fileType="['xlsx', 'xls']"
              :action="'/csf/api/commission/upload/excel'"
              @uploadEnd="getUploadFileFunc"
              :responseType="'onlyStatus'"
            />

            <el-button text @click="downloadTemplate" size="small" class="download-template-btn">
              下载模板
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 列表区域 -->
    <el-card class="table-card">
      <div class="totalData" v-if="getAllSelectedRows().length > 0 || isSearch">
        <span v-for="(item, index) in statisticList">
          <span :style="{ marginLeft: index == 0 ? ' 0' : '20px' }">{{ item.name }}：</span>
          <span>{{ item.format ? formatCurrency(item.value) : item.value }}</span>
        </span>
      </div>
      <el-table
        ref="tableRef"
        v-loading="tableLoading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        row-key="commissionBizId"
        :reserve-selection="true"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :reserve-selection="true"
        ></el-table-column
        >/>
        <el-table-column prop="policyNo" label="保单号" min-width="120" align="center" />
        <el-table-column prop="expectedAmount" label="总金额" min-width="120" align="center" />
        <el-table-column
          prop="currentCommissionRatio"
          label="当前来佣比例"
          min-width="120"
          align="center"
        />
        <el-table-column
          prop="periodPaidRatio"
          label="已入账来佣比例"
          min-width="120"
          align="center"
        />
        <el-table-column
          prop="periodPendingRatio"
          label="当期剩余来佣比例"
          min-width="120"
          align="center"
        />
        <el-table-column prop="paidAmount" label="已入账金额" min-width="120" align="center" />
        <el-table-column prop="pendingAmount" label="待入账金额" min-width="120" align="center" />
        <el-table-column
          prop="reconciliationCompany"
          label="对账公司"
          min-width="120"
          align="center"
        />
        <el-table-column
          prop="commissionPeriod"
          label="当前入账期数"
          min-width="100"
          align="center"
        />
        <el-table-column prop="totalPeriod" label="预计总期数" min-width="100" align="center" />
        <el-table-column prop="commissionName" label="入账项目" min-width="120" align="center" />
        <el-table-column prop="amount" label="入账金额" min-width="100" align="center" />
        <el-table-column prop="currency" label="入账币种" min-width="80" align="center">
          <template #default="scope">
            <dict-tag :options="currencyTypeOptions" :value="scope.row.currency" />
          </template>
        </el-table-column>
        <el-table-column prop="commissionDate" label="入账日期" min-width="120" align="center" />
        <el-table-column prop="status" label="比对状态" min-width="100" align="center">
          <template #default="scope">
            <span>{{ convertStatusToDict(scope.row.status) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          min-width="150"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="scope">
            <div class="btnCon">
              <el-button text size="small" type="primary" @click="handleEdit(scope.row)"
                >编辑</el-button
              >

              <el-button text size="small" type="danger" @click="handleDelete(scope.row)"
                >删除</el-button
              >
              <el-dropdown placement="bottom" style="margin-left: 10px">
                <el-button type="primary" link size="small">
                  更多 <el-icon><ArrowDown /></el-icon
                ></el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleAlignment(scope.row)"
                      >比对记录</el-dropdown-item
                    >
                    <el-dropdown-item @click="operationRecord(scope.row)"
                      >操作记录</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 底部确认按钮 -->
    <div class="footer-actions" v-if="selectedRows.length > 0">
      <el-button
        type="primary"
        size="large"
        @click="handleGenerateBilling"
        :disabled="selectedRows.length === 0"
      >
        确认生成可出账记录
      </el-button>
    </div>
    <!-- 编辑对话框 -->
    <!-- 入账记录对话框（新增/编辑共用） -->
    <el-dialog
      v-model="incomeDialogVisible"
      :title="incomeDialogTitle"
      width="600px"
      :before-close="handleCloseDialog"
    >
      <el-form :model="incomeForm" label-width="100px" :rules="incomeFormRules" ref="incomeFormRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="保单号" prop="policyNo">
              <el-select
                v-model="incomeForm.policyNo"
                filterable
                remote
                reserve-keyword
                placeholder="请输入保单号"
                :remote-method="searchPolicy"
                :loading="policyLoading"
                @change="plilcyChange"
                remote-show-suffix
              >
                <el-option
                  v-if="policyOptions.length === 0"
                  disabled
                  value=""
                  label="暂无数据"
                  style="color: #909399; text-align: center"
                />
                <el-option
                  v-for="item in policyOptions"
                  :key="item.policyBizId"
                  :label="item.policyNo"
                  :value="item.policyNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="对账公司" prop="reconciliationCompany">
              <el-select v-model="incomeForm.reconciliationCompany" placeholder="请选择对账公司">
                <el-option
                  v-for="item in companyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前期数" prop="commissionPeriod">
              <el-input-number
                v-model="incomeForm.commissionPeriod"
                :min="1"
                @change="periodChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总期数" prop="totalPeriod">
              <el-input-number v-model="incomeForm.totalPeriod" :min="1" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入账项目" prop="commissionName">
              <el-input v-model="incomeForm.commissionName" placeholder="请输入入账项目" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入账金额" prop="amount">
              <el-input v-model="incomeForm.amount" placeholder="请输入金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="币种" prop="currency">
              <el-select v-model="incomeForm.currency" placeholder="请选择币种">
                <el-option
                  v-for="item in currencyTypeOptions"
                  :key="item.itemValue"
                  :label="item.itemLabel"
                  :value="item.itemValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入账日期" prop="commissionDate">
              <el-date-picker
                v-model="incomeForm.commissionDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算汇率" prop="exchangeRate">
              <el-input v-model="incomeForm.exchangeRate" placeholder="请输入汇率" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保费" prop="premium">
              <el-input v-model="incomeForm.premium" placeholder="请输入保费" />
            </el-form-item>
          </el-col>

          <template v-if="editStatus == 'edit'">
            <el-col :span="12">
              <el-form-item label="比对状态" prop="status">
                <el-select v-model="incomeForm.status" placeholder="请选择状态">
                  <el-option
                    v-for="item in dictLists"
                    :key="item.itemValue"
                    :label="item.itemLabel"
                    :value="item.itemValue"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </template>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="incomeForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="incomeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitIncomeForm" :loading="incomeLoading">
            {{ isEditMode ? '更新' : '新增' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="比对记录" v-model="showAlignmentRecord" width="1000px" append-to-body>
      <el-table :data="alignmentList" border>
        <el-table-column prop="createTime" label="比对时间" align="center" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="佣金期数" prop="commissionPeriod" align="center" fixed="left">
        </el-table-column>

        <el-table-column label="总期数" prop="totalPeriod" align="center"></el-table-column>
        <el-table-column prop="status" label="比对状态" min-width="100" align="center">
          <template #default="scope">
            <span>{{ convertStatusToDict(scope.row.status) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="来佣币种" prop="currency" align="center"
          ><template #default="scope">
            <dict-tag :options="currencyTypeOptions" :value="scope.row.currency" /> </template
        ></el-table-column>
        <el-table-column label="入账金额" prop="amount" align="center"></el-table-column>
        <el-table-column label="结算汇率" prop="exchangeRate" align="center"></el-table-column>
      </el-table>
      <el-pagination
        v-show="alignmentPages.total >= 0"
        :total="alignmentPages.total"
        :current-page="alignmentPages.pageNo"
        :page-size="alignmentPages.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleAlignmentSizeChange"
        @current-change="handleAlignmentCurrentChange"
        style="margin-top: 10px"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="操作记录" v-model="showOperationRecord" width="1000px" append-to-body>
      <el-table :data="operationList" border>
        <el-table-column label="变更字段" prop="field" align="center" width="150"></el-table-column>
        <el-table-column
          label="变更前信息"
          prop="beforeChange"
          align="center"
          width="200"
        ></el-table-column>
        <el-table-column label="变更后信息" prop="afterChange" align="center" width="200">
        </el-table-column>
        <el-table-column label="变更人" prop="userName" align="center" width="150">
        </el-table-column>
        <el-table-column prop="createTime" label="变更时间" align="center">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-show="operationPages.total >= 0"
        :total="operationPages.total"
        :current-page="operationPages.pageNo"
        :page-size="operationPages.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleOperationSizeChange"
        @current-change="handleOperationCurrentChange"
        style="margin-top: 10px"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { Search, RefreshLeft, UploadFilled, Plus, Document } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 导入有关来佣的接口
import {
  getPolicyCommissionList,
  downloadPolicyFortune,
  generateCommissionRecord,
  updatePolicyCommission,
  incomeStatistics,
  incomeEditRecords,
  incomeCompareRecords,
  policyData
} from '@/api/financial/commission'

import FileUpload from '@/components/FileUpload/index'
import { useRouter } from 'vue-router'
const { proxy } = getCurrentInstance()
const router = useRouter()

import { listType } from '@/api/system/dict/type'
// 添加表格引用
const tableRef = ref()
const statisticList = ref([
  { name: '合计应入账金额', value: '0', key: 'totalAmount', format: true },
  { name: '合计实际入账金额', value: '0', key: 'totalPaidAmount', format: true },
  { name: '待入账金额', value: '0', key: 'pendingPaidAmount', format: true },
  { name: '已入账比例', value: '0', key: 'paidAmountRatio', format: false },
  { name: '总保单数', value: '0', key: 'totalPolicyCount', format: false }
])
// 存储所有选中的行数据（用于跨页保持选择）
const allSelectedRows = ref(new Map())
const alignmentList = ref([]) //比对记录列表
const operationList = ref([]) //操作记录列表
const showAlignmentRecord = ref(false) // 是否显示比对记录列表
const showOperationRecord = ref(false) // 是否显示比对记录列表
// 通过dictType=csf_commission_status获取比对状态字典值,获取对象中的dictItemList
const dictLists = ref([])
const currencyTypeOptions = ref([])
const alignmentPages = reactive({
  total: 0,
  pageNo: 1,
  pageSize: 5
})
const operationPages = reactive({
  total: 0,
  pageNo: 1,
  pageSize: 5
})
const currentRowOperation = ref({})

const isSearch = ref(false)
const editStatus = ref('add')
const policyLoading = ref(false)
const policyOptions = ref([])
// 搜索保单方法
const searchPolicy = query => {
  policyLoading.value = true
  try {
    const params = {
      policyNo: query,
      pageNo: 1,
      pageSize: 10
    }

    policyData(params).then(response => {
      policyOptions.value = response.data.records
    })
  } catch (error) {
    console.error('保单号搜索失败', error)
    policyOptions.value = []
  } finally {
    policyLoading.value = false
  }
}
const plilcyChange = () => {
  policyOptions.value.forEach(item => {
    if (incomeForm.policyNo == item.policyNo) {
      incomeForm.premium = item.premium
      incomeForm.totalPeriod = item.totalPeriod
    }
  })
}
const periodChange = () => {
  if (
    incomeForm.totalPeriod &&
    incomeForm.commissionPeriod &&
    incomeForm.commissionPeriod > incomeForm.totalPeriod
  ) {
    ElMessage.error('当前期数不能大于总期数')
    incomeForm.commissionPeriod = '1'
  }
}
const getAlignmentData = () => {
  let data = {
    commissionBizId: currentRowOperation.value.commissionBizId,
    pageNo: alignmentPages.pageNo,
    pageSize: alignmentPages.pageSize
  }
  incomeCompareRecords(data).then(response => {
    if (response.code == 200) {
      alignmentList.value = response.data.records
      alignmentPages.total = response.data.total
      showAlignmentRecord.value = true
    } else {
      ElMessage.error(response.msg)
      showAlignmentRecord.value = false
      alignmentPages.total = 0
      alignmentList.value = []
    }
  })
}
const getOperationData = () => {
  let data = {
    commissionBizId: currentRowOperation.value.commissionBizId,
    pageNo: operationPages.pageNo,
    pageSize: operationPages.pageSize
  }
  incomeEditRecords(data).then(response => {
    if (response.code == 200) {
      operationList.value = response.data.records
      operationPages.total = response.data.total
      showOperationRecord.value = true
    } else {
      ElMessage.error(response.msg)
      showOperationRecord.value = false
      operationPages.total = 0
      operationList.value = []
    }
  })
}
// 比对记录分页事件
const handleAlignmentSizeChange = val => {
  alignmentPages.pageSize = val
  alignmentPages.pageNo = 1
  getAlignmentData()
}

const handleAlignmentCurrentChange = val => {
  alignmentPages.pageNo = val
  getAlignmentData()
}

// 操作记录分页事件
const handleOperationSizeChange = val => {
  operationPages.pageSize = val
  operationPages.pageNo = 1
  getOperationData()
}

const handleOperationCurrentChange = val => {
  operationPages.pageNo = val
  getOperationData()
}
const closeDialog = () => {
  showAlignmentRecord.value = false
  alignmentList.value = []
  alignmentPages.value = {
    pageNo: 1,
    pageSize: 5,
    total: 0
  }
  showOperationRecord.value = false
  operationList.value = []
  operationPages.value = {
    pageNo: 1,
    pageSize: 5,
    total: 0
  }
}
// 设置当前页的选中状态
const setCurrentPageSelection = () => {
  if (!tableRef.value) return

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

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

  // 从全局选中中移除当前页不再存在的行
  // for (const key of allSelectedRows.value.keys()) {
  //   if (!currentPageKeys.includes(key)) {
  //     allSelectedRows.value.delete(key)
  //   }
  // }

  // 更新当前页的选中状态
  tableData.value.forEach(row => {
    const isSelected = selectedRows.value.some(
      selectedRow => selectedRow.commissionBizId === row.commissionBizId
    )

    if (isSelected) {
      allSelectedRows.value.set(row.commissionBizId, row)
    } else {
      allSelectedRows.value.delete(row.commissionBizId)
    }
  })
  getStatistics()
}
const getStatistics = async () => {
  try {
    let commissionIds = getAllSelectedRows().map(item => item.id)
    if (commissionIds.length > 0) {
      // 调用接口获取来佣列表
      const res = await incomeStatistics({
        commissionIds: commissionIds
      })
      if (res.data) {
        statisticList.value.forEach(item => {
          item.value = res.data[item.key]
        })
      }
    } 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 formatCurrency = amount => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(amount)
}
const getLists = () => {
  return new Promise((resolve, reject) => {
    listType({ typeList: ['csf_commission_status', 'bx_currency_type'] })
      .then(res => {
        if (res.code === 200 && res.data) {
          const dictData = res.data.find(item => item.dictType === 'csf_commission_status')
          dictLists.value = dictData?.dictItemList || []
          // 处理币种字典值
          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)
      })
  })
}
// 返回数据中状态需要转换为字典值
const convertStatusToDict = status => {
  const dictItem = dictLists.value.find(item => item.itemValue == status)
  return dictItem?.itemLabel ?? status
}

// 增加通过表格排序，排序字段sortField，升降序sortOrder
const handleSortChange = column => {
  pagination.sortField = column.prop
  pagination.sortOrder = column.order === 'ascending' ? 'ascend' : 'descend'
  fetchTableData()
}

// 搜索表单数据
const searchForm = reactive({
  policyNo: '',
  reconciliationCompany: '',
  incomeDateRange: [],
  status: '',
  expectedDate: ''
})

// 对账公司选项

const companyOptions = ref([])
// 获取对账公司列表
import { getReconciliationCompanyList } from '@/api/financial/commission'
import { getAllCompanys } from '@/api/common'
const fetchReconciliationCompanyList = async () => {
  try {
    const response = await getAllCompanys({
      pageNo: 1,
      pageSize: 1000
    })
    if (response.code === 200) {
      companyOptions.value = response.data.records.map(item => ({
        label: item.deptName,
        value: item.deptBizId
      }))
    } else {
      ElMessage.error(response.msg)
    }
  } catch (error) {
    ElMessage.error('获取对账公司列表失败')
  }
}

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

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

onMounted(() => {
  // 获取字典值后，再调用接口获取来佣列表
  initialData()
})

const initialData = async () => {
  await getLists()

  fetchTableData()
  fetchReconciliationCompanyList()
}

const getUploadFileFunc = data => {
  console.log(data)
  if (data === 200) {
    ElMessage.success('上传成功')
    fetchTableData()
  } else {
    ElMessage.error('上传失败')
  }
}

// 获取列表数据
// 调用接口获取入账列表
const fetchTableData = async () => {
  tableLoading.value = true
  try {
    // 调用接口获取来佣列表
    const res = await getPolicyCommissionList({
      pageNo: pagination.currentPage,
      pageSize: pagination.pageSize,
      policyNo: searchForm.policyNo,
      status: searchForm.status,
      expectedDate: searchForm.expectedDate ? proxy.parseTime(searchForm.expectedDate) : '',
      reconciliationCompany: searchForm.reconciliationCompany,
      startTime: searchForm.incomeDateRange[0] ? `${searchForm.incomeDateRange[0]} 00:00:00` : '',
      endTime: searchForm.incomeDateRange[1] ? `${searchForm.incomeDateRange[1]} 23:59:59` : ''
    })
    if (res.data.page) {
      tableData.value = res.data.page.records
      pagination.total = res.data.page.total
    }
    if (res.data.commissionStatisticsVO && isSearch.value) {
      statisticList.value.forEach(item => {
        item.value = res.data.commissionStatisticsVO[item.key]
      })
    }
    // 数据加载完成后，设置当前页的选中状态
    nextTick(() => {
      setCurrentPageSelection()
    })
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1
  Object.values(searchForm).some(value => {
    if (Array.isArray(value) && value.length > 0) {
      isSearch.value = true
    }
    if (value !== '' && value != null) {
      isSearch.value = true
    }
  })
  clearAllSelection()
  fetchTableData()
  ElMessage.success('查询成功')
}

// 重置表单
const resetForm = () => {
  searchForm.policyNo = ''
  searchForm.reconciliationCompany = ''
  searchForm.status = ''
  searchForm.expectedDate = ''
  searchForm.incomeDateRange = []
  isSearch.value = false
  pagination.currentPage = 1
  pagination.pageSize = 10
  // 清空选择
  clearAllSelection()
  ElMessage.success('已重置筛选条件')
  fetchTableData()
}

// 处理分页大小变化
const handleSizeChange = val => {
  pagination.pageSize = val
  fetchTableData()
}

// 处理分页页码变化
const handleCurrentChange = val => {
  pagination.currentPage = val

  fetchTableData()
}

// 处理表格选择变化
const handleSelectionChange = rows => {
  selectedRows.value = rows
  // 更新全局选中状态
  updateAllSelectedRows()
}

// 下载模板
const downloadTemplate = () => {
  //  下载地址
  const templateUrl =
    'https://yd-ali-oss.oss-cn-shanghai-finance-1-pub.aliyuncs.com/xlsx/2025/10/14/54ce715eabab4f1abd8652ba0fca0c51.xlsx'
  // 修改下载文件名
  const fileName = '对账单导入模板.xlsx'
  // 下载文件
  window.open(templateUrl, '_blank', `download=${fileName}-${new Date().getTime()}`)
}

// 新增入账
const handleAdd = () => {
  incomeDialogTitle.value = '新增入账记录'
  isEditMode.value = false
  editStatus.value = 'add'
  // 重置表单数据
  Object.assign(incomeForm, {
    commissionBizId: '',
    policyNo: '',
    reconciliationCompany: '',
    commissionPeriod: 1,
    totalPeriod: 1,
    commissionName: '',
    amount: 0,
    currency: 'HKD',
    commissionDate: '',
    remark: '',
    exchangeRate: '7.80',
    premium: '',
    status: ''
  })

  // 重置表单验证
  if (incomeFormRef.value) {
    incomeFormRef.value.clearValidate()
  }

  incomeDialogVisible.value = true
}

import { deletePolicyCommission } from '@/api/financial/commission'
// 删除
const handleDelete = row => {
  ElMessageBox.confirm(`确定要删除保单 ${row.policyNo} 的入账记录吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用删除接口
    deletePolicyCommission({
      commissionBizId: row.commissionBizId
    })
      .then(res => {
        if (res.code === 200) {
          ElMessage.success('删除成功')
          fetchTableData()
        } else {
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {
        ElMessage.error('删除失败')
      })
  })
}

// 生成可出账记录
// 调用generateCommissionRecord接口
const handleGenerateBilling = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要生成可出账记录的记录')
    return
  }
  try {
    console.log(selectedRows.value)
    await generateCommissionRecord({
      commissionBizIdList: selectedRows.value.map(row => row.commissionBizId)
    })
    ElMessage.success('生成成功')
    // 这里可以添加路由跳转到 financialBilling 组件
    // router.push('/financialCenter/financial/billing')
  } catch (error) {
    console.error('生成失败:', error)
    ElMessage.error('生成失败')
  }
}

// 入账记录对话框相关
const incomeDialogVisible = ref(false)
const incomeDialogTitle = ref('入账记录')
const incomeLoading = ref(false)
const isEditMode = ref(false)
const incomeFormRef = ref()

// 入账表单数据
const incomeForm = reactive({
  commissionBizId: '',
  policyNo: '',
  reconciliationCompany: '',
  commissionPeriod: 1,
  totalPeriod: 1,
  commissionName: '',
  amount: 0,
  currency: 'CNY',
  commissionDate: '',
  remark: '',
  expectedDate: '',
  exchangeRate: '',
  premium: '',
  status: ''
})
// 表单验证规则
const incomeFormRules = {
  policyNo: [{ required: true, message: '请输入保单号', trigger: 'blur' }],
  reconciliationCompany: [{ required: true, message: '请选择对账公司', trigger: 'change' }],
  commissionName: [{ required: true, message: '请输入入账项目', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
  commissionDate: [{ required: true, message: '请选择入账日期', trigger: 'change' }]
}

// 编辑入账记录
const handleEdit = row => {
  incomeDialogTitle.value = `编辑入账记录 - ${row.policyNo}`
  isEditMode.value = true
  editStatus.value = 'edit'
  console.log('row', row)

  // 填充表单数据
  Object.assign(incomeForm, {
    commissionBizId: row.commissionBizId,
    policyNo: row.policyNo,
    reconciliationCompany: row.reconciliationCompany,
    commissionPeriod: row.commissionPeriod || 1,
    totalPeriod: row.totalPeriod || 1,
    commissionName: row.commissionName,
    amount: row.amount,
    currency: row.currency || 'CNY',
    commissionDate: row.commissionDate,
    remark: row.remark || '',
    exchangeRate: row.exchangeRate || '',
    premium: row.premium || '',
    status: row.status || ''
  })

  // 重置表单验证
  if (incomeFormRef.value) {
    incomeFormRef.value.clearValidate()
  }

  incomeDialogVisible.value = true
}
const handleAlignment = row => {
  currentRowOperation.value = row
  getAlignmentData()
}
const operationRecord = row => {
  currentRowOperation.value = row
  getOperationData()
}
// 提交入账表单（新增/编辑共用）
import { addPolicyCommission } from '@/api/financial/commission'
import { computed } from 'vue'
const submitIncomeForm = async () => {
  if (!incomeFormRef.value) {
    ElMessage.error('请先初始化表单')
    return
  }

  try {
    // 表单验证
    const valid = await incomeFormRef.value.validate()
    if (!valid) {
      ElMessage.warning('请完善表单信息')
      return
    }

    incomeLoading.value = true

    if (isEditMode.value) {
      // 编辑模式 - 调用更新接口
      await updatePolicyCommission(incomeForm)
      ElMessage.success('更新成功')
    } else {
      // 新增模式 - 调用新增接口
      // 注意：这里需要根据实际的新增API进行调整
      await addPolicyCommission(incomeForm)
      ElMessage.success('新增成功')
    }

    incomeDialogVisible.value = false
    fetchTableData() // 刷新表格数据
  } catch (error) {
    if (error && error.errorFields) {
      ElMessage.warning('请完善表单信息')
    } else {
      console.error(isEditMode.value ? '更新失败:' : '新增失败:', error)
      ElMessage.error(isEditMode.value ? '更新失败' : '新增失败')
    }
  } finally {
    incomeLoading.value = false
  }
}

// 关闭对话框处理
const handleCloseDialog = done => {
  if (incomeLoading.value) {
    ElMessage.info('正在保存，请稍候...')
    return
  }

  ElMessageBox.confirm('确定要关闭吗？未保存的修改将会丢失', '提示', {
    type: 'warning'
  })
    .then(() => {
      done()
    })
    .catch(() => {})
}
</script>

<style scoped>
.btnCon {
  display: flex;
  align-items: center;
  justify-content: center;
}
.financial-income-page {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.search-card {
  margin-bottom: 20px;
  padding: 15px 20px;
}

.search-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
  height: 32px;
}

.action-area {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.import-card {
  padding: 20px;
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
}

.import-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.import-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.upload-excel {
  display: inline-block;
}

/* 文件信息显示样式 */
.file-info {
  margin-top: 15px;
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-info-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-info-content .el-icon {
  color: #409eff;
  font-size: 16px;
}

.file-name {
  font-weight: 500;
  color: #303133;
}

.file-size {
  color: #909399;
  font-size: 12px;
}

.confirm-import-btn {
  margin-left: 12px;
}

/* 下载模板按钮样式 */
.download-template-btn {
  color: #409eff;
  font-size: 12px;
  padding: 8px 12px;
}

.download-template-btn:hover {
  background-color: #ecf5ff;
}

.table-card {
  padding: 15px 20px;
}
.totalData {
  margin-bottom: 10px;
  font-size: 14px;
  color: #000;
}
.pagination {
  margin-top: 15px;
  text-align: right;
}

.footer-actions {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .import-actions {
    flex-wrap: wrap;
  }

  .download-template-btn {
    margin-top: 10px;
  }

  .file-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .confirm-import-btn {
    margin-left: 0;
    align-self: flex-end;
  }
}

@media (max-width: 992px) {
  .search-card .el-col {
    margin-bottom: 15px;
  }

  .search-buttons {
    justify-content: flex-start;
  }
}

@media (max-width: 768px) {
  .search-card .el-col {
    width: 100%;
  }

  .import-actions {
    flex-direction: column;
    align-items: flex-start;
  }

  .download-template-btn {
    margin-top: 10px;
  }
}
</style>
