<template>
  <div>
    <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>
        <el-table :data="tableData" height="400" border highlight-current-row style="width: 100%" v-loading="loading">
          <el-table-column prop="policyNo" label="保单号" width="120" fixed="left" sortable />
          <el-table-column prop="policyNo" label="新单状态" width="120" fixed="left" sortable />
          <el-table-column prop="appointmentNo" label="预约编号" width="150" fixed="left" sortable />
          <el-table-column prop="signDate" label="签单日" width="150" fixed="left" sortable />
          <el-table-column prop="policyBizId" label="最晚缴费日" width="150" fixed="left" sortable />
          <el-table-column prop="policyHolder" label="投保人" width="150" fixed="left" sortable />
          <el-table-column prop="policyNo" label="受保人" width="150" fixed="left" sortable />
          <el-table-column prop="insuranceCompany" label="保险公司" width="150" fixed="left" sortable />
          <el-table-column prop="productName" label="产品计划" width="150" fixed="left" sortable />
          <el-table-column prop="paymentNumber" label="缴费年期" width="150" fixed="left" sortable />
          <el-table-column fixed="right" label="操作" min-width="80">
            <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=dialogFlag :showAction='false' :showClose='true'
      @close='dialogFlag = false'>
      内容
    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import CommonPage from '@/components/commonPage'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import CommonDialog from '@/components/commonDialog'
import { loadDicts, getDictLabel } from '@/utils/useDict'
import useUserStore from '@/store/modules/user'
import { safeDownload } from '@/utils/safeDownload'
import {
  getPolicyFollowList,
  getExpectedCommissionList,
  changePolicyStatus,
  policyFollowReport
} from '@/api/sign/underwritingMain'
const userStore = useUserStore()
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const loading = ref(false)
// 搜索表单数据 
const searchFormData = reactive({})
const selectedRow = ref(null)
// 弹窗相关
const dialogFlag = ref(false)
// 获取新单状态,字典值转化方法
onMounted(async () => {
  try {
    await loadDicts(['csf_policy_follow_status'])
  } catch (error) {
    console.error('字典加载失败', error)
  } finally {
    loading.value = false
  }
})
// 按钮事件处理
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 () => {
  loadTableData()
}
const visibleDefaultButtons = ref(['reset', 'query'])
// 按钮配置
const operationBtnList = ref([
  {
    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 tableData = ref([])
const searchFormRef = ref(null)
const searchParams = ref({})
const searchConfig = ref([
  {
    type: 'input',
    prop: 'policyNo',
    label: '保单号'
  },
  {
    type: 'select',
    prop: 'status',
    label: '新单状态',
    dictType: 'csf_policy_follow_status'
  },
  {
    type: 'input',
    prop: 'appointmentNo',
    label: '预约编号'
  }, {
    type: 'daterange',
    prop: 'signDate',
    label: '签单日',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间'
  },
  {
    type: 'date',
    prop: 'latestPaymentDate',
    label: '最晚缴费日',
    placeholder: '请选择'
  },

  {
    type: 'select',
    prop: 'insuranceCompanyBizIdList',
    label: '保险公司',
    api: '/insurance/base/api/insuranceCompany/page',
    keywordField: 'queryContent',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入保险公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'insuranceCompanyBizId',
    labelKey: 'abbreviation',
    multiple: true,
    transform: (res) => {
      console.log(res)
      return res?.data.records || []
    }
  }, {
    type: 'select',
    prop: 'productLaunchBizIdList',
    label: '产品计划',
    api: '/product/api/relProjectProductLaunch/parameter/page',
    keywordField: 'productName',
    requestParams: {
      tenantBizId: userStore.projectInfo.tenantBizId || '',
      projectBizId: userStore.projectInfo.projectBizId || '', fieldBizId: 'field_olk1qZe81qHHKXbw', fieldValueBizId: 'field_value_uOfJH5ucA2YwJpbn', pageNo: 1, pageSize: 20
    },
    placeholder: '输入产品计划名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'productLaunchBizId',
    labelKey: 'productName',
    multiple: true,
    transform: (res) => {
      return res?.data.records || []
    }
  }, {
    type: 'input',
    prop: 'paymentTerm',
    label: '缴费年期',
    inputType: 'decimal',
    rules: [
      { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }
    ]
  }
])


const loadTableData = async () => {
  loading.value = true
  const searchParams = searchFormRef.value.getFormData() || {}
  try {
    const params = {
      ...searchParams.value,
      signDateStart: searchParams.value?.signDate[0] || undefined,
      signDateEnd: searchParams.value?.signDate[1] || undefined,
      signDate: undefined,
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
    const response = await getPolicyFollowList(params)
    tableData.value = response.data.records
    pageTotal.value = response.data.total
    pageSize.value = response.data.size
  } catch (error) {
    ElMessage.error(error.message || '查询失败')
  } finally {
    loading.value = false
  }
}


// 表格操作菜单
const dropdownItems = [
  { label: '查看详情', value: 'viewDetail' },
  { label: '更新数据', value: 'updateData' },
  { label: '设置新单状态', value: 'setNewSingleStatus' },
  { label: '查看关联', value: 'viewRelated' },
  { label: '生成签单报告', value: 'generateReport' },
  { label: '更新记录', value: 'updateRecord' },
]

const handleSelect = async (e, row) => {
  selectedRow.value = { ...row }
  console.log(e, row)
  switch (e) {
    case 'viewDetail':
      ElMessage.info('查看详情')
      break
    case 'updateData':
      ElMessage.info('更新数据')
      break
    case 'setNewSingleStatus':
      ElMessage.info('设置新单状态')
      break
    case 'viewRelated':
      ElMessage.info('查看关联')
      break
    case 'generateReport':
      ElMessage.info('生成签单报告')
      break
    case 'updateRecord':
      ElMessage.info('更新记录')
      break
    default:
      break
  }
}






</script>

<style scoped></style>