<!-- components/FormPage.vue -->
<template>
  <div class="form-page">
    <el-form ref="formRef" :model="localData" label-width="120px" size="default">
      <!-- 完整Tab列表 -->
      <el-tabs 
        ref="tabsRef"
        v-model="activeTab" 
        @tab-click="handleTabClick" 
        :before-leave="handleBeforeLeave"
        class="appointmentTabPaneBox"
      >
        <el-tab-pane label="基础信息"         name="basic"></el-tab-pane>
        <el-tab-pane label="产品计划"         name="productPlan"></el-tab-pane>
        <el-tab-pane label="投保人"           name="policyholder"></el-tab-pane>
        <el-tab-pane label="受保人"           name="insured"></el-tab-pane>
        <el-tab-pane label="受益人"           name="beneficiary"></el-tab-pane>
        <el-tab-pane label="第二持有人"       name="secondHolder"></el-tab-pane>
        <el-tab-pane label="预约附件"         name="appointmentAttachment"></el-tab-pane>
        <el-tab-pane label="介绍人"           name="introducer"></el-tab-pane>
        <el-tab-pane label="邮寄信息"         name="postal"></el-tab-pane>
        <el-tab-pane label="关联记录"         name="relatedRecords"></el-tab-pane>
        <el-tab-pane label="新单附件"         name="policyAttachment"></el-tab-pane>
      </el-tabs>

      <!-- 1. 基础信息 Tab（保留你的原有代码） -->
      <div v-if="activeTab === 'basic'" class="tab-content">
        <div class="section">
          <h3 class="sectionTitle">基础信息</h3>
          <SearchForm
            ref="basicInfoFormRef"
            :config="basicInfoFormConfig"
            v-model="basicInfoFormData"
            :disabled="props.mode === 'viewDetail'"
          />
        </div>
        <div class="section">
          <h3 class="sectionTitle">保单信息</h3>
          <SearchForm
            ref="policyInfoFormRef"
            :config="policyInfoFormConfig"
            v-model="policyInfoFormData"
            :disabled="props.mode === 'viewDetail'"
          />
        </div>
      </div>

      <!-- 2. 产品计划 Tab（完全匹配你的传参格式） -->
      <div v-else-if="activeTab === 'productPlan'" class="tab-content">
        <div class="section">
          <h3 class="sectionTitle">产品计划</h3>
          <!-- 完全匹配预约页面的ProductPlan传参 -->
          <ProductPlan
            :activeName="activeName"
            :formStatus="formStatus"
            :idsObj="idsObj"
            :apiProductPlanInfoDto="policySummeryInfo.apiProductPlanInfoDto"
            :appointmentStatus="policySummeryInfo.status"
            ref="productPlanRef"
            @policyEditSuccess="getPolicyDetail"
            :pageSource="pageSource"
            :showSubmitBtn="showSubmitBtn"
            :tabIndex="tabsList.findIndex(t => t.name === 'productPlan')"
            anchorContainer=".appointmentTabPaneBox"
            :fatherTabName="activeTab"
            :isEditMode="props.mode !== 'viewDetail'"
            :affixOffset="pageSource == 'fnaList' ? 360 : 250"
            :isExportAppointment="isExportPolicy"
          />
        </div>
      </div>

      <!-- 3. 投保人/受保人/受益人/第二持有人/预约附件 Tab（保留结构，后续按需补传参） -->
      <div v-else-if="activeTab === 'policyholder'" class="tab-content">
        <div class="section">
          <h3 class="sectionTitle">投保人信息</h3>
          <!-- 这里补充你预约页面投保人组件的真实传参 -->
          <Customer
            ref="policyholderRef"
            type="policyholder"
            :isEditMode="props.mode !== 'viewDetail'"
            :policyBizId="props.policyBizId"
            v-model="policyholderFormData"
          />
        </div>
      </div>
      <div v-else-if="activeTab === 'insured'" class="tab-content">
        <div class="section">
          <h3 class="sectionTitle">受保人信息</h3>
          <Customer
            ref="insuredRef"
            type="insured"
            :isEditMode="props.mode !== 'viewDetail'"
            :policyBizId="props.policyBizId"
            v-model="insuredFormData"
          />
        </div>
      </div>
      <div v-else-if="activeTab === 'beneficiary'" class="tab-content">
        <div class="section">
          <h3 class="sectionTitle">受益人信息</h3>
          <Beneficiary
            ref="beneficiaryRef"
            :isEditMode="props.mode !== 'viewDetail'"
            :policyBizId="props.policyBizId"
            v-model="beneficiaryFormData"
          />
        </div>
      </div>
      <div v-else-if="activeTab === 'secondHolder'" class="tab-content">
        <div class="section">
          <h3 class="sectionTitle">第二持有人信息</h3>
          <SecondHolder
            ref="secondHolderRef"
            :isEditMode="props.mode !== 'viewDetail'"
            :policyBizId="props.policyBizId"
            v-model="secondHolderFormData"
          />
        </div>
      </div>
      <div v-else-if="activeTab === 'appointmentAttachment'" class="tab-content">
        <div class="section">
          <h3 class="sectionTitle">预约附件</h3>
          <FileUpload
            ref="appointmentAttachmentRef"
            :isEditMode="props.mode !== 'viewDetail'"
            :bizId="props.policyBizId"
            type="appointment"
          />
        </div>
      </div>

      <!-- 以下是你已实现的Tab（保留不变） -->
      <div v-else-if="activeTab === 'introducer'" class="tab-content">
        <div class="section">
          <h3 class="sectionTitle">介绍人信息</h3>
          <h5>
            第一位默认是客户主要负责人，客户资料出现在介绍人（主）账号下，其他介绍人不会看到客户信息
          </h5>
          <EditableTable
            v-model="introducerTableData"
            :row-config="introducerConfig"
            @batch-save="handleBatchSave"
            :disabled="props.mode === 'viewDetail'"
          />
        </div>
      </div>
      <div v-else-if="activeTab === 'postal'" class="tab-content">
        <div class="section">
          <h3 class="sectionTitle">邮寄信息</h3>
          <SearchForm
            ref="postalFormRef"
            :config="postalFormConfig"
            v-model="postalFormData"
            :disabled="props.mode === 'viewDetail'"
          />
        </div>
      </div>
      <div v-else-if="activeTab === 'relatedRecords'" class="tab-content">
        <div class="section">
          <h3 class="sectionTitle">关联记录</h3>
          <el-table :data="relatedTableData" border style="width: 100%">
            <el-table-column prop="fnaNo" label="流程编号" width="180" />
            <el-table-column prop="policyNo" label="保单号" width="180" />
            <el-table-column prop="customerName" label="客户姓名" width="180" />
            <el-table-column
              prop="createTime"
              label="创建时间"
              width="180"
              :formatter="row => formatToDate(row.createTime)"
            />
            <el-table-column fixed="right" label="操作" min-width="120">
              <template #default>
                <el-button link type="primary" size="small" @click="viewRecordDetail">
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div v-else-if="activeTab === 'policyAttachment'" class="tab-content">
        <div class="section">
          <h3 class="sectionTitle">附件</h3>
          <el-button
            type="primary"
            @click="fileUploadDialogFlag = true"
            :disabled="props.mode === 'viewDetail'"
          >
            <el-icon class="el-icon--right"> <Upload /> </el-icon>上传附件
          </el-button>
          <el-table :data="attachmentTableData" border style="width: 100%">
            <el-table-column
              v-for="(column, index) in attachmentTableColumns"
              :key="index"
              :prop="column.prop"
              :label="column.label"
              :width="column.width"
              :sortable="column.sortable"
              :formatter="column.formatter"
            />
            <el-table-column fixed="right" label="操作" min-width="120">
              <template #default>
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="handleClick"
                  :disabled="props.mode === 'viewDetail'"
                >
                  修改
                </el-button>
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click="handleClick"
                  :disabled="props.mode === 'viewDetail'"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="form-footer">
        <el-button size="default" @click="handleCancel">取消</el-button>
        <el-button type="primary" size="default" @click="handleSubmit">确认</el-button>
      </div>
    </el-form>

    <!-- 文件上传弹窗 -->
    <CommonDialog
      dialogTitle="文件导入"
      dialogWidth="80%"
      :openDialog="fileUploadDialogFlag"
      :showAction="true"
      :showClose="true"
      @close="((fileUploadDialogFlag = false), (files = ''))"
      @confirm="((fileUploadDialogFlag = false), (files = ''))"
    >
      <FileUpload
        v-model="files"
        :data="{ obiectTableName: 'policy_follow', objectBizId: props.policyBizId }"
        :file-type="['xlsx', 'xls', 'doc', 'docx', 'pdf', 'txt', 'jpg', 'jpeg', 'png', 'gif']"
        :action="'/oss/api/oss/batch/upload'"
        :limit="10"
        :fileSize="15"
        :name="'files'"
        @uploadEnd="handleUploadEnd"
      />
    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, nextTick, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'

