<!-- 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="referrer"></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-if="activeTab === 'firstPayment'" class="tab-content">
                <!-- 签单信息 -->
                <div class="section">
                    <h3 class="sectionTitle">缴费信息</h3>
                    <SearchForm ref="firstPremiumFormRef" :config="firstPremiumFormConfig"
                        v-model="firstPremiumFormData" />
                </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 } from 'vue'
import SearchForm from '@/components/SearchForm/SearchForm.vue'



const basicInfoFormRef = ref()
const basicInfoFormData = ref({})
const basicInfoFormConfig = ref([
    {
        type: 'date',
        prop: 'signDate',
        label: '签单日',
    }, {
        type: 'select',
        prop: 'currency',
        label: '签单员',
        dictType: 'bx_currency_type',
    }, {
        type: 'input',
        prop: 'policyNo',
        label: '签单员执业编号',

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

])

// 保单信息
const policyInfoFormRef = ref()
const policyInfoFormData = ref({})
const policyInfoFormConfig = ref([
    {
        type: 'date',
        prop: 'endDate',
        label: '保单号',
    }, {
        type: 'date',
        prop: 'effectiveDate',
        label: '保单生效日',
    }, {
        type: 'date',
        prop: 'effectiveDate',
        label: '保单截止日',
    }, {
        type: 'date',
        prop: 'underwritingDate',
        label: '保单核保日',
    }, {
        type: 'date',
        prop: 'underwritingDate',
        label: '保单回执日',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '回执状态',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '是否开通直接支付',
    }, {
        type: 'input',
        prop: 'insurer',
        label: '保单持有人',
    }, {
        type: 'input',
        prop: 'insurer',
        label: '保单受保人',
    }, {
        type: 'select',
        prop: 'insuranceType',
        label: '受保人年龄',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '宽限期',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '是否参加递增保障权益',
    },
])

// 基本计划
const basicPlanFormRef = ref()
const basicPlanFormData = ref({})
const basicPlanFormConfig = ref([
    {
        type: 'select',
        prop: 'paymentFrequency',
        label: '保险公司',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '保险险种',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '产品名称',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '付款频率',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '保障期限',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '保额（重疾险）',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '供款期数',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '保单币种',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '每期保费',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '保单征费',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '是否预缴',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '是否追溯',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '回溯日期',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '首期付款方式',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '续期付款方式',
    }, {
        type: 'select',
        prop: 'paymentFrequency',
        label: '红利付款方式',
    },
])

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

// ===== Props & Emits =====

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

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

// ===== 本地响应式数据 =====
const defaultFormData = () => ({
    signDate: '',
    agentId: '',
    location: '',
    policyNo: '',
    effectiveDate: '',
    endDate: '',
    underwritingDate: '',
    insurer: '',
    insuranceType: '',
    productName: '',
    paymentFrequency: '',
    additionalPlans: []
})


// ✅ 使用 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({
        product: '',
        frequency: '',
        term: '',
        periods: '',
        currency: '',
        premium: '',
        fee: ''
    })
}

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')
}

// 如果外部 modelValue 更新（比如重新加载数据），同步到 localData
watch(
    () => props.modelValue,
    (newVal) => {
        if (newVal) {
            Object.assign(localData, defaultFormData(), 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;
}
</style>