<template>
  <div>
    <CommonPage :operationBtnList='operationBtnList' :visibleDefaultButtons="visibleDefaultButtons" v-loading.fullscreen.lock="statusLoading"
      :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_new', 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="issueNumber" 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" :policyBizId="selectedRow.policyBizId" :mode="mode"
        ref="policyDetailFormRef" @submit="onSubmit" @cancel="viewDetailDialogFlag = false"
        v-if="viewDetailDialogFlag" />
    </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,
  saveMailingInfo, updatePolicyfollow, batchSaveBrokers, saveInitialPayment,updatePolicyProduct
} from '@/api/sign/underwritingMain'
import {copyToClipboard} from '@/utils/copyToClipboard'
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 statusLoading = 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_new'
  }, 
  {
    type: 'date',
    prop: 'effectiveDate',
    label: '保单生效日',
  }, {
    type: 'date',
    prop: 'underwritingDate',
    label: '保单核保日',
  },
])
// 查看关联记录
const viewRelatedDialogFlag = ref(false)
const relateRecordTableData = ref([])
const viewRelatedDetail = (row) => {
  ElMessage.info(`查看关联记录详情：${JSON.stringify(row)}`)
}
// 提交修改状态
const handleEditStatusSubmit = async () => {
  statusLoading.value = true;
  try {
    await editStatusFormRef.value.validate()
    const res = await changePolicyStatus({
      policyBizId: selectedRow.value.policyBizId,
      ...editStatusFormData.value
    })
    if (res.code === 200) {
      statusLoading.value = false;
      ElMessage.success('修改状态成功')
      editStatusDialogFlag.value = false
      loadTableData()
    } else {
       statusLoading.value = false;
      ElMessage.error(res.msg || '修改状态失败')
    }
  } catch (error) {
     statusLoading.value = false;
    console.error('修改状态失败', error)
  }
}

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

const onSubmit = async (data) => {
  console.log('提交的数据:', data)
  // 调用 API 保存
  // alert('提交成功！')
  let params = {}
  if (data.activeTab === 'postal') {
    params = {
      policyBizId: selectedRow.value.policyBizId,
      ...data,
      activeTab: undefined
    }
    const res = await saveMailingInfo(params)
    if (res.code === 200) {
      ElMessage.success('保存邮寄信息成功')
    } else {
      ElMessage.error(res.msg || '保存邮寄信息失败')
    }
  } else if (data.activeTab === 'basic') {
    params = {
      policyBizId: selectedRow.value.policyBizId,
      ...data,
      activeTab: undefined
    }
    const res = await updatePolicyfollow(params)
    if (res.code === 200) {
      ElMessage.success(data.activeTab === 'basic' ? '保存基本信息成功' : '保存产品计划成功')
       loadTableData()
      // viewDetailDialogFlag.value = false
    } else {
      ElMessage.error(res.msg || (data.activeTab === 'basic' ? '保存基本信息失败' : '保存产品计划失败'))
    }
  } else if (data.activeTab === 'productPlan') {
    params = {
      policyBizId: selectedRow.value.policyBizId,
      ...data,
      activeTab: undefined
    }
    const res = await updatePolicyProduct(params)
    if (res.code === 200) {
      ElMessage.success('保存产品计划成功')
       loadTableData()
      // viewDetailDialogFlag.value = false
    } else {
      ElMessage.error(res.msg || ('保存产品计划失败'))
    }
  } else if (data.activeTab === 'introducer') {
    params = {
      policyBizId: selectedRow.value.policyBizId,
      brokerList: normalizeIntroducerData(data),
      activeTab: undefined
    }
    const res = await batchSaveBrokers(params)
    if (res.code === 200) {
      ElMessage.success('保存转介人成功')
      // viewDetailDialogFlag.value = false
    } else {
      ElMessage.error(res.msg || '保存转介人失败')
    }

  } else if (data.activeTab === 'attachment') {

  } else if (data.activeTab === 'firstPayment') {
    try {
      params = {
        policyBizId: selectedRow.value.policyBizId,
        ...data,
        activeTab: undefined
      }
      const res = await saveInitialPayment(params)
      if (res.code === 200) {
        ElMessage.success('保存首期缴费成功')
        // viewDetailDialogFlag.value = false
      } else {
        ElMessage.error(res.msg || '保存首期缴费失败')
      }
    } catch (error) {
      console.error('首期缴费表单验证失败', error)
      return
    }

  }

}

// 处理转介人数据格式
const normalizeIntroducerData = (data) => {
  if (Array.isArray(data)) return data
  if (data && typeof data === 'object') {
    const keys = Object.keys(data).filter(k => /^\d+$/.test(k))
    if (keys.length > 0) {
      return keys.sort((a, b) => a - b).map(k => data[k])
    }
  }
  return []
}
// 获取新单状态,字典值转化方法
onMounted(async () => {
  try {
    await loadDicts(['csf_policy_follow_status_new'])
    loadTableData()
  } 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_new'
  },
  {
    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: 'fullName',
    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 }
  console.log('列表点击操作', e, selectedRow.value)
  mode.value = e
  switch (e) {
    case 'viewDetail':
      viewDetailDialogFlag.value = true
      break
    case 'updateData':
      if (selectedRow.value.status === '生效') {
        ElMessage.warning('非新单状态，不能更新数据')
        return
      }
      viewDetailDialogFlag.value = true
      break
    case 'setNewSingleStatus':
       if (selectedRow.value.status === '生效') {
        ElMessage.warning('保单已生效，不能更新新单状态')
        return
      }
      editStatusDialogFlag.value = true
      editStatusFormData.value = {
        status: row.status,
        effectiveDate:row.effectiveDate,
        underwritingDate:row.underwritingDate
      }
      break
    case 'viewRelated':
      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'
    )
    if (res.code === 200) {
      ElMessage.success('报告生成成功')
    }else{
      ElMessage.error(res.msg || '报告生成失败')
    }

    // 可以添加下载报告的逻辑
  } catch (error) {
    console.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 || '更新失败')
  }
}

// 保存邮寄信息
const saveMailingInfoapi = async () => {
  if (!basicInfoFormData.value.policyNo) {
    ElMessage.error('请先输入保单号')
    return
  }
  try {
    const params = {
      policyBizId: basicInfoFormData.value.policyBizId,
      mailingMethod: postalFormData.value.mailingMethod,
      deliveryNo: postalFormData.value.deliveryNo,
      brokerSignDate: postalFormData.value.brokerSignDate,
      customerSignDate: postalFormData.value.customerSignDate,
    }
    const res = await savePostalInfo(params)
    if (res.code === 200) {
      ElMessage.success('保存邮寄信息成功')
    } else {
      ElMessage.error(res.msg || '保存邮寄信息失败')
    }
  } catch (error) {
    console.error('保存邮寄信息失败', error)
  } finally {

  }


}





</script>

<style scoped></style>