// ========== 1. 组件导入（保留你的原有导入） ==========
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import CommonDialog from '@/components/commonDialog'
import EditableTable from '@/components/csf-common/EditableTable.vue'
import ProductPlan from '@/views/sign/appointment/components/productPlan.vue'
import Customer from '@/views/sign/FnaList/components/customer'
import Beneficiary from '@/views/sign/appointment/components/beneficiaryInfo.vue'
import SecondHolder from '@/views/sign/appointment/components/secondHolderInfo.vue'
import FileUpload from '@/views/sign/appointment/components/fileUpload.vue'

// ========== 2. API和工具函数导入（保留你的原有导入） ==========
import { getPolicyfollow, getProductPlan, getPolicyholder,getInsurant,getBeneficiary,getSecondHolder,getAppointmentFiles,updatePolicyfollow } from '@/api/sign/underwritingMain'
import { uploadOssFileList } from '@/api/common'
import { getProcessDetail } from '@/api/sign/fna'
import { loadDicts, getDictLabel } from '@/utils/useDict'
import { formatToDate } from '@/utils/date'
import useUserStore from '@/store/modules/user'

// ========== 3. 核心变量定义（新增ProductPlan所需的所有参数） ==========
const { proxy } = getCurrentInstance()
const router = useRouter()
const userStore = useUserStore()

