<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.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">总保费（HKD）</div>
                  <div class="card-value">{{ formatCurrency(statisticsData.totalPremium) }}</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.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.totalCompareCommissionCount }}</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.successCompareCommissionCount }}</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.failedCompareCommissionCount }}</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.expectePaidAmount) }}</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.differenceAmount) }}</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        <el-table :data="tableData" ref="multipleTableRef" height="400" row-key="id" border highlight-current-row
          style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="40" />
          <el-table-column prop="reconciliationYearMonth" label="检核年月" width="120" sortable />
          <el-table-column prop="policyNo" label="保单号" width="120" sortable />
          <el-table-column prop="reconciliationCompany" label="对账公司" width="120" sortable />
          <el-table-column prop="commissionDate" label="入账日" width="120" sortable />
          <el-table-column prop="status" label="入账状态" width="120" sortable :formatter="formatStatus" />
          <el-table-column prop="currentCommissionRatio" label="本次入账比例" width="130" sortable />
          <el-table-column prop="periodPaidRatio" label="累积入账比例" width="130" sortable />
          <el-table-column prop="periodPendingRatio" label="待入账比例" width="120" sortable />
          <el-table-column prop="paidAmount" label="本次入账金额" width="130" sortable />
          <el-table-column prop="currency" label="入账币种" width="120" sortable />
          <el-table-column prop="exchangeRate" 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 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>
        <!-- 表格操作菜单 -->
        <div class="tableOptionContainer">
          <el-button type="primary" :icon="Select" :disabled="updatePayRollStatusDisable"
            @click="generateCommissionRecordapi">生成可出账记录</el-button>
        </div>
      </template>
    </CommonPage>
    <!-- 开始检核弹窗-->
    <CommonDialog dialogTitle='开始检核' dialogWidth='80%' :openDialog=dialogFlag :showAction='false' :showClose='true'
      @close='dialogFlag = false'>
      <el-row>
        <el-col :xs="24" :sm="24" :md="24" :lg="24">
          <SearchForm ref="checkFormRef" :config="checkConfig" />
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :xs="24" :sm="12" :md="3" :lg="3">
          <el-button type="primary" :icon="Plus" :disabled="!checkFormRef?.getFormData().reconciliationYearMonth"
            @click="addCheckRecordDialogFlag = true; searchParams = checkFormRef.getFormData()">新增</el-button>
        </el-col>
        <el-col :xs="24" :sm="24" :md="3" :lg="3">
          <el-button type="primary" :icon="Upload" :disabled="!checkFormRef?.getFormData().reconciliationYearMonth"
            @click="fileUploadDialogFlag = true; searchParams = checkFormRef.getFormData()">导入</el-button>
        </el-col>
        <el-col :xs="24" :sm="24" :md="3" :lg="3">
          <el-button link type="primary">下载导入模板 </el-button>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="24" :lg="24">
          <el-table :data="checkRecordTableData" style="width: 100%">
            <el-table-column prop="commissionBizType" label="应收款类型" width="120" />
            <el-table-column prop="receivableNo" label="应收款编号" width="120" />
            <el-table-column prop="policyNo" label="关联保单号" width="120" />
            <el-table-column prop="status" label="比对状态" width="120" />
            <el-table-column prop="commissionPeriod" label="佣金期数" width="120" />
            <el-table-column prop="totalPeriod" label="总期数" width="120" />
            <el-table-column prop="commissionDate" label="入账日（实）" width="120" />
            <el-table-column prop="amount" label="入账金额" width="120" />
            <el-table-column prop="currency" label="入账币种" width="120" />
            <el-table-column prop="commissionName" label="入账项目" width="120" />
            <el-table-column prop="reconciliationCompany" label="对账公司" width="120" />
            <!-- <el-table-column prop="zip" label="入账状态" width="120" /> -->
            <el-table-column fixed="right" label="操作" min-width="120">
              <template #default>
                <el-button link type="primary" size="small" @click="checkRecordEdit(row)">
                  修改
                </el-button>
                <el-button link type="primary" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>


    </CommonDialog>
    <!-- 新增检核记录弹窗 -->
    <CommonDialog dialogTitle='新增检核记录' dialogWidth='80%' :openDialog=addCheckRecordDialogFlag :showAction='true'
      :showClose='true' @close='addCheckRecordDialogFlag = false' @confirm='handleAddCheckRecord()'>
      <el-row>
        <el-col :xs="24" :sm="24" :md="24" :lg="24">
          <SearchForm ref="addCheckRecordFormRef" :config="addCheckRecordConfig" />
        </el-col>
      </el-row>
    </CommonDialog>

    <CommonDialog dialogTitle='文件导入' dialogWidth='80%' :openDialog=fileUploadDialogFlag :showAction='true'
      :showClose='true' @close='fileUploadDialogFlag = false; files = ""'>
      <FileUpload v-model="files" :data="{ headerRow: 0 }" :file-type="['xlsx', 'xls']" :action="'/oss/api/excel/import'"
        :limit="1" :fileSize="15" />
    </CommonDialog>

    <!-- 设置比对状态 -->
    <CommonDialog dialogTitle='设置比对状态' dialogWidth='80%' :openDialog=setCompareStatusDialogFlag :showAction='true'
      :showClose='true' @close='setCompareStatusDialogFlag = false;'>
      <SearchForm ref="setCompareStatusFormRef" :config="setCompareStatusConfig" />
    </CommonDialog>


    <!-- 更新数据 -->

    <CommonDialog dialogTitle='更新数据' dialogWidth='80%' :openDialog=updateDataDialogFlag :showAction='true'
      :showClose='true' @close='updateDataDialogFlag = false;'>

    </CommonDialog>

    <!-- 查看记录 -->
    <CommonDialog dialogTitle='查看记录' dialogWidth='80%' :openDialog=viewRecordDialogFlag :showAction='true'
      :showClose='true' @close='viewRecordDialogFlag = false;'>

    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } 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 { getPolicyCommissionList, generateCommissionRecord, addPayrollCheckRecord, commissionExpectedRecord } from '@/api/financial/commission'
