<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>
        <!-- 统计信息卡片 -->
        <div class="statistics-container" v-if="statisticsData.totalPolicyCount > 0">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">入账金额</div>
                  <div class="card-value">{{ statisticsData.totalInAmount }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">总保费数</div>
                  <div class="card-value">{{ formatCurrency(statisticsData.totalPremiumAmount) }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">总保费（HKD）</div>
                  <div class="card-value">{{ statisticsData.reconciliationCompanyCount }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">待出账金额</div>
                  <div class="card-value">{{ statisticsData.reconciliationRecordCount }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">可出账金额</div>
                  <div class="card-value">{{ statisticsData.reconciliationSuccessCount }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">差额（估）</div>
                  <div class="card-value">{{ formatCurrency(statisticsData.reconciliationFailureAmount) }}</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        <el-table :data="tableData" height="400" border highlight-current-row style="width: 100%" v-loading="loading">
          <el-table-column prop="policyNo" label="保单号" width="120" sortable />
          <el-table-column prop="reconciliationCompany" label="保险公司" width="120" sortable />
          <el-table-column prop="payableNo" label="累积已入账金额" width="120" sortable />
          <el-table-column prop="payableNo" label="累积已入账比例" width="120" sortable />
          <el-table-column prop="payableNo" label="出账项目" width="130" sortable />
          <el-table-column prop="payableNo" label="出账期数" width="130" sortable />
          <el-table-column prop="payableNo" label="总期数" width="120" sortable />
          <el-table-column prop="payableNo" label="转介人" width="130" sortable />
          <el-table-column prop="currency" label="所属团队" width="120" sortable />
          <el-table-column prop="payableNo" label="应出账金额" width="140" sortable />
          <el-table-column prop="commissionPeriod" label="出账币种" width="130" sortable />
          <el-table-column prop="totalPeriod" label="已出账金额" width="120" sortable />
          <el-table-column prop="commissionName" label="剩余出账金额" width="120" sortable />
          <el-table-column prop="premium" label="本期出账金额" width="120" sortable />
          <el-table-column prop="remark" label="剩余出账比例" width="120" sortable />
          <el-table-column prop="status" label="出账状态" width="120" sortable />
          <el-table-column prop="status" label="期交保费" width="120" sortable />
          <el-table-column prop="status" label="出账日（实）" width="120" sortable />
          <el-table-column prop="status" 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=dialogFlag :showAction='false' :showClose='true'
      @close='dialogFlag = false'>

    </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 } from '@/api/financial/commission'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const loading = ref(false)
const searchFormRef = ref(null)
const searchParams = ref({})
const searchConfig = ref([
  {
    type: 'input',
    prop: 'policyNo',
    label: '保单号'
  }, {
    type: 'select',
    prop: 'status',
    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, // 自定义防抖时间
    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, // 自定义防抖时间
    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 statisticsData = ref({})
// 弹窗相关
const dialogFlag = ref(false)

// 按钮事件处理
const handleAdd = () => {
  ElMessage.info('点击新增按钮')
}
const handleImport = () => {
  ElMessage.info('点击导入按钮')
}
const handleExport = () => {
  ElMessage.info('点击导出按钮')
}
const handleReset = () => {
  // 重置搜索表单
  searchFormRef.value.resetForm()
  searchParams.value = {}
  console.log('表单已重置')
}
const handleQuery = async () => {
  const params = searchFormRef.value.getFormData()
  console.log('父组件发起查询:', params)
  loadTableData(params)
}
const visibleDefaultButtons = ref(['add', 'import', 'export', 'reset', 'query'])
// 按钮配置
const operationBtnList = ref([
  {
    key: 'add',
    direction: 'left',
    label: '新增出账',
    click: handleAdd
  }, {
    key: 'import',
    direction: 'left',
    label: '导入出账',
    click: handleImport
  },
  {
    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 = (row) => {
  console.log('选中行:', row)
}


</script>

<style scoped></style>