// 加载字典
proxy.useDictLists([
  'sys_no_yes',
  'csf_ap_frequency',
  'bx_currency_type',
  'csf_ap_first_issue',
  'csf_ap_dividend',
  'csf_fortune_status',
  'csf_ap_mailing_method',
  'receipt_status'
])

// ========== 6. Props & Emits（保留不变） ==========
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({})
  },
  mode: {
    type: String,
    default: 'viewDetail' // viewDetail=查看，edit=编辑
  },
  policyBizId: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'submit', 'cancel', 'saveSuccess'])

// ========== 4. ProductPlan组件所需的完整参数（完全匹配你的传参） ==========
const activeName = ref('productPlan') // 激活的子标签名
const formStatus = ref('edit') // 表单状态（edit/view）
const idsObj = ref({
  policyBizId: props.policyBizId, // 核心：新单跟进的保单ID
  fnaBizId: '',
  appointmentBizId: ''
})
// 保单汇总信息（适配ProductPlan的apiProductPlanInfoDto）
const policySummeryInfo = ref({
  apiProductPlanInfoDto: {},
  status: '' // 预约状态
})
const pageSource = ref('newOrder') // 页面来源：新单跟进
const showSubmitBtn = ref(false) // 是否显示提交按钮（新单跟进不需要）
// Tab列表（匹配tabIndex计算）
const tabsList = ref([
  { name: 'basic', label: '基础信息' },
  { name: 'productPlan', label: '产品计划' },
  { name: 'policyholder', label: '投保人' },
  { name: 'insured', label: '受保人' },
  { name: 'beneficiary', label: '受益人' },
  { name: 'secondHolder', label: '第二持有人' },
  { name: 'appointmentAttachment', label: '预约附件' },
  { name: 'introducer', label: '介绍人' },
  { name: 'postal', label: '邮寄信息' },
  { name: 'relatedRecords', label: '关联记录' },
  { name: 'policyAttachment', label: '新单附件' }
])
const isExportPolicy = ref(false) // 是否导出保单
const tabsRef = ref(null) // tabs组件ref