import { Plus, Upload, Select } from '@element-plus/icons-vue'
import FileUpload from '@/components/FileUpload/index.vue'
import { loadDicts, getDictLabel } from '@/utils/useDict'
const files = ref('')
// 分页相关
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: 'statusList',
    label: '比对状态',
    multiple: true,
    dictType: 'csf_commission_status'
  }, {
    type: 'select',
    prop: 'reconciliationCompanyBizIdList',
    label: '对账公司',
    api: '/insurance/base/api/insuranceReconciliationCompany/page',
    keywordField: 'name',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入对账公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
        multiple: true,
    valueKey: 'reconciliationCompanyBizId',
    labelKey: 'name',
    transform: (res) => {
      console.log(res)
      return res?.data.records || []
    }
  }, {
    type: 'date',
    prop: 'expectedDate',
    label: '入账日（估）',
    placeholder: '请选择'
  }, {
    type: 'daterange',
    prop: 'commissionDate',
    label: '入账日（实）',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间'
  }, {
    type: 'select',
    prop: 'insuranceCompanyBizIdList',
    label: '保险公司',
    api: '/insurance/base/api/insuranceCompany/page',
    keywordField: 'queryContent',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入保险公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    multiple: true,
    valueKey: 'insuranceCompanyBizId',
    labelKey: 'abbreviation',
    transform: (res) => {
      console.log(res)
      return res?.data.records || []
    }
  }, {
    type: 'date',
    prop: 'reconciliationYearMonth',
    label: '检核年月',
    placeholder: '检核年月',
    format: 'YYYY-MM',
    valueFormat: 'YYYY-MM'
  }
])

// 设置比对状态
const setCompareStatusDialogFlag = ref(false)
const setCompareStatusConfig = ref([
  {
    type: 'select',
    prop: 'status',
    label: '比对状态',
    dictType: 'csf_commission_status'
  }
])
const setCompareStatusFormRef = ref(null)

// 更新数据
const updateDataDialogFlag = ref(false)
// 查看记录
const viewRecordDialogFlag = ref(false)



const fileUploadDialogFlag = ref(false)
const checkRecordTableData = ref([])
// 检核表单

const checkFormRef = ref(null)
const checkConfig = ref([
  {
    type: 'date',
    prop: 'reconciliationYearMonth',
    label: '检核年月',
    placeholder: '检核年月',
    format: 'YYYY-MM',
    valueFormat: 'YYYY-MM',
    rules: [{ required: true, message: '请选择检核年月', trigger: 'blur' }]
  }
])
const checkRecordEdit = (row) => {
  console.log(row)
}

// 生成可出账记录按钮
const updatePayRollStatusDisable = ref(true)
// 获取入账状态,字典值转化方法
onMounted(async () => {
  try {
    await loadDicts(['csf_expected_commission_status'])
  } catch (error) {
    console.error('字典加载失败', error)
  } finally {
    loading.value = false
  }
})
// 格式化函数（每次渲染都会调用，所以能拿到最新字典）
const formatStatus = (row, column) => {
  return getDictLabel('csf_expected_commission_status', row.status) // 实时查缓存
}
// 应收单类型
const commissionBizTypeOptions = [
  { value: 'R', label: '关联保单应收单' },
  { value: 'U', label: '非关联保单应收单' }
]
// 应收单类型通过value转成label
const getCommissionBizTypeLabel = (value) => {
  const item = commissionBizTypeOptions.find(item => item.value === value)
  return item?.label || ''
}

