<!-- components/FormPage.vue -->
<template>
    <div class="form-page">
        <el-form ref="formRef" :model="localData" label-width="120px" size="default">
            <!-- Tabs -->
            <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                <el-tab-pane label="基础信息" name="basic"></el-tab-pane>
                <el-tab-pane label="首期缴费" name="firstPayment"></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="related"></el-tab-pane>
                <el-tab-pane label="附件" name="attachment"></el-tab-pane>
            </el-tabs>

            <!-- 基础信息 Tab 内容 -->
            <div v-if="activeTab === 'basic'" class="tab-content">
                <!-- 签单信息 -->
                <div class="section">
                    <h3 class="sectionTitle">基础信息</h3>
                    <SearchForm ref="basicInfoFormRef" :config="basicInfoFormConfig" v-model="basicInfoFormData" />
                </div>

                <!-- 保单信息 -->
                <div class="section">
                    <h3 class="sectionTitle">保单信息</h3>
                    <SearchForm ref="policyInfoFormRef" :config="policyInfoFormConfig" v-model="policyInfoFormData" />
                </div>

                <!-- 基本计划 -->
                <div class="section">
                    <h3 class="sectionTitle">基本计划</h3>
                    <SearchForm ref="basicPlanFormRef" :config="basicPlanFormConfig" v-model="basicPlanFormData" />
                </div>

                <!-- 附加计划（可编辑表格） -->
                <div class="section">
                    <h3 class="sectionTitle">附加计划</h3>
                    <el-button type="primary" size="default" @click="addAdditionalPlan">+ 新增</el-button>
                    <el-table :data="localData.additionalPlans || []" style="width: 100%; margin-top: 10px" border>
                        <el-table-column prop="product" label="产品名称" width="180">
                            <template #default="{ row }">
                                <el-input v-model="row.product" size="default" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="frequency" label="付款频率" width="150">
                            <template #default="{ row }">
                                <el-select v-model="row.frequency" size="default" placeholder="选择">
                                    <el-option label="月付" value="monthly" />
                                    <el-option label="年付" value="yearly" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="term" label="保障期限" width="150">
                            <template #default="{ row }">
                                <el-input v-model="row.term" size="default" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="periods" label="供款期数" width="150">
                            <template #default="{ row }">
                                <el-input v-model="row.periods" size="default" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="currency" label="保单币种" width="150">
                            <template #default="{ row }">
                                <el-input v-model="row.currency" size="default" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="premium" label="每期保费" width="150">
                            <template #default="{ row }">
                                <el-input v-model="row.premium" size="default" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="fee" label="保单征费" width="150">
                            <template #default="{ row }">
                                <el-input v-model="row.fee" size="default" />
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="120">
                            <template #default="{ $index }">
                                <el-button size="default" type="danger" @click="deleteRow($index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>

            <!-- 首期缴费 Tab 内容 -->
            <div v-else-if="activeTab === 'firstPayment'" class="tab-content">
                <!-- 签单信息 -->
                <div class="section">
                    <h3 class="sectionTitle">缴费信息</h3>
                    <SearchForm ref="firstPremiumFormRef" :config="firstPremiumFormConfig"
                        v-model="firstPremiumFormData" />
                    <h3 class="sectionTitle">首期对账信息</h3>
                    <el-table :data="firstPremiumTableData" border style="width: 100%">
                        <el-table-column prop="date" label="申请对账日期" width="180" />
                        <el-table-column prop="name" label="对账状态" width="180" />
                        <el-table-column prop="address" label="缴费方式" width="180" />
                        <el-table-column prop="address" label="汇款币种" width="180" />
                        <el-table-column prop="address" label="汇款日期" width="180" />
                        <el-table-column prop="address" label="认定金额" width="180" />
                        <el-table-column prop="address" label="认定币种" width="180" />
                    </el-table>
                </div>
            </div>
            <!-- 介绍人 Tab 内容 -->
            <div v-else-if="activeTab === 'introducer'" class="tab-content">
                <!-- 签单信息 -->
                <div class="section">
                    <h3 class="sectionTitle">介绍人信息</h3>
                    <h5>第一位默认是客户主要负责人，客户资料出现在介绍人（主）账号下，其他介绍人不会看到客户信息</h5>
                    <el-button type="primary">
                        <el-icon class="el-icon--right">
                            <Upload />
                        </el-icon>新增
                    </el-button>
                    <el-table :data="firstPremiumTableData" border style="width: 100%">
                        <el-table-column prop="date" label="介绍人姓名" width="180" />
                        <el-table-column prop="name" label="性别" width="180" />
                        <el-table-column prop="address" label="内部编号" width="180" />
                        <el-table-column prop="address" label="所属团队" width="180" />
                        <el-table-column prop="address" label="分配比例" width="180" />
                        <el-table-column prop="address" label="备注" width="180" />
                        <el-table-column fixed="right" label="操作" min-width="120">
                            <template #default>
                                <el-button link type="primary" size="small" @click="handleClick">
                                    Detail
                                </el-button>
                                <el-button link type="primary" size="small">Edit</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <!-- 邮寄信息 Tab 内容 -->
            <div v-else-if="activeTab === 'postal'" class="tab-content">
                <div class="section">
                    <h3 class="sectionTitle">邮寄信息</h3>
                    <SearchForm ref="postalFormRef" :config="postalFormConfig" v-model="postalFormData" />
                </div>
            </div>
            <!-- 关联记录 Tab 内容 -->
            <div v-else-if="activeTab === 'related'" class="tab-content">
                <div class="section">
                    <h3 class="sectionTitle">关联记录</h3>
                    <el-table :data="relatedTableData" border style="width: 100%">
                        <el-table-column prop="date" label="流程编号" width="180" />
                        <el-table-column prop="name" label="客户姓名" width="180" />
                        <el-table-column prop="address" label="创建时间" width="180" />
                        <el-table-column fixed="right" label="操作" min-width="120">
                            <template #default>
                                <el-button link type="primary" size="small" @click="handleClick">
                                    Detail
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <!-- 附件 Tab 内容 -->
            <div v-else-if="activeTab === 'attachment'" class="tab-content">
                <div class="section">
                    <h3 class="sectionTitle">附件</h3>
                    <el-button type="primary">
                        <el-icon class="el-icon--right">
                            <Upload />
                        </el-icon>上传附件
                    </el-button>
                    <el-table :data="attachmentTableData" border style="width: 100%">
                        <el-table-column prop="date" label="文件名" width="180" />
                        <el-table-column prop="name" label="文件类型" width="180" />
                        <el-table-column prop="address" label="上传时间" width="180" />
                        <el-table-column prop="address" label="上传人" width="180" />
                        <el-table-column fixed="right" label="操作" min-width="120">
                            <template #default>
                                <el-button link type="primary" size="small" @click="handleClick">
                                    修改
                                </el-button><el-button link type="danger" size="small" @click="handleClick">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <!-- 其他 Tab 占位（你可以按需填充） -->
            <div v-else class="tab-placeholder">
                <el-empty description="该 Tab 内容待开发" />
            </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>
    </div>