// ========== 5. 原有变量（保留不变） ==========
const files = ref('')
const fileUploadDialogFlag = ref(false)
const tabDirty = ref({
  basic: false,
  productPlan: false,
  policyholder: false,
  insured: false,
  beneficiary: false,
  secondHolder: false,
  appointmentAttachment: false,
  introducer: false,
  postal: false,
  relatedRecords: false,
  policyAttachment: false
})



// ========== 7. 通用Tab表单数据（保留） ==========
const productPlanRef = ref(null)
const policyholderFormData = ref({})
const insuredFormData = ref({})
const beneficiaryFormData = ref({})
const secondHolderFormData = ref({})
const appointmentAttachmentRef = ref(null)

// ========== 8. 你已实现的变量（完全保留） ==========
const introducerTableData = ref([])
const introducerConfig = ref([
  {
    type: 'select',
    prop: 'brokerName',
    label: '转介人',
    api: '/insurance/base/api/userSaleExpand/page',
    keywordField: 'realName',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入转介人名称搜索',
    debounceWait: 500,
    onChangeExtraFields: {
      internalCode: 'code',
      team: 'teamName',
      phone: 'phone',
      brokerBizId: 'clientUserBizId'
    },
    transform: res => {
      return (res?.data.records || []).map(item => ({
        value: item.realName,
        label: item.realName,
        ...item
      }))
    }
  },
  {
    type: 'input',
    prop: 'phone',
    label: '手机号码',
    span: 4,
    disabled: true
  },
  {
    type: 'input',
    prop: 'internalCode',
    label: '内部编号',
    span: 4,
    disabled: true
  },
  {
    type: 'input',
    prop: 'team',
    label: '所属团队',
    span: 4,
    disabled: true
  },
  {
    type: 'input',
    prop: 'brokerRatio',
    label: '分配比例%',
    span: 4,
    inputType: 'integer',
    rules: [
      { required: true, message: '请输入比例' },
      {
        validator: (rule, value, cb) => {
          const n = Number(value)
          if (isNaN(n) || n < 0 || n > 100) cb(new Error('0～100'))
          else cb()
        }
      }
    ]
  },
  {
    type: 'textarea',
    prop: 'remark',
    label: '备注',
    span: 4
  }
])

const basicInfoFormRef = ref()
const basicInfoFormData = ref({})
const basicInfoFormConfig = ref([
  { type: 'date', prop: 'signDate', label: '签单日' },
  {
    type: 'select',
    prop: 'signer',
    label: '签单员',
    api: '/insurance/base/api/userSignExpand/page',
    keywordField: 'realName',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入签单员姓名搜索',
    debounceWait: 500,
    onChangeExtraFields: { signerBizId: 'userSignBizId', practiceCode: 'practiceCode' },
    valueKey: 'realName',
    labelKey: 'realName',
    transform: res => res?.data.records || [],
    rules: [{ required: true, message: '请选择签单员', trigger: 'blur' }]
  },
  { type: 'input', prop: 'practiceCode', label: '签单员执业编号' },
  { type: 'select', prop: 'signLocation', label: '签单地点', dictType: 'csf_ap_meeting_point' }
])

