<template>
  <CommonPage
    :operationBtnList="operationBtnList"
    :showSearchForm="true"
    :show-pagination="true"
  >
    <!-- 搜索区域 -->
    <template #searchForm>
      <el-form 
        :model="searchFormData" 
        ref="searchFormRef" 
        label-position="top"
        class="search-form"
      >
        <el-row :gutter="20">
          <el-col 
            :xs="24" :sm="12" :md="8" :lg="6" :xl="6" 
            v-for="item in searchFormItems" 
            :key="item.value"
          >
            <el-form-item 
              :label="item.label" 
              :prop="item.value" 
              :rules="item.rules"
            >
              <template v-if="item.type === 'input'">
                <el-input 
                  v-model="searchFormData[item.value]" 
                  :placeholder="item.placeholder" 
                  size="large" 
                  clearable
                />
              </template>
              
              <template v-else-if="item.type === 'select'">
                <el-select 
                  v-model="searchFormData[item.value]" 
                  :placeholder="item.placeholder" 
                  size="large" 
                  clearable
                >
                  <el-option 
                    v-for="option in item.options" 
                    :key="option.value" 
                    :label="option.label" 
                    :value="option.value"
                  />
                </el-select>
              </template>
              
              <template v-else-if="item.type === 'daterange'">
                <el-date-picker
                  v-model="searchFormData[item.value]"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  size="large"
                  clearable
                  style="width: 100%"
                />
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    
    <!-- 列表区域 -->
    <template #table>
     
      <!-- 应收款管理列表 -->
      <el-table 
        :data="tableData" 
        height="260" 
        border  
        highlight-current-row
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="commissionBizType" label="应收款类型" width="120" fixed="left" />
        <el-table-column prop="receivableNo" label="应收款编号" width="120" />
        <el-table-column prop="policyNo" label="保单号" width="120" />
        <el-table-column prop="reconciliationCompany" label="对账公司" width="120" />
        <el-table-column prop="status" label="入账状态" width="100">
          <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="100" />
        <el-table-column prop="totalPeriod" label="入账总期数" width="100" />
        <el-table-column prop="commissionType" label="入账项目" width="100" />
        <el-table-column prop="commissionDate" label="入账日(估)" width="120" />
        <el-table-column prop="commissionRatio" label="入账比例(估)" width="120">
          <template #default="{ row }">
            {{ (row.commissionRatio || 0) + '%' }}
          </template>
        </el-table-column>
        <el-table-column prop="expectedAmount" label="入账金额(估)" width="120">
          <template #default="{ row }">
            {{ formatCurrency(row.expectedAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="paidRatio" label="已入账比例" width="120">
          <template #default="{ row }">
            {{ (row.paidRatio || 0) + '%' }}
          </template>
        </el-table-column>
        <el-table-column prop="paidAmount" label="已入账金额" width="120">
          <template #default="{ row }">
            {{ formatCurrency(row.paidAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="pendingRatio" label="待入账比例" width="120">
          <template #default="{ row }">
            {{ (row.pendingRatio || 0) + '%' }}
          </template>
        </el-table-column>
        <el-table-column prop="pendingAmount" label="待入账金额（估）" width="120">
          <template #default="{ row }">
            {{ formatCurrency(row.pendingAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="defaultExchangeRate" label="结算汇率（估）" width="120" />
        <el-table-column prop="insurerBizId" label="保险公司" width="120" />
        <el-table-column prop="productLaunchBizId" label="产品计划" width="120" />
        <el-table-column prop="premium" label="期交保费" width="120">
          <template #default="{ row }">
            {{ formatCurrency(row.premium) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="150" />
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleViewDetail(row)"
            >
              查看
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </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="6" :lg="6">
            <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="6" :lg="6">
            <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="6" :lg="6">
            <el-card shadow="hover" class="statistics-card">
              <div class="card-content">
                <div class="card-label">待入账金额</div>
                <div class="card-value">{{ formatCurrency(statisticsData.pendingAmount) }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6">
            <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="Receivables">
import CommonPage from '@/components/commonPage'
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatCurrency } from '@/utils/number'

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const loading = ref(false)



// 搜索表单数据
const searchFormData = reactive({
  policyNo: '',
  incomeDateRange: [''] ,
  incomeStatus: '',
  incomeTerm: '',
  incomeItem: '',
  outTeam: '',
  insurer: '',
  productPlan: '',
  paymentType: '',
  intermediary: '',
  signer: ''
})

// 搜索表单项配置
const searchFormItems = ref([
  {
    label: '保单号',
    value: 'policyNo',
    type: 'input',
    placeholder: '请输入保单号'
  },
  {
    label: '入账日（估）',
    value: 'incomeDateRange',
    type: 'daterange',
    placeholder: '请选择入账日（估）'
  },
  {
    label: '入账状态',
    value: 'incomeStatus',
    type: 'select',
    placeholder: '请选择入账状态',
    options: [
      { label: '全部', value: '' },
      { label: '已入账', value: '1' },
      { label: '待入账', value: '0' }
    ]
  },
  {
    label: '入账期数',
    value: 'incomeTerm',
    type: 'input',
    placeholder: '请输入入账期数'
  },
  {
    label: '入账项目',
    value: 'incomeItem',
    type: 'select',
    placeholder: '请选择入账项目',
    options: [
      { label: '全部', value: '' },
      { label: '佣金', value: '1' },
      { label: '服务费', value: '2' }
    ]
  },
  {
    label: '出单团队',
    value: 'outTeam',
    type: 'select',
    placeholder: '请选择出单团队',
    options: [
      { label: '全部', value: '' },
      { label: '团队A', value: '1' },
      { label: '团队B', value: '2' }
    ]
  },
  {
    label: '保险公司',
    value: 'insurer',
    type: 'select',
    placeholder: '请选择保险公司',
    options: [
      { label: '全部', value: '' },
      { label: '保险公司A', value: '1' },
      { label: '保险公司B', value: '2' }
    ]
  },
  {
    label: '产品计划',
    value: 'productPlan',
    type: 'select',
    placeholder: '请选择产品计划',
    options: [
      { label: '全部', value: '' },
      { label: '计划A', value: '1' },
      { label: '计划B', value: '2' }
    ]
  },
  {
    label: '应收款类型',
    value: 'paymentType',
    type: 'select',
    placeholder: '请选择应收款类型',
    options: [
      { label: '全部', value: '' },
      { label: '关联保单应收单', value: '1' },
      { label: '非关联保单应收单', value: '2' }
    ]
  },
  { 
    label: '转介人',
    value: 'intermediary',
    type: 'select',
    placeholder: '请选择转介人',
    options: [
      { label: '全部', value: '' },
      { label: '转介人A', value: '1' },
      { label: '转介人B', value: '2' }
    ]
  },
  {
    label: '签单员',
    value: 'signer',
    type: 'select',
    placeholder: '请选择签单员',
    options: [
      { label: '全部', value: '' },
      { label: '签单员A', value: '1' },
      { label: '签单员B', value: '2' }
    ]
  }
])

// 表格数据
const tableData = ref([
  // 示例数据
  {
    id: 1,
    commissionBizType: '佣金',
    receivableNo: 'YSK001',
    policyNo: 'POL001',
    reconciliationCompany: '对账公司A',
    status: '1',
    commissionPeriod: 1,
    totalPeriod: 12,
    commissionType: '首期佣金',
    commissionDate: '2024-01-15',
    commissionRatio: 8.5,
    expectedAmount: 8500,
    paidRatio: 100,
    paidAmount: 8500,
    pendingRatio: 0,
    pendingAmount: 0,
    defaultExchangeRate: 1.0,
    insurerBizId: '保险公司A',
    productLaunchBizId: '计划A',
    premium: 100000,
    remark: '备注信息'
  },
  {
    id: 2,
    commissionBizType: '服务费',
    receivableNo: 'YSK002',
    policyNo: 'POL002',
    reconciliationCompany: '对账公司B',
    status: '0',
    commissionPeriod: 2,
    totalPeriod: 12,
    commissionType: '服务费',
    commissionDate: '2024-02-15',
    commissionRatio: 5.0,
    expectedAmount: 5000,
    paidRatio: 50,
    paidAmount: 2500,
    pendingRatio: 50,
    pendingAmount: 2500,
    defaultExchangeRate: 1.0,
    insurerBizId: '保险公司B',
    productLaunchBizId: '计划B',
    premium: 50000,
    remark: ''
  }
])

// 统计信息
const statisticsData = ref({
  totalAmount: 13500,
  totalPaidAmount: 11000,
  pendingAmount: 2500,
  paidRatio: 81.48, // (11000/13500*100)
  totalPolicyCount: 2
})



// 按钮事件处理
const handleAdd = () => {
  ElMessage.info('点击新增按钮')
  // 这里可以打开新增弹窗
  // proxy.$refs.addForm.resetFields()
}

const handleImport = () => {
  ElMessage.info('点击导入按钮')
  // 这里可以打开导入弹窗
  // proxy.$refs.importForm.resetFields()
}

const handleExport = () => {
  ElMessage.info('点击导出按钮')
  // 这里可以执行导出逻辑
  // proxy.$refs.exportForm.resetFields()
}

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 handleViewDetail = (row) => {
  ElMessage.info(`查看应收款详情：${row.receivableNo}`)
  // 这里可以打开详情弹窗或跳转到详情页
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除应收款 "${row.receivableNo}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 执行删除操作
    tableData.value = tableData.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
    
    // 重新计算统计信息
    calculateStatistics()
  } catch {
    // 用户取消了操作
  }
}

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  loadTableData()
}

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

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 这里应该调用真实的API接口
    // const params = {
    //   ...searchFormData,
    //   currentPage: currentPage.value,
    //   pageSize: pageSize.value
    // }
    // const response = await api.getReceivablesList(params)
    // tableData.value = response.data.list
    // pageTotal.value = response.data.total
    
    // 计算统计信息
    calculateStatistics()
    
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 计算统计信息
const calculateStatistics = () => {
  const data = tableData.value
  const totalAmount = data.reduce((sum, item) => sum + (item.expectedAmount || 0), 0)
  const totalPaidAmount = data.reduce((sum, item) => sum + (item.paidAmount || 0), 0)
  const pendingAmount = totalAmount - totalPaidAmount
  const paidRatio = totalAmount > 0 ? (totalPaidAmount / totalAmount * 100) : 0
  
  statisticsData.value = {
    totalAmount,
    totalPaidAmount,
    pendingAmount,
    paidRatio: Number(paidRatio.toFixed(2)),
    totalPolicyCount: data.length
  }
}

// 监听搜索条件变化（可选：自动查询）
watch(
  () => searchFormData,
  () => {
    // 如果需要自动查询，可以在这里调用
    // debounce(() => loadTableData(), 500)
  },
  { deep: true }
)

// 初始化加载数据
onMounted(() => {
  loadTableData()
  calculateStatistics()
})
</script>

<style scoped lang="scss">

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 15px 0;
  border-top: 1px solid var(--el-border-color-lighter);
}

.statistics-cards {
  margin-top: 20px;
}

.statistics-card {
  margin-bottom: 15px;
  .card-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    .card-label {
      color: var(--el-text-color-secondary);
      margin-bottom: 8px;
    }
    .card-value {
      font-size: 24px;
      font-weight: 600;
      color: var(--el-color-primary);
    }
  }
}

// 响应式调整
@media (max-width: 768px) {
  
  .statistics-cards {
    .el-col {
      margin-bottom: 15px;
    }
  }
}
</style>