<template>
  <div class="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>
        <!-- 统计信息卡片 -->

        <el-table
          :data="tableData"
          @selection-change="handleSelectionChange"
          height="400"
          border
          highlight-current-row
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column prop="fortuneBizType" label="应付单类型" width="120" sortable>
            <template #default="{ row }">
              {{ getFortuneBizTypeLabel(row.fortuneBizType) }}
            </template>
          </el-table-column>
          <el-table-column prop="policyNo" label="保单号" width="120" sortable />
          <el-table-column prop="insuranceCompany" label="保险公司" width="120" sortable />
          <el-table-column
            prop="commissionPaidAmount"
            label="累积已入账金额"
            width="120"
            sortable
          />
          <el-table-column prop="commissionPaidRatio" label="累积已入账比例" width="120" sortable />
          <el-table-column prop="fortuneName" label="出账项目" width="130" sortable />
          <el-table-column prop="fortunePeriod" label="出账期数" width="130" sortable />
          <el-table-column prop="fortuneTotalPeriod" label="总期数" width="120" sortable />
          <el-table-column prop="broker" label="转介人" width="130" sortable />
          <el-table-column prop="team" label="所属团队" width="120" sortable />
          <el-table-column prop="amount" label="应出账金额" width="140" sortable />
          <el-table-column prop="currency" label="出账币种" width="130" sortable />
          <el-table-column prop="fortunePaidAmount" label="已出账金额" width="120" sortable />
          <el-table-column prop="fortuneUnpaidAmount" label="剩余出账金额" width="120" sortable />
          <el-table-column prop="currentPaymentAmount" label="本期出账金额" width="120" sortable />
          <el-table-column prop="fortuneUnpaidRatio" label="剩余出账比例" width="120" sortable />
          <el-table-column prop="status" label="出账状态" width="120" sortable>
            <template #default="{ row }">
              {{ getDictLabel('csf_fortune_status', row.status) }}
            </template>
          </el-table-column>
          <el-table-column prop="premium" label="期交保费" width="120" sortable />
          <el-table-column prop="payoutDate" label="出账日（实）" width="120" sortable />
          <el-table-column prop="remark" label="备注" width="120" sortable />
          <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="80%"
      :openDialog="addCheckRecordFormDialogFlag"
      :showAction="true"
      :showClose="true"
      @close="addCheckRecordFormDialogFlag = false"
      @confirm="addCheckRecordaddBatchapi"
    >
      <SearchForm
        ref="addCheckRecordFormRef"
        :config="addCheckRecordConfig"
        v-model="addCheckRecordFormModel"
      />
    </CommonDialog>
    <!-- 导入出账检核页面 -->
    <CommonDialog
      dialogTitle="新增出账检核"
      dialogWidth="80%"
      :openDialog="importCheckRecordFlag"
      :showAction="true"
      :showClose="true"
      @close="importCheckRecordFlag = false"
    >
      <FileUploadPreview
        :header-row="0"
        :required-fields="'amount,exchangeRate'"
        :use-chinese-header="true"
        :transform-submit-data="transformToBackend"
        @submit="onSubmit"
      />
    </CommonDialog>
    <!-- 设置本期出账金额 -->
    <CommonDialog
      dialogTitle="设置本期出账金额"
      dialogWidth="80%"
      :openDialog="setPayoutAmountDialogFlag"
      :showAction="true"
      :showClose="true"
      @close="setPayoutAmountDialogFlag = false"
      @confirm="updatePayoutAmountapi"
    >
      <SearchForm
        ref="setPayoutAmountFormRef"
        :config="setPayoutAmountConfig"
        v-model="setPayoutAmountFormModel"
      />
    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import CommonPage from '@/components/commonPage'
import CommonDialog from '@/components/commonDialog'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import { ElMessage } from 'element-plus'
import { formatCurrency } from '@/utils/number'
// 接口
import {
  getPolicyFortuneList,
  addCheckRecordaddBatch,
  updatePayoutAmount,
  downloadPolicyFortuneAccount
} from '@/api/financial/commission'
import useUserStore from '@/store/modules/user'
import { loadDicts, getDictLabel } from '@/utils/useDict'