</template>

<script setup>
import { ref, reactive, watch, nextTick, onMounted } from 'vue'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import { Delete, Edit, Search, Share, Upload } from '@element-plus/icons-vue'
import { getPolicyfollow, updatePolicyfollow, saveMailingInfo, batchSaveBrokers, saveInitialPayment } from '@/api/sign/underwritingMain'
const basicInfoFormRef = ref()
const basicInfoFormData = ref({})
const basicInfoFormConfig = ref([
    {
        type: 'date',
        prop: 'signDate',
        label: '签单日',
    }, {
        type: 'select',
        prop: 'signerBizId',
        label: '签单员',
        api: '/insurance/base/api/userSignExpand/page',
        keywordField: 'realName',
        requestParams: { pageNo: 1, pageSize: 20 },
        placeholder: '输入签单员姓名搜索',
        debounceWait: 500, // 自定义防抖时间
        onChangeExtraFields: {
            signer: 'realName',// 自动同步 raw.name 到 reconciliationCompany
        },
        valueKey: 'userSignBizId',
        labelKey: 'realName',
        transform: (res) => {
            console.log(res)
            return res?.data.records || []
        },
        rules: [
            { required: true, message: '请选择签单员', trigger: 'blur' },
        ]

    }, {
        type: 'input',
        prop: 'policyNo',
        label: '签单员执业编号',

    }, {
        type: 'select',
        prop: 'signLocation',
        label: '签单地点',
        dictType: 'bx_currency_type'
    },

])