const policyInfoFormRef = ref()
const policyInfoFormData = ref({})
const policyInfoFormConfig = ref([
  { type: 'input', prop: 'policyNo', label: '保单号' },
  {
    type: 'input',
    prop: 'coolingOffDays',
    label: '冷静期（天）',
    inputType: 'decimal',
    rules: [
      { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' },
      { required: true, message: '请填写冷静期', trigger: 'blur' }
    ]
  },
  {
    type: 'date',
    prop: 'coolingOffEndDate',
    label: '冷静期到期日',
    rules: [{ required: true, message: '请填写冷静期到期日', trigger: 'blur' }]
  },
  { type: 'date', prop: 'effectiveDate', label: '保单生效日' },
  { type: 'date', prop: 'policyExpirationDate', label: '保单截止日' },
  { type: 'date', prop: 'underwritingDate', label: '保单核保日' },
  { type: 'date', prop: 'receiptDate', label: '保单回执日' },
  { type: 'select', prop: 'receiptStatus', label: '回执状态', dictType: 'receipt_status' },
  { type: 'select', prop: 'directPaymentEnabled', label: '是否开通直接支付', dictType: 'sys_no_yes' },
  { type: 'input', prop: 'policyHolder', label: '保单持有人' },
  { type: 'input', prop: 'insured', label: '保单受保人' },
  { type: 'input', prop: 'insuredAge', label: '受保人年龄' },
  {
    type: 'input',
    prop: 'gracePeriod',
    label: '宽限期（天）',
    inputType: 'decimal',
    rules: [{ pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
  },
  { type: 'date', prop: 'latestPaymentDate', label: '最晚缴费日' },
  { type: 'select', prop: 'isJoin', label: '是否参加递增保障权益', dictType: 'sys_no_yes' },
  {
    type: 'select',
    prop: 'policyType',
    label: '保单类型',
    options: [{ label: '纸质保单', value: 2 }, { label: '电子保单', value: 1 }]
  }
])

const postalFormRef = ref(null)
const postalFormData = ref({})
const postalFormConfig = ref([
  { type: 'select', prop: 'mailingMethod', label: '寄送方式', dictType: 'csf_mailing_method' },
  { type: 'input', prop: 'deliveryNo', label: '快递单号', visible: formData => formData.mailingMethod == '2' },
  { type: 'input', prop: 'mailingItem', label: '邮寄物品', visible: formData => formData.mailingMethod == '2' },
  {
    type: 'date',
    prop: 'brokerSignDate',
    label: '我司签收日',
    rules: [{ required: true, message: '请输入我司签收日', trigger: 'blur' }]
  },
  {
    type: 'date',
    prop: 'customerSignDate',
    label: '客户签收日',
    rules: [{ required: true, message: '请输入客户签收日', trigger: 'blur' }]
  }
])

const relatedTableData = ref([])
const attachmentTableData = ref([])
const attachmentTableColumns = ref([
  { prop: 'originalName', label: '文件名', sortable: true, width: '150', formatter: row => row.originalName || '-' },
  { prop: 'fileType', label: '文件类型', sortable: true, width: '150', formatter: row => row.fileType || '-' },
  { prop: 'createTime', label: '上传时间', sortable: true, width: '150', formatter: row => row.createTime || '-' },
  { prop: 'creatorName', label: '上传人', sortable: true, width: '150', formatter: row => row.creatorName || '-' }
])

const defaultFormData = () => ({})
const localData = ref(defaultFormData())
const formRef = ref()
const activeTab = ref('basic')

// ========== 9. ProductPlan所需的回调方法 ==========
// 产品计划编辑成功后刷新保单详情
const getPolicyDetail = () => {
  // 重新加载新单跟进数据
  getPolicyfollowDetail()
  // 重新加载产品计划数据
  loadProductPlanData()
  ElMessage.success('产品计划修改成功')
  tabDirty.value.productPlan = true
}

// ========== 10. 原有方法（适配ProductPlan参数） ==========
const handleBeforeLeave = async (newTabName, oldTabName) => {
  if (tabDirty.value[oldTabName]) {
    try {
      await ElMessageBox.confirm(`“${getTabLabel(oldTabName)}” 未提交，确定要切换吗？`, '提示', {
        confirmButtonText: '继续切换',
        cancelButtonText: '取消',
        type: 'warning'
      })
      return true
    } catch {
      return false
    }
  }
  return true
}

const getTabLabel = (name) => {
  const labels = {
    basic: '基础信息',
    productPlan: '产品计划',
    policyholder: '投保人',
    insured: '受保人',
    beneficiary: '受益人',
    secondHolder: '第二持有人',
    appointmentAttachment: '预约附件',
    introducer: '介绍人',
    postal: '邮寄信息',
    relatedRecords: '关联记录',
    policyAttachment: '新单附件'
  }
  return labels[name] || name
}

const handleTabClick = (tab) => {
  const tabName = tab.props.name
  // 产品计划Tab加载逻辑（适配新参数）
  if (tabName === 'productPlan') {
    // 更新idsObj的policyBizId
    idsObj.value.policyBizId = props.policyBizId
    // 加载产品计划数据
    loadProductPlanData()
  } else if (tabName === 'policyholder') {
    loadPolicyholderData()
  } else if (tabName === 'insured') {
    loadInsuredData()
  } else if (tabName === 'beneficiary') {
    loadBeneficiaryData()
  } else if (tabName === 'secondHolder') {
    loadSecondHolderData()
  } else if (tabName === 'appointmentAttachment') {
    loadAppointmentAttachmentData()
  } else if (tabName === 'postal') {
    postalFormConfig.value = postalFormConfig.value.map(item => ({
      ...item,
      disabled: props.mode === 'viewDetail'
    }))
  } else if (tabName === 'relatedRecords') {
    getRelationRecord(localData.value.fnaBizId || props.modelValue.fnaBizId)
  } else if (tabName === 'policyAttachment') {
    getAttachmentListDetail(props.policyBizId)
  }
}

// ========== 11. 产品计划数据加载（适配新参数） ==========
const loadProductPlanData = () => {
  console.log('------------',props.policyBizId )
  if (!props.policyBizId) return
  console.log()
  getProductPlan(props.policyBizId).then(res => {
    if (res.code === 200) {
      // 适配policySummeryInfo的格式
      policySummeryInfo.value.apiProductPlanInfoDto = res.data || {}
      policySummeryInfo.value.status = localData.value.status || ''
    }
  })
}

// ========== 12. 其他通用Tab数据加载（保留） ==========
const loadPolicyholderData = () => {
  if (!props.policyBizId) return
  getPolicyholder(props.policyBizId).then(res => {
    if (res.code === 200) {
      policyholderFormData.value = res.data || {}
    }
  })
}

const loadInsuredData = () => {
  if (!props.policyBizId) return
  getInsurant(props.policyBizId).then(res => {
    if (res.code === 200) {
      insuredFormData.value = res.data || {}
    }
  })
}

const loadBeneficiaryData = () => {
  if (!props.policyBizId) return
  getBeneficiary(props.policyBizId).then(res => {
    if (res.code === 200) {
      beneficiaryFormData.value = res.data || {}
    }
  })
}

const loadSecondHolderData = () => {
  if (!props.policyBizId) return
  getSecondHolder(props.policyBizId).then(res => {
    if (res.code === 200) {
      secondHolderFormData.value = res.data || {}
    }
  })
}

const loadAppointmentAttachmentData = () => {
  if (!props.policyBizId) return
  getAppointmentFiles({ policyBizId: props.policyBizId }).then(res => {
    if (res.code === 200) {
      appointmentAttachmentRef.value?.setFileList(res.data || [])
    }
  })
}

// ========== 13. 你已实现的方法（完全保留） ==========
const handleBatchSave = (validRows) => {
  console.log('批量提交:', validRows)
  introducerTableData.value = validRows
  tabDirty.value.introducer = true
}

const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return

    // 收集所有数据（包含产品计划）
    const submitData = {
      policyBizId: props.policyBizId,
      ...basicInfoFormData.value,
      ...policyInfoFormData.value,
      ...postalFormData.value,
      brokerList: introducerTableData.value,
      // 产品计划数据（从ProductPlan组件获取）
      productPlan: productPlanRef.value ? productPlanRef.value.getFormData() : {}
    }

    try {
      const res = await updatePolicyfollow(submitData)
      if (res.code === 200) {
        ElMessage.success('保存成功')
        emit('saveSuccess', res.data)
        Object.keys(tabDirty.value).forEach(key => tabDirty.value[key] = false)
      }
    } catch (error) {
      ElMessage.error(`保存失败：${error.message || '服务器错误'}`)
    }
  })
}

