<!-- 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 } from 'vue'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import { Delete, Edit, Search, Share, Upload } from '@element-plus/icons-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 firstPremiumTableData = ref([])
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: '首期保费优惠'
    },
])

// 邮寄信息
const postalFormRef = ref(null)
const postalFormData = ref({})
const postalFormConfig = ref([
    {
        type: 'input',
        prop: 'postalCode',
        label: '寄送方式',

    }, {
        type: 'input',
        prop: 'address',
        label: '快递单号',

    }, {
        type: 'date',
        prop: 'address',
        label: '我司签收日',
        rules: [
            { required: true, message: '请输入我司签收日', trigger: 'blur' }
        ]
    }, {
        type: 'date',
        prop: 'address',
        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 = () => ({
    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')
}

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

// 如果外部 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;
}
.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>