// 保单信息
const policyInfoFormRef = ref()
const policyInfoFormData = ref({})
const policyInfoFormConfig = ref([
    {
        type: 'input',
        prop: 'policyNo',
        label: '保单号',
    }, {
        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: '是否开通直接支付',
    }, {
        type: 'input',
        prop: 'policyHolder',
        label: '保单持有人',
    }, {
        type: 'input',
        prop: 'insured',
        label: '保单受保人',
    }, {
        type: 'input',
        prop: 'insuredAge',
        label: '受保人年龄',
    }, {
        type: 'input',
        prop: 'gracePeriod',
        label: '宽限期',
    }, {
        type: 'select',
        prop: 'isJoin',
        label: '是否参加递增保障权益',
        dictType: 'sys_no_yes'
    },
])

// 基本计划
const basicPlanFormRef = ref()
const basicPlanFormData = ref({})
const basicPlanFormConfig = ref([
    {
        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: 'select',
        prop: 'paymentFrequency',
        label: '保险险种',
    }, {
        type: 'select',
        prop: 'productName',
        label: '产品名称',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '付款频率',
        dictType: 'csf_ap_frequency'
    }, {
        type: 'select',
        prop: 'guaranteePeriod',
        label: '保障期限',
    }, {
        type: 'input',
        prop: 'sumInsured',
        label: '保额（重疾险）',
    }, {
        type: 'select',
        prop: 'issueNumber',
        label: '供款期数',
    }, {
        type: 'select',
        prop: 'policyCurrency',
        label: '保单币种',
        dictType: 'bx_currency_type'
    }, {
        type: 'input',
        prop: 'initialPremium',
        label: '每期保费',
        inputType: 'decimal',
        decimalDigits: 2,
        visible: (formData) => formData.commissionBizType == 'R',
        rules: [
            { required: true, message: '请输入金额', trigger: 'blur' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '最多两位小数', trigger: 'blur' }
        ]
    }, {
        type: 'input',
        prop: 'policyLevy',
        label: '保单征费',
        inputType: 'decimal',
        decimalDigits: 2,
        visible: (formData) => formData.commissionBizType == 'R',
        rules: [
            { required: true, message: '请输入金额', trigger: 'blur' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '最多两位小数', trigger: 'blur' }
        ]
    }, {
        type: 'select',
        prop: 'isPrepay',
        label: '是否预缴',
        dictType: 'sys_no_yes'
    }, {
        type: 'select',
        prop: 'isTraceable',
        label: '是否追溯',
        dictType: 'sys_no_yes'
    }, {
        type: 'select',
        prop: 'retroactiveDate',
        label: '回溯日期',
    }, {
        type: 'select',
        prop: 'initialPaymentMethod',
        label: '首期付款方式',
        dictType: 'csf_ap_first_issue'
    }, {
        type: 'select',
        prop: 'renewalPaymentMethod',
        label: '续期付款方式',
        dictType: 'csf_ap_first_issue'
    }, {
        type: 'select',
        prop: 'dividendPaymentMethod',
        label: '红利付款方式',
        dictType: 'csf_ap_dividend'
    },
])

// 首期保费
const firstPremiumTableData = ref([])
const firstPremiumFormRef = ref()
const firstPremiumFormData = ref({})
const firstPremiumFormConfig = ref([
    {
        type: 'input',
        prop: 'initialPremium',
        label: '首期保费',
        inputType: 'decimal',
        decimalDigits: 2,
        rules: [
            { required: true, message: '请输入金额', trigger: 'blur' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '最多两位小数', trigger: 'blur' }
        ]
    }, {
        type: 'input',
        prop: 'policyLevy',
        label: '保单征费',
        inputType: 'decimal',
        decimalDigits: 2,
        rules: [
            { required: true, message: '请输入金额', trigger: 'blur' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '最多两位小数', trigger: 'blur' }
        ]
    }, {
        type: 'select',
        prop: 'initialPaymentMethod',
        label: '首期缴费方式',
        dictType: 'csf_ap_first_issue'
    }, {
        type: 'input',
        prop: 'initialPremiumPaid',
        label: '首期已缴保费',
        inputType: 'decimal',
        decimalDigits: 2,
        rules: [
            { required: true, message: '请输入金额', trigger: 'blur' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '最多两位小数', trigger: 'blur' }
        ]
    }, {
        type: 'input',
        prop: 'initialPremiumDue',
        label: '首期待缴保费',
        inputType: 'decimal',
        decimalDigits: 2,
        rules: [
            { required: true, message: '请输入金额', trigger: 'blur' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '最多两位小数', trigger: 'blur' }
        ]
    }, {
        type: 'input',
        prop: 'initialPremiumTotal',
        label: '首期缴费总额',
        inputType: 'decimal',
        decimalDigits: 2,
        rules: [
            { required: true, message: '请输入金额', trigger: 'blur' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '最多两位小数', trigger: 'blur' }
        ]
    }, {
        type: 'select',
        prop: 'initialPaymentStatus',
        label: '缴费状态',
        multiple: true,
        dictType: 'csf_fortune_status'
    }, {
        type: 'date',
        prop: 'latestPaymentDate',
        label: '最晚缴费日',
        placeholder: '请选择'
    }, {
        type: 'input',
        prop: 'initialPremiumDiscount',
        label: '首期保费优惠金额',
        inputType: 'decimal',
        decimalDigits: 2,
        rules: [
            { required: true, message: '请输入金额', trigger: 'blur' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '最多两位小数', trigger: 'blur' }
        ]
    },
])