const handleCancel = () => {
  emit('cancel')
}

const handleClick = () => {
  ElMessage.info('附件操作功能待完善')
}

const getPolicyfollowDetail = () => {
  if (!props.policyBizId) return
  getPolicyfollow(props.policyBizId).then(res => {
    if (res.code === 200) {
      const data = res.data
      localData.value = { ...localData.value, ...data }
      basicInfoFormData.value = { ...transformToFormData(data, basicInfoFormConfig.value) }
      policyInfoFormData.value = { ...transformToFormData(data, policyInfoFormConfig.value) }
      postalFormData.value = { ...transformToFormData(data, postalFormConfig.value) }
      introducerTableData.value = data.brokerList || []
      
      // 同步更新产品计划的状态参数
      policySummeryInfo.value.status = data.status || ''
      idsObj.value.fnaBizId = data.fnaBizId || ''
      idsObj.value.appointmentBizId = data.appointmentBizId || ''
    }
  })
}

const getAttachmentListDetail = (policyBizId) => {
  if (!policyBizId) return
  const params = { objectBizId: policyBizId, pageNo: 1, pageSize: 100 }
  uploadOssFileList(params).then(res => {
    if (res.code === 200) {
      attachmentTableData.value = res.data || []
    }
  })
}

const handleUploadEnd = (code) => {
  if (code === 200) {
    ElMessage.success('上传文件成功')
    fileUploadDialogFlag.value = false
    files.value = ''
    getAttachmentListDetail(props.policyBizId)
    tabDirty.value.policyAttachment = true
  } else {
    ElMessage.error('上传文件失败')
  }
}