const userStore = useUserStore()
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const loading = ref(false)
const selectedRow = ref(null)
const searchFormRef = ref(null)
const searchParams = ref({})
const searchConfig = ref([
  {
    type: 'input',
    prop: 'policyNo',
    label: '保单号'
  },
  {
    type: 'select',
    prop: 'statusList',
    label: '出账状态',
    multiple: true,
    dictType: 'csf_fortune_status'
  },
  {
    type: 'select',
    prop: 'insuranceCompanyBizIdList',
    label: '保险公司',
    api: '/insurance/base/api/insuranceCompany/page',
    keywordField: 'queryContent',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入保险公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    multiple: true,
    valueKey: 'insuranceCompanyBizId',
    labelKey: 'abbreviation',
    transform: res => {
      console.log(res)
      return res?.data.records || []
    }
  },
  {
    type: 'select',
    prop: 'productLaunchBizIdList',
    label: '产品计划',
    api: '/product/api/relProjectProductLaunch/parameter/page',
    keywordField: 'productName',
    requestParams: {
      tenantBizId: userStore.projectInfo.tenantBizId || '',
      projectBizId: userStore.projectInfo.projectBizId || '',
      fieldBizId: 'field_olk1qZe81qHHKXbw',
      fieldValueBizId: 'field_value_uOfJH5ucA2YwJpbn',
      pageNo: 1,
      pageSize: 20
    },
    placeholder: '输入产品计划名称搜索',
    debounceWait: 500, // 自定义防抖时间
    multiple: true,
    valueKey: 'productLaunchBizId',
    labelKey: 'productName',
    transform: res => {
      return res?.data.records || []
    }
  },
  {
    type: 'daterange',
    prop: 'payoutDate',
    label: '出账日（估）',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间'
  }
  // {
  //   type: 'select',
  //   prop: 'status',
  //   label: '入账状态',
  //   multiple: true,
  //   dictType: 'csf_expected_commission_status'
  // },
])
// 表格操作菜单
const dropdownItems = [
  { label: '设置本期出账金额', value: 'setPayRoll' }
  // { label: '更新', value: 'editRecord' },
  // { label: '查看记录', value: 'viewRecord' }
]
// 应收单类型
const fortuneBizTypeOptions = [
  { value: 'R', label: '关联保单应付单' },
  { value: 'U', label: '非关联保单应付单' }
]
// 应付单类型通过value转成label
const getFortuneBizTypeLabel = value => {
  const item = fortuneBizTypeOptions.find(item => item.value === value)
  return item?.label || ''
}
// 新增出账检核
const addCheckRecordFormModel = ref({})
const addCheckRecordFormRef = ref(null)
const addCheckRecordFormDialogFlag = ref(false)
const addCheckRecordConfig = [
  {
    type: 'select',
    prop: 'fortuneBizType',
    label: '应付单类型',
    options: fortuneBizTypeOptions
  },
  {
    type: 'select',
    prop: 'status',
    label: '出账状态',
    dictType: 'csf_expected_fortune_status'
  },
  {
    type: 'input',
    prop: 'policyNo',
    label: '关联保单号',
    visible: formData => formData.fortuneBizType === 'R'
  },
  {
    type: 'input',
    prop: 'fortunePeriod',
    label: '佣金期数',
    inputType: 'decimal',
    visible: formData => formData.fortuneBizType === 'R',
    rules: [{ pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'fortuneTotalPeriod',
    label: '总期数',
    inputType: 'decimal',
    visible: formData => formData.fortuneBizType === 'R',
    rules: [{ pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
  },
  {
    type: 'date',
    prop: 'actualPayoutDate',
    label: '出账日（实）',
    placeholder: '请选择',
    maxDate: 'today'
  },
  {
    type: 'input',
    prop: 'amount',
    label: '出账金额',
    inputType: 'decimal',
    rules: [{ pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'currency',
    label: '出账币种',
    dictType: 'bx_currency_type'
  },
  {
    type: 'select',
    prop: 'fortuneType',
    label: '出账项目',
    dictType: 'csf_fortune_type'
  },
  {
    type: 'select',
    prop: 'brokerBizId',
    label: '转介人',
    api: '/insurance/base/api/userSaleExpand/page',
    keywordField: 'realName',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入转介人名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'userSaleBizId',
    labelKey: 'realName',
    onChangeExtraFields: {
      broker: 'realName', // 自动同步 raw.name 到 reconciliationCompany
      reconciliationCompanyCode: 'code'
    },
    transform: res => {
      return res?.data.records || []
    }
  }
]

// 设置本期出账金额
const setPayoutAmountFormModel = ref({})
const setPayoutAmountFormRef = ref(null)
const setPayoutAmountDialogFlag = ref(false)
const setPayoutAmountConfig = [
  {
    type: 'input',
    prop: 'currentPaymentAmount',
    label: '出账金额',
    inputType: 'decimal',
    rules: [{ pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'currency',
    label: '出账币种',
    dictType: 'bx_currency_type'
  },
  {
    type: 'select',
    prop: 'status',
    label: '出账状态',
    dictType: 'csf_expected_fortune_status'
  }
]

// 统计信息
const statisticsData = ref({})
// 弹窗相关
const dialogFlag = ref(false)

// 按钮事件处理
const handleAdd = () => {
  addCheckRecordFormDialogFlag.value = true
}

const handleExport = () => {
  ElMessage.info('点击导出按钮')
}
const handleReset = () => {
  // 重置搜索表单
  searchFormRef.value.resetForm()
  console.log('表单已重置')
}
const handleQuery = async () => {
  const params = searchFormRef.value.getFormData()
  loadTableData(params)
}
const visibleDefaultButtons = ref(['add', 'import', 'export', 'reset', 'query'])
// 按钮配置
const operationBtnList = ref([
  {
    key: 'add',
    direction: 'left',
    label: '新增出账',
    click: handleAdd
  },

  {
    key: 'export',
    direction: 'right',
    click: handleExport
  },
  {
    key: 'reset',
    direction: 'right',
    click: handleReset
  },
  {
    key: 'query',
    direction: 'right',
    click: handleQuery
  }
])

// 加载表格数据
const loadTableData = async (searchParams = {}) => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      ...searchParams,
      payoutDateStart: searchParams.payoutDate?.[0] || undefined,
      payoutDateEnd: searchParams.payoutDate?.[1] || undefined,
      payoutDate: undefined
    }
    const res = await getPolicyFortuneList(params)
    tableData.value = res.data.page.records || []
    pageTotal.value = res.data.page.total || 0
    pageSize.value = res.data.page.size || 0
    // 统计信息
    statisticsData.value = res.data.statisticsVO || {}
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error(error.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}
loadTableData()
// 分页事件
const handleSizeChange = val => {
  pageSize.value = val
  loadTableData()
}
const handleCurrentChange = val => {
  currentPage.value = val
  loadTableData()
}
// 表格数据
const tableData = ref([])

const handleSelect = (e, row) => {
  console.log('选中行:', e, row)
  selectedRow.value = row
  if (e === 'setPayRoll') {
    setPayoutAmountDialogFlag.value = true
  }
}
const addCheckRecordaddBatchapi = async data => {
  const formData = addCheckRecordFormRef.value.getFormData()
  console.log('新增出账检核记录:', formData)
  const params = [{ ...formData }]
  try {
    const res = await addCheckRecordaddBatch(params)
    if (res.code === 200) {
      ElMessage.success('新增出账检核记录成功')
      addCheckRecordFormDialogFlag.value = false
      addCheckRecordFormRef.value.resetForm()
      loadTableData()
    } else {
      ElMessage.error(res.msg || '新增出账检核记录失败')
    }
  } catch (error) {
    console.error('新增出账检核记录失败:', error)
    ElMessage.error(error.message || '新增出账检核记录失败')
  }
}

// 设置本期出账金额
const updatePayoutAmountapi = async data => {
  console.log('设置本期出账金额:', data)
  const params = {
    ...setPayoutAmountFormRef.value.getFormData(),
    fortuneBizId: selectedRow.value.fortuneBizId
  }
  try {
    const res = await updatePayoutAmount(params)
    if (res.code === 200) {
      ElMessage.success('设置本期出账金额成功')
      loadTableData()
    } else {
      ElMessage.error(res.msg || '设置本期出账金额失败')
    }
  } catch (error) {
    console.error('设置本期出账金额失败:', error)
    ElMessage.error(error.message || '设置本期出账金额失败')
  }
}
const updatePayRollStatusDisable = ref(true)
const multipleSelection = ref([])
const handleSelectionChange = val => {
  multipleSelection.value = val
  console.log('全选:', val)
  // 完成检核按钮是否禁用
  updatePayRollStatusDisable.value = val.length === 0
}

const downloadPolicyFortuneAccountapi = async data => {
  console.log('生成出账清单:', data)
  try {
    const res = await downloadPolicyFortuneAccount({
      fortuneBizIdList: multipleSelection.value.map(item => item.fortuneBizId)
    })
    if (res.code === 200) {
      ElMessage.success('完成检核，等待关账')
      loadTableData()
    }
  } catch (error) {
    console.error('检核失败:', error)
    ElMessage.error(error.response?.data?.msg || '检核失败')
  }
}
import FileUploadPreview from '@/components/fileUploadPreview/fileUploadPreview.vue'

const importCheckRecordFlag = ref(false)
// 如果后端接收的就是当前格式，可直接透传
const formatForBackend = rows => {
  return rows.map(row => ({
    ...row,
    amount: Number(row.amount) || 0,
    exchangeRate: Number(row.exchangeRate) || 1
  }))
}

const onSubmit = data => {
  console.log('提交给后端的数据:', data)
  // 调用保存 API
}

// 获取入账状态,字典值转化方法
onMounted(async () => {
  try {
    await loadDicts(['csf_fortune_status'])
  } catch (error) {
    console.error('字典加载失败', error)
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.tableOptionContainer {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>