// 邮寄信息
const postalFormRef = ref(null)
const postalFormData = ref({})
const postalFormConfig = ref([
    {
        type: 'input',
        prop: 'mailingMethod',
        label: '寄送方式',
        dictType: 'csf_ap_mailing_method'
    }, {
        type: 'input',
        prop: 'deliveryNo',
        label: '快递单号'
    }, {
        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([])
// ===== Props & Emits =====

const props = defineProps({
    modelValue: {
        type: Object,
        default: () => ({})
    }
})

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

// ===== 本地响应式数据 =====
const defaultFormData = () => ({
})


// ✅ 使用 ref 而不是 reactive
const localData = ref(defaultFormData())

// ✅ 只在挂载时初始化一次（避免 watch 形成闭环）
onMounted(() => {
    if (props.modelValue) {
        // 深拷贝 + 合并默认值，防止缺失字段
        localData.value = { ...defaultFormData(), ...props.modelValue }
    }
})

// ✅ 监听 localData 变化，emit 出去（用于 v-model）
watch(
    () => localData.value,
    (newVal) => {
        emit('update:modelValue', newVal)
    },
    { deep: true }
)
// ===== 表单引用 & 验证规则 =====
const formRef = ref()
const activeTab = ref('basic')

// ===== 添加附加险计划方法 =====
const addAdditionalPlan = () => {
    localData.additionalPlans.push({})
}

const deleteRow = (index) => {
    localData.additionalPlans.splice(index, 1)
}

const handleTabClick = (tab) => {
    console.log('切换到 Tab:', tab.name)
}

const handleSubmit = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            emit('submit', { ...localData })
        }
    })
}

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

const handleClick = (tab) => {
    activeTab.value = tab.name
}

// 如果外部 modelValue 更新（比如重新加载数据），同步到 localData
watch(
    () => props.modelValue,
    (newVal) => {
        if (newVal) {
            Object.assign(localData, defaultFormData(), newVal)
        }
    },
    { deep: true }
)

// 查询新单跟进详情
//  /csf/api/policy_follow/get/vo?policyBizId=${policyBizId}
const getPolicyfollowDetail = (policyBizId) => {
    getPolicyfollow(policyBizId).then(res => {
        if (res.code === 200) {
            Object.assign(localData, defaultFormData(), res.data)
            policyInfoFormData.value = transformToFormData(res.data, policyInfoFormConfig.value);
            basicPlanFormData.value = transformToFormData(res.data, basicPlanFormConfig.value);
            basicInfoFormData.value = transformToFormData(res.data, basicInfoFormConfig.value);
            firstPremiumFormData.value = transformToFormData(res.data, firstPremiumFormConfig.value);
        }
    })
}

// 组装表单数据
const transformToFormData = (apiData, formConfig) => {
    const formData = {};

    // 遍历表单配置，逐个赋值
    formConfig.forEach(item => {
        const { prop } = item;

        // 根据 prop 决定如何从 apiData 取值
        switch (prop) {
    
            case 'signLocation':
                formData[prop] = apiData.signLocation || null;
                break;

            default:
                // 如果 prop 和后端字段同名，可以直接赋值
                formData[prop] = apiData[prop] ?? null;
        }
    });

    return formData;
}
// 页面加载时调用
onMounted(() => {
    getPolicyfollowDetail(localData.value.policyBizId)
})
</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 0 15px 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;
}
</style>