<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="500" border highlight-current-row style="width: 100%" v-loading="loading">
          <el-table-column prop="policyNo" label="保单号" width="200" sortable />
          <el-table-column prop="status" label="新单状态" width="120" sortable>
            <template #default="{ row }">
              {{ getDictLabel('csf_policy_follow_status', row.status) }}
            </template>
          </el-table-column>
          <el-table-column prop="appointmentNo" label="预约编号" width="200" sortable />
          <el-table-column prop="signDate" label="签单日" width="200" sortable />
          <el-table-column prop="latestPaymentDate" label="最晚缴费日" width="200" sortable />
          <el-table-column prop="policyHolder" label="投保人" width="150" sortable />
          <el-table-column prop="insured" label="受保人" width="150" sortable />
          <el-table-column prop="insuranceCompany" label="保险公司" width="200" sortable />
          <el-table-column prop="productName" label="产品计划" width="200" sortable />
          <el-table-column prop="paymentTerm" label="缴费年期" width="120" 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=editStatusDialogFlag :showAction='true'
      :showClose='true' @close='editStatusDialogFlag = false' @confirm='handleEditStatusSubmit'>
      <SearchForm ref="editStatusFormRef" :config="editStatusFormConfig" v-model="editStatusFormData" />
    </CommonDialog>

    <!-- 查看关联记录 -->
    <CommonDialog dialogTitle='查看关联记录' dialogWidth='80%' :openDialog=viewRelatedDialogFlag :showAction='false'
      :showClose='true' @close='viewRelatedDialogFlag = false'>
      <el-table :data="relateRecordTableData" style="width: 100%">
        <el-table-column fixed prop="followDate" label="流程编号" width="150" />
        <el-table-column prop="name" label="客户姓名" width="120" />
        <el-table-column prop="state" label="创建时间" width="120" sortable />
        <el-table-column fixed="right" label="操作" min-width="120">
          <template #default>
            <el-button link type="primary" size="small" @click="viewRelatedDetail(row)">
              查看
            </el-button>
            <el-button link type="danger" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </CommonDialog>

    <!-- 查看详情、更新数据 -->
    <CommonDialog :dialogTitle='mode === "viewDetail" ? "查看详情" : "更新数据"' dialogWidth='80%' :openDialog=viewDetailDialogFlag :showAction='false'
      :showClose='true' @close='viewDetailDialogFlag = false' @confirm='handleUpdateSubmit'>
      <PolicyDetail v-model="policyDetailFormData" ref="policyDetailFormRef" @submit="onSubmit" @cancel="showDialog = false"/>
    </CommonDialog>


  </div>
</template>

<script setup>
import { ref, reactive, computed, watch ,nextTick} 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'

import PolicyDetail from './policyDetail.vue'
const policyDetailFormRef = ref(null)
const policyDetailFormData = ref({})
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 editStatusDialogFlag = ref(false)
// 修改状态
const editStatusFormData = ref({})
const editStatusFormRef = ref(null)
const editStatusFormConfig = ref([
  {
    type: 'select',
    prop: 'status',
    label: '新单状态',
    dictType: 'csf_policy_follow_status'
  }, {
    type: 'date',
    prop: 'policyEffectiveDate',
    label: '保单生效日',
  }, {
    type: 'date',
    prop: 'policyInsureDate',
    label: '保单核保日',
  },
])
// 查看关联记录
const viewRelatedDialogFlag = ref(false)
const relateRecordTableData = ref([])
const viewRelatedDetail = (row) => {
  ElMessage.info(`查看关联记录详情：${JSON.stringify(row)}`)
}
// 提交修改状态
const handleEditStatusSubmit = async () => {
  try {
    await editStatusFormRef.value.validate()
    const res = await changePolicyStatus({
      policyBizId: selectedRow.value.policyBizId,
      ...editStatusFormData.value
    })
    if (res.code === 200) {
      ElMessage.success('修改状态成功')
      editStatusDialogFlag.value = false
      loadTableData()
    } else {
      ElMessage.error(res.msg || '修改状态失败')
    }
  } catch (error) {
    console.error('修改状态失败', error)
  }
}

// 查看详情、更新数据
const viewDetailDialogFlag = ref(false)

const onSubmit = (data) => {
  console.log('提交的数据:', data)
  // 调用 API 保存
  alert('提交成功！')
  viewDetailDialogFlag.value = false
}

const handleClose = () => {
  // 可选：清空数据
}
// 获取新单状态,字典值转化方法
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) => {
      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
  searchParams.value = searchFormRef.value.getFormData() || {}
  // console.log(searchParams.value)
  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: 'generateReport' },
  { label: '设置新单状态', value: 'setNewSingleStatus' },
  { label: '查看关联', value: 'viewRelated' },
  // { label: '查看记录', value: 'viewRecord' },
]
const mode = ref('viewDetail')

const handleSelect = async (e, row) => {
  selectedRow.value = { ...row }
  mode.value = e
  switch (e) {
    case 'viewDetail':
      // ElMessage.info('查看详情')
      viewDetailDialogFlag.value = true
        // 等待 DOM 更新完成
      await nextTick()
      if(policyDetailFormRef.value) {
        // 调用子组件详情查询接口
        const data = await policyDetailFormRef.value.getPolicyfollowDetail(row.policyBizId)
      }
      break
    case 'updateData':
      ElMessage.info('更新数据')
      break
    case 'setNewSingleStatus':
      // ElMessage.info('设置新单状态')
      editStatusDialogFlag.value = true
      editStatusFormData.value = {
        status: row.status
      }
      break
    case 'viewRelated':
      // ElMessage.info('查看关联')
      viewRelatedDialogFlag.value = true
      break
    case 'generateReport':
      generateReport(row)
      break
    case 'viewRecord':
      ElMessage.info('查看记录')
      break
    default:
      break
  }
}

const generateReport = async (row) => {
  if (!selectedRow.value) {
    ElMessage.warning('请选择要生成报告的新单')
    return
  }
  try {
    const response = await policyFollowReport(row.policyBizId)
    // 文件名设置为应收款导出_yyyy-MM-dd hh:mm:ss.xlsx,不需要-，用字符串
    const fileName = `签单报告_${new Date().toLocaleString().replace(/\//g, '').replace(/:/g, '').replace(/\s/g, '')}.pdf`
    await safeDownload(
      response,
      fileName,
      'application/pdf;charset=utf-8'
    )
    ElMessage.success('报告生成成功')
    // 可以添加下载报告的逻辑
  } catch (error) {
    ElMessage.error(error.message || '报告生成失败')
  }
}

const handleUpdateSubmit = async () => {
  if (!selectedRow.value) {
    ElMessage.warning('请选择要更新的新单')
    return
  }
  try {
    const response = await updatePolicyFollow(selectedRow.value)
    ElMessage.success('更新成功')
    // 刷新当前页数据
    loadTableData()
    // 关闭弹窗
    viewDetailDialogFlag.value = false
  } catch (error) {
    ElMessage.error(error.message || '更新失败')
  }
}







</script>

<style scoped></style>