<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>
       
    </template>
    <!-- 列表区域 -->
    <template #table>
     
      <!-- 应付款管理列表 -->
      <el-table 
        :data="tableData" 
        height="400" 
        border  
        highlight-current-row
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="commissionBizType" label="应付款类型" width="120" fixed="left" sortable  />
        <el-table-column prop="payableNo" label="应付款编号" width="120" />
        <el-table-column prop="policyNo" label="保单号" width="120" />
        <el-table-column prop="status" label="出账状态" width="120" sortable>
          <template #default="{ row }">
            <el-tag :type="row.status === '1' ? 'success' : 'warning'">
              {{ row.status === '1' ? '已入账' : '待入账' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fortunePeriod" label="出账期数" width="120" sortable />
        <el-table-column prop="fortuneTotalPeriod" label="出账总期数" width="120" sortable />
        <el-table-column prop="fortuneType" label="出账项目" width="120" sortable />
        <el-table-column prop="payoutDate" 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.expectedAmount) }}
          </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>
    <!-- 统计信息卡片 -->
      <div class="statistics-cards" 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>
      <!-- 出账记录表格弹窗-->
      <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, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatCurrency } from '@/utils/number'
import { expectedFortuneList, payRecordList } from '@/api/financial/commission'
// 分页相关
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 searchFormData = reactive({
  policyNo: '',
  incomeDateRange: [], // 改为数组格式
  statusList: [],
  fortuneName: [], // 修改字段名
  fortunePeriod: '',
  insurerBizId: [],
  productLaunchBizId: [],
  commissionBizType: '',
  teamBizId: '',
})

// 表格数据
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 = () => {
  // 重置搜索表单
  Object.keys(searchFormData).forEach(key => {
    if (Array.isArray(searchFormData[key])) {
      searchFormData[key] = []
    } else {
      searchFormData[key] = ''
    }
  })
  ElMessage.success('搜索条件已重置')
  // 重新加载数据
  loadTableData()
}

const handleQuery = async () => {
  loadTableData()
}

// 按钮配置
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 () => {
  loading.value = true
  try {
    const params = {
      // ...searchFormData,
      // payoutDateStart: searchFormData.incomeDateRange[0],
      // payoutDateEnd: searchFormData.incomeDateRange[1],
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
    const response = await expectedFortuneList(params)
    tableData.value = response.data.records
    pageTotal.value = response.data.total
    pageSize.value = response.data.size
    
    // 统计信息
     statisticsData.value = {
        totalExpectedAmount: response.data.expectedStatisticsVO.totalExpectedAmount,
        totalPaidAmount: response.data.expectedStatisticsVO.totalPaidAmount,
        totalUnpaidAmount: response.data.expectedStatisticsVO.totalUnpaidAmount,
        paidAmountRatio: response.data.expectedStatisticsVO.paidAmountRatio,
        totalPolicyCount: response.data.expectedStatisticsVO.totalPolicyCount,
        totalPremiumAmount: response.data.expectedStatisticsVO.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>