<template>
  <div>
    <CommonPage :operationBtnList="operationBtnList" :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">{{ formatCurrency(statisticsData.totalAmount) }}</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.totalPaidAmount) }}</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.pendingPaidAmount) }}</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.paidAmountRatio }}</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.totalPolicyCount }}</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.totalPolicyCount }}</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="fortuneBizType" label="应付款类型" width="120" fixed="left" sortable>
            <template #default="{ row }">
              {{ getFortuneBizTypeLabel(row.fortuneBizType) }}
            </template>
          </el-table-column>
          <el-table-column prop="payableNo" label="应付款编号" width="120" sortable/>
          <el-table-column prop="policyNo" label="保单号" width="120" sortable/>
          <el-table-column prop="status" label="出账状态" width="120" sortable>
            <template #default="{ row }">
              {{ getDictLabel('csf_expected_fortune_status', row.status) }}
            </template>
          </el-table-column>
          <el-table-column prop="currency" label="出账币种" width="120" sortable />
          <el-table-column prop="fortunePeriod" label="出账期数" width="120" sortable />
          <el-table-column prop="fortuneTotalPeriod" label="出账总期数" width="120" sortable />
          <el-table-column prop="fortuneName" label="出账项目" width="120" sortable />
          <el-table-column prop="payoutDate" label="出账日(估)" width="120" sortable />
          <el-table-column prop="actualPayoutDate" label="出账日(实)" width="120" sortable />
          <el-table-column prop="commissionRatio" label="出账比例(估)" width="140" sortable>
            <template #default="{ row }">
              {{ (row.commissionRatio || 0) + '%' }}
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="出账金额(估)" width="140" sortable>
            <template #default="{ row }">
              {{ formatCurrency(row.amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="paidRatio" label="已出账比例" width="120" sortable>
            <template #default="{ row }">
              {{ (row.paidRatio || 0) + '%' }}
            </template>
          </el-table-column>
          <el-table-column prop="paidAmount" label="已出账金额" width="120" sortable>
            <template #default="{ row }">
              {{ formatCurrency(row.paidAmount) }}
            </template>
          </el-table-column>
          <el-table-column prop="pendingRatio" label="待出账比例" width="120" sortable>
            <template #default="{ row }">
              {{ (row.pendingRatio || 0) + '%' }}
            </template>
          </el-table-column>
          <el-table-column prop="unpaidAmount" label="待出账金额（估）" width="160" sortable>
            <template #default="{ row }">
              {{ formatCurrency(row.unpaidAmount) }}
            </template>
          </el-table-column>
          <el-table-column prop="insurerBizId" label="保险公司" width="120" sortable />
          <el-table-column prop="productLaunchBizId" label="产品计划" width="120" sortable />
          <el-table-column prop="premium" label="期交保费" width="120" sortable>
            <template #default="{ row }">
              {{ formatCurrency(row.premium) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="150" />
          <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="payRecordDialogTableVisible" :showAction="false"
      :showClose="true" @close="payRecordDialogTableVisible = false">
      <el-table :data="payRecordDialogTableData" border style="width: 100%">
        <el-table-column v-for="item in payRecordDialogTableColumns" :key="item.property" :property="item.property"
          :label="item.label" :width="item.width" />
      </el-table>
    </CommonDialog> -->
  </div>
</template>

<script setup name="Payables">
import CommonPage from '@/components/commonPage'
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatCurrency } from '@/utils/number'
import { expectedFortuneList, payRecordList } from '@/api/financial/commission'
import SearchForm from '@/components/SearchForm/SearchForm.vue'

import {getDictLabel} from '@/utils/useDict';
// 应收单类型
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 searchFormRef = ref(null)
const searchParams = ref({})
const searchConfig = ref([
  {
    type: 'input',
    prop: 'policyNo',
    label: '保单号'
  },
  {
    type: 'daterange',
    prop: 'payoutDate',
    label: '出账日（估）',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间'
  },
  {
    type: 'select',
    prop: 'statusList',
    label: '出账状态',
    multiple: true,
    dictType: 'csf_expected_fortune_status'
  },
  {
    type: 'input',
    prop: 'fortunePeriod',
    label: '出账期数',
    inputType: 'decimal',
    rules: [
      { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }
    ]
  },
  {
    type: 'select',
    prop: 'fortuneName',
    label: '出账项目',
    dictType: 'csf_fortune_type'
  },
  {
    type: 'select',
    prop: 'insurerBizId',
    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: 'productLaunchBizId',
    label: '产品计划',
    api: '/product/api/relProjectProductLaunch/parameter/page',
    keywordField: 'productName',
    requestParams: { 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: 'select',
    prop: 'fortuneBizType',
    label: '应付单类型',
    options: [
      { value: 'R', label: '关联保单应付单' },
      { value: 'U', label: '非关联保单应付单' }
    ]
  }, {
    type: 'select',
    prop: 'teamBizId',
    label: '出单团队',
    api: '/csf/api/team/page',
    keywordField: 'teamName',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入出单团队名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'teamBizId',
    labelKey: 'teamName',
    transform: (res) => {
      return res?.data.records || []
    }
  },
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const loading = ref(false)
// 表格操作菜单
const dropdownItems = [
  { label: '出账记录', value: 'payRecord' },
  { label: '设置状态', value: 'setStatus' }
]

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

// 统计信息
const statisticsData = ref({
  totalExpectedAmount: 0,
  totalPaidAmount: 0,
  totalUnpaidAmount: 0,
  paidAmountRatio: 0,
  totalPolicyCount: 0,
  totalPremiumAmount: 0
})

// 按钮事件处理
const handleAdd = () => {
  ElMessage.info('点击新增按钮')
}

const handleImport = () => {
  ElMessage.info('点击导入按钮')
}

const handleExport = () => {
  ElMessage.info('点击导出按钮')
}

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

const handleQuery = async () => {
  const params = searchFormRef.value.getSearchParams()
  console.log('父组件发起查询:', params)
  loadTableData(params)
}

// 按钮配置
const operationBtnList = ref([
  {
    key: 'add',
    direction: 'left',
    click: handleAdd
  },
  {
    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
  loadTableData()
}

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

// 加载表格数据
const loadTableData = async (searchParams = {}) => {
  console.log(searchFormRef.value)
  loading.value = true
  try {
    const params = {
      ...searchParams,
      payoutDateStart: searchParams.payoutDate?.[0] || undefined,
      payoutDateEnd: searchParams.payoutDate?.[1] || undefined,
      payoutDate: undefined,
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
    const response = await expectedFortuneList(params)
    tableData.value = response.data.page.records
    pageTotal.value = response.data.page.total
    pageSize.value = response.data.page.size

    // 统计信息
    statisticsData.value = {
      totalExpectedAmount: response.data.statisticsVO.totalExpectedAmount,
      totalPaidAmount: response.data.statisticsVO.totalPaidAmount,
      totalUnpaidAmount: response.data.statisticsVO.totalUnpaidAmount,
      paidAmountRatio: response.data.statisticsVO.paidAmountRatio,
      totalPolicyCount: response.data.statisticsVO.totalPolicyCount,
      totalPremiumAmount: response.data.statisticsVO.totalPremiumAmount
    }

  } catch (error) {
    console.error('加载数据失败:', error)
    // ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 出账记录查询
const loadPayRecordTableData = async () => {
  loading.value = true
  try {
    const params = {

    }
    const response = await payRecordList(params)
    payRecordDialogTableData.value = response.data.records
    pageTotal.value = response.data.total
    pageSize.value = response.data.size

  } catch (error) {
    console.error('加载数据失败:', error)
    // ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}



loadTableData()
</script>

<style scoped lang="scss">
.page-search-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

.search-actions {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}
</style>