// 新增检核记录表单
const addCheckRecordFormRef = ref(null)
const addCheckRecordConfig = ref([
  {
    type: 'select',
    prop: 'commissionBizType',
    label: '应收单类型',
    placeholder: '应收单类型',
    options: commissionBizTypeOptions
  },
  {
    type: 'input',
    prop: 'policyNo',
    label: '保单号'
  },
  {
    type: 'input',
    prop: 'commissionPeriod',
    label: '佣金期数',
    inputType: 'decimal',
    rules: [
      { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }
    ]
  }, {
    type: 'input',
    prop: 'totalPeriod',
    label: '总期数',
    inputType: 'decimal',
    rules: [
      { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }
    ]
  }, {
    type: 'date',
    prop: 'commissionDate',
    label: '入账日（实）',
    placeholder: '请选择'
  }, {
    type: 'input',
    prop: 'amount',
    label: '入账金额',
    inputType: 'decimal',
    rules: [
      { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }
    ]
  }, {
    type: 'select',
    prop: 'currency',
    label: '入账币种',
    dictType: 'bx_currency_type'
  }, {
    type: 'select',
    prop: 'commissionName',
    label: '入账项目',
    dictType: 'csf_commission_type'
  }, {
    type: 'select',
    prop: 'reconciliationCompanyBizIdList',
    label: '对账公司',
    api: '/insurance/base/api/insuranceReconciliationCompany/page',
    keywordField: 'name',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入对账公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    multiple: true,
    valueKey: 'reconciliationCompanyBizId',
    labelKey: 'name',
    transform: (res) => {
      console.log(res)
      return res?.data.records || []
    }
  }
])
const addCheckRecordDialogFlag = ref(false)
const handleAddCheckRecord = async () => {
  try {
    const addCheckSearchParams = addCheckRecordFormRef.value.getFormData()
    const params = {
      ...addCheckSearchParams,
      reconciliationYearMonth: searchParams.value.reconciliationYearMonth
    }
    await addPayrollCheckRecord([params])
    ElMessage.success('新增检核记录成功')
    addCheckRecordDialogFlag.value = false
    checkRecordTableData.value = []
    checkRecordQuery()
  } catch (error) {
    console.error('新增检核记录失败', error)
    ElMessage.error('新增检核记录失败')
  }
}
// 生成可出账记录
const generateCommissionRecordapi = async () => {
  try {
    const res = await generateCommissionRecord({
      commissionBizIdList: multipleSelection.value.map(item => item.commissionBizId)
    })
    if (res.code === 200) {
      ElMessage.success('生成可出账记录成功')
    } else {
      ElMessage.error(res.msg || '生成可出账记录失败')
    }
  } catch (error) {
    console.error('生成可出账记录失败', error)
    ElMessage.error('生成可出账记录失败')
  }
 
}
// 表格操作菜单
const dropdownItems = [
  { label: '设置比对状态', value: 'setStatus' },
  { label: '更新数据', value: 'editRecord' },
  { label: '查看记录', value: 'viewRecord' }
]

// 统计信息
const statisticsData = ref({})
// 弹窗相关
const dialogFlag = ref(false)

// 按钮事件处理
const handleAdd = () => {
  // 开始检核
  dialogFlag.value = true
}

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 checkRecordQuery = async () => {
  try {
    const params = {
      reconciliationYearMonth: searchParams.value.reconciliationYearMonth
    }
    const res = await commissionExpectedRecord(params)
    checkRecordTableData.value = res.data.records || []
  } catch (error) {
    console.error('查询检核记录失败', error)
    ElMessage.error('查询检核记录失败')
  }

}

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  console.log('全选:', val)
  // 生成可出账记录按钮是否禁用
  updatePayRollStatusDisable.value = val.length === 0
}
const visibleDefaultButtons = ref(['add', 'reset', 'query'])
// 按钮配置
const operationBtnList = ref([
  {
    key: 'add',
    direction: 'left',
    label: '开始检核',
    click: handleAdd
  },
  // {
  //   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,
      commissionDateStart: searchParams.commissionDate?.[0] || undefined,
      commissionDateEnd: searchParams.commissionDate?.[1] || undefined,
      commissionDate:undefined
    }
    const res = await getPolicyCommissionList(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.commissionStatisticsVO || {}
  } 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 = (e, row) => {
  console.log('选中行:', e, row)
  if (row === 'setStatus') {
    setCompareStatusDialogFlag.value = true
    return
  } else if (row === 'editRecord') {
    updateDataDialogFlag.value = true
    return
  } else if (row === 'viewRecord') {
    viewRecordDialogFlag.value = true
    return
  }
}


</script>

<style scoped>
.tableOptionContainer {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.el-row,
.el-col {
  margin-bottom: 5px;
}
</style>