const transformToFormData = (apiData, formConfig) => {
  const formData = {}
  formConfig.forEach(item => {
    const { prop, dictType } = item
    let value = apiData[prop] ?? null
    if (dictType && typeof value === 'number') {
      value = String(value)
    }
    formData[prop] = value
  })
  return formData
}

const getRelationRecord = (fnaBizId) => {
  getProcessDetail(fnaBizId).then(res => {
    if (res.code === 200) {
      relatedTableData.value = [res.data] || []
    }
  })
}

const viewRecordDetail = (e) => {
  router.push({
    path: '/sign/FnaList/edit',
    query: {
      fnaBizId: localData.value.fnaBizId,
      type: 'edit',
      status: localData.value.status,
      source: 'newOrder',
      appointmentBizId: localData.value.appointmentBizId
    }
  })
}

// ========== 14. 初始化（适配ProductPlan参数） ==========
onMounted(async () => {
  if (props.modelValue) {
    localData.value = { ...defaultFormData(), ...props.modelValue }
  }
  // 初始化idsObj的policyBizId
  idsObj.value.policyBizId = props.policyBizId
  // 加载基础数据
  getPolicyfollowDetail()
  
  // 初始化formStatus
  formStatus.value = props.mode === 'viewDetail' ? 'view' : 'edit'
})

// 监听props变化，同步更新idsObj
watch(() => props.policyBizId, (newVal) => {
  if (newVal) {
    idsObj.value.policyBizId = newVal
  }
})

// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    Object.assign(localData, defaultFormData(), newVal)
  }
}, { deep: true })

// 监听localData变化
watch(() => localData.value, (newVal) => {
  emit('update:modelValue', newVal)
}, { deep: true })
</script>

<style scoped>
.form-page {
  padding: 10px;
  background: #fff;
  border-radius: 4px;
  padding-top: 0;
}

.tab-placeholder {
  padding: 40px 0;
}

.form-footer {
  text-align: center;
  margin-top: 30px;
}

.sectionTitle {
  margin: 0 0 15px 0;
  font-size: 16px;
  line-height: 1;
  position: relative;
  padding-left: 16px;
}

.sectionTitle::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6px;
  height: 20px;
  background-color: #007bff;
  border-radius: 5px;
}

.section h5 {
  margin: 0;
  font-size: 14px;
  line-height: 1;
  position: relative;
  background-color: rgba(0, 119, 238, 0.05);
  color: #383838;
  padding: 15px 10px;
  border-radius: 4px;
}

/* 适配anchorContainer锚点容器样式 */
.appointmentTabPaneBox {
  position: relative;
}
</style>