<template>
  <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"
          v-model="searchFormData"
          :fields="searchFields"
          label-position="top" 
          :label-width="null"  
          :inline="false"       
          :gutter="20"       
          class="custom-search-form"
        />
    </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="commissionPeriod" label="出账期数" width="120" sortable />
        <el-table-column prop="totalPeriod" label="出账总期数" width="120" sortable />
        <el-table-column prop="commissionType" label="出账项目" width="120" sortable />
        <el-table-column prop="paymentDate" 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="expectedAmount" label="出账金额(估)" width="140" sortable>
          <template #default="{ row }">
            {{ formatCurrency(row.expectedAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="paidAmountRatio" label="已出账比例" width="120" sortable>
          <template #default="{ row }">
            {{ (row.paidAmountRatio || 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="pendingPaidAmount" label="待出账金额（估）" width="160" sortable>
          <template #default="{ row }">
            {{ formatCurrency(row.pendingPaidAmount) }}
          </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>
    </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>
</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 } from '@/api/financial/commission'
import SearchForm from '@/components/SearchForm/index.vue'
import { searchCompanies, searchCommissionTypes } from '@/api/search'
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const loading = ref(false)


// 搜索表单数据 - 修正字段名
const searchFormData = reactive({
  policyNo: '',
  incomeDateRange: [], // 改为数组格式
  statusList: [],
  fortuneName: [], // 修改字段名
  fortunePeriod: '',
  insurerBizId: [],
  productLaunchBizId: [],
  commissionBizType: '',
  teamBizId: '',
})

const searchFields = ref([
  {
    type: 'input',
    field: 'policyNo',
    label: '保单号',
    placeholder: '请输入保单号',
    colSpan: 6, 
    clearable: true,
    rules: [
      { max: 50, message: '保单号长度不能超过50个字符', trigger: 'blur' }
    ]
  },
  {
    type: 'daterange',
    field: 'incomeDateRange',
    label: '入账日期',
    startPlaceholder: '开始日期',
    endPlaceholder: '结束日期',
    colSpan: 6,
    dateFormat: 'YYYY-MM-DD',
    props: {
      valueFormat: 'YYYY-MM-DD',
      style: 'width: 100%'
    }
  },
  {
    type: 'multi-select',
    field: 'statusList',
    label: '入账状态',
    placeholder: '请选择入账状态',
    colSpan: 6,
    options: [
      { label: '已入账', value: '1' },
      { label: '待入账', value: '0' },
      { label: '部分入账', value: '2' }
    ]
  },
  {
    type: 'remote-multi-select',
    field: 'commissionNameList',
    label: '入账项目',
    placeholder: '请输入关键词搜索',
    colSpan: 6,
    remoteConfig: {
      type: 'commissionType',
      apiMethod: searchCommissionTypes,
      formatResult: (data) => data.map(item => ({
        label: item.typeName,
        value: item.typeCode,
        remark: item.remark
      })),
      defaultOptions: [
        { label: '佣金', value: 'COMMISSION' },
        { label: '服务费', value: 'SERVICE_FEE' }
      ]
    }
  },
  {
    type: 'remote-multi-select',
    field: 'reconciliationCompanyList',
    label: '对账公司',
    placeholder: '请输入关键词搜索',
    colSpan: 6,
    remoteConfig: {
      type: 'company',
      apiMethod: (params) => searchCompanies({ ...params, type: 'reconciliation' }),
      defaultOptions: []
    }
  },
  {
    type: 'input',
    field: 'commissionPeriod',
    label: '入账期数',
    placeholder: '请输入期数',
    colSpan: 6,
  },
  {
    type: 'remote-multi-select',
    field: 'insurerBizId',
    label: '保险公司',
    placeholder: '请输入关键词搜索保险公司',
    colSpan: 6,
    remoteConfig: {
      type: 'insurer',
      apiMethod: (params) => searchCompanies({ ...params, type: 'insurer' }),
      defaultOptions: []
    }
  },
  {
    type: 'remote-multi-select',
    field: 'productLaunchBizId',
    label: '产品计划',
    placeholder: '请输入关键词搜索产品计划',
    colSpan: 6,
    remoteConfig: {
      type: 'product',
      apiMethod: (params) => searchCompanies({ ...params, type: 'product' }),
      defaultOptions: []
    }
  },
  {
    type: 'select',
    field: 'commissionBizType',
    label: '应收款类型',
    placeholder: '请选择应收款类型',
    colSpan: 6,
    options: [
      { label: '全部', value: '' },
      { label: '关联保单应收单', value: '1' },
      { label: '非关联保单应收单', value: '2' }
    ]
  },
  {
    type: 'remote-multi-select',
    field: 'teamBizId',
    label: '出单团队',
    placeholder: '请输入关键词搜索出单团队',
    colSpan: 6,
    remoteConfig: {
      type: 'team',
      apiMethod: (params) => searchCompanies({ ...params, type: 'team' }),
      defaultOptions: []
    }
  }
])

// 表格数据
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 () => {
  // 表单验证
  // const valid = await proxy.$refs.searchFormRef.validate()
  // if (!valid) return
  
  ElMessage.info('执行查询操作')
  loadTableData()
}
// 控制要显示的默认按钮
// const visibleDefaultButtons = ref(['add', 'import', 'export']) // 只显示新增和查询两个默认按钮
// 按钮配置
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,
      currentPage: 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.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
  }
}



// 初始化加载数据
onMounted(() => {
  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>