<template>
    <div class="charge-set-container">
        <!-- Tab栏 -->
        <el-tabs v-model="activeTab" class="charge-tabs">
            <el-tab-pane label="收费设置" name="charge">
                <!-- 收费设置 -->
                <div class="charge-content">
                    <!-- 服务商选择 -->
                    <div class="setting-group">
                        <label class="setting-label">
                            <span class="required">*</span>
                            服务商选择：
                        </label>
                        <el-radio-group v-model="form.servicer">
                            <el-radio v-for="dict in charge_set_servicer" :key="dict.value" :value="dict.value">
                                {{ dict.label }}
                            </el-radio>
                        </el-radio-group>
                    </div>

                    <!-- 是否开启预定金收费 -->
                    <div class="setting-group">
                        <label class="setting-label">
                            <span class="required">*</span>
                            是否开启预定金收费：
                        </label>
                        <el-radio-group v-model="form.moneyCharge">
                            <el-radio v-for="dict in money_charge" :key="dict.value" :value="dict.value">
                                {{ dict.label }}
                            </el-radio>
                        </el-radio-group>
                    </div>

                    <!-- 收费模式设置 -->
                    <div class="setting-group">
                        <label class="setting-label">
                            <span class="required">*</span>
                            收费模式设置：
                        </label>
                        <el-radio-group v-model="form.chargeMode">
                            <el-radio value='1'>单项收费</el-radio>
                            <el-radio value="2">组合收费</el-radio>
                        </el-radio-group>
                    </div>

                    <!-- 项目表格 -->
                    <div class="table-container">
                        <table v-if="form.chargeMode === '1'" class="charge-table">
                            <thead>
                                <tr>
                                    <th>编号</th>
                                    <th>项目名称 <span class="required">*</span></th>
                                    <th>项目编码</th>
                                    <th>计价单位</th>
                                    <th>价格 <span class="required">*</span></th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="(item, index) in chargeForm.forwardChargeItems" :key="index">
                                    <td>{{ index + 1 }}</td>
                                    <td>{{ item.name }}</td>
                                    <td>
                                        <input type="text" v-model="item.code" placeholder="请输入" class="table-input" />
                                    </td>
                                    <td>次</td>
                                    <td class="price-cell">
                                        <input type="number" v-model="item.price" class="table-input price-input" />
                                        <span class="unit">元</span>
                                    </td>
                                </tr>
                            </tbody>
                        </table>

                        <!-- 组合收费表格 -->
                        <table v-else-if="form.chargeMode === '2'" class="charge-table">
                            <thead>
                                <tr>
                                    <th>编号</th>
                                    <th>项目名称 <span class="required">*</span></th>
                                    <th>项目编码</th>
                                    <th>计价单位</th>
                                    <th>价格 <span class="required">*</span></th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="(item, index) in chargeForm.combinedChargeItems" :key="index">
                                    <td>{{ index + 1 }}</td>
                                    <td>{{ item.name }}</td>
                                    <td>
                                        <input type="text" v-model="item.code" placeholder="请输入" class="table-input" />
                                    </td>
                                    <td>次</td>
                                    <td class="price-cell">
                                        <input type="number" v-model="item.price" class="table-input price-input" />
                                        <span class="unit">元</span>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- 营养筛查收费设置 -->
                    <div class="setting-group">
                        <label class="setting-label">
                            <span class="required">*</span>
                            营养筛查收费设置：
                        </label>
                        <div class="input-with-unit">
                            <el-input v-model="form.nutritionChargeSet" type="number" class="number-input" placeholder="请输入金额" />
                            <span class="unit">元/次</span>
                        </div>
                    </div>

                    <!-- 适合处方类型 -->
                    <div class="setting-group">
                        <label class="setting-label">
                            <span class="required">*</span>
                            适合处方类型：
                        </label>
                        <el-checkbox-group v-model="chargeForm.prescriptionTypes">
                            <el-checkbox v-for="dict in fee_type.filter(item => ['3', '4'].includes(item.value))" :key="dict.value" :value="dict.value">
                                {{ dict.label }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>

                    <!-- 住院患者订单设置 -->
                    <div class="setting-group">
                        <label class="setting-label">住院患者订单设置：</label>
                        <el-radio-group v-model="form.patientOrderSet">
                            <el-radio value="1">开启</el-radio>
                            <el-radio value="2">关闭</el-radio>
                        </el-radio-group>
                    </div>

                    <!-- 订单有效时长 -->
                    <div class="setting-group">
                        <label class="setting-label">订单有效时长：</label>
                        <div class="duration-setting">
                            <el-button class="duration-btn" @click="decreaseDuration">−</el-button>
                            <el-input v-model="form.orderIndate" class="duration-input" :min="1" :max="365" />
                            <el-button class="duration-btn" @click="increaseDuration">+</el-button>
                            <span class="unit">天</span>
                        </div>
                    </div>

                    <!-- 保存按钮 -->
                    <div class="save-button-container">
                        <button class="save-btn" @click="submitForm">保存</button>
                    </div>
                </div>
            </el-tab-pane>

            <el-tab-pane label="账户设置" name="account">
                <!-- 账户设置 -->
                <div class="account-content">
                    <!-- 是否开启账户 -->
                    <div class="setting-group">
                        <label class="setting-label">是否开启账户：</label>
                        <el-radio-group v-model="accountForm.enableAccount">
                            <el-radio value="1">是</el-radio>
                            <el-radio value="0">否</el-radio>
                        </el-radio-group>
                    </div>

                    <!-- 账户扣费设置 -->
                    <div class="setting-group">
                        <label class="setting-label">账户扣费设置：</label>
                        <el-radio-group v-model="accountForm.chargeSetting">
                            <el-radio value="inpatient">住院</el-radio>
                        </el-radio-group>
                    </div>

                    <!-- 信用额度 -->
                    <div class="setting-group">
                        <label class="setting-label">信用额度：</label>
                        <div class="input-with-unit">
                            <el-input v-model="accountForm.creditLimit" type="number" class="number-input" placeholder="0.00" />
                            <span class="unit">元</span>
                        </div>
                    </div>

                    <!-- 最低充值额度 -->
                    <div class="setting-group">
                        <label class="setting-label">最低充值额度：</label>
                        <div class="input-with-unit">
                            <el-input v-model="accountForm.minRechargeAmount" type="number" class="number-input" placeholder="0.00" />
                            <span class="unit">元</span>
                        </div>
                    </div>

                    <!-- 自动扣费设置 -->
                    <div class="setting-group">
                        <label class="setting-label">自动扣费设置：</label>
                        <el-radio-group v-model="accountForm.autoDeduction">
                            <el-radio value="1">开启</el-radio>
                            <el-radio value="0">关闭</el-radio>
                        </el-radio-group>
                    </div>

                    <!-- 充值方式 -->
                    <div class="setting-group">
                        <label class="setting-label">充值方式：</label>
                        <el-checkbox-group v-model="accountForm.rechargeMethod">
                            <el-checkbox value="cash">现金充值</el-checkbox>
                            <el-checkbox value="unionpay">银联充值</el-checkbox>
                        </el-checkbox-group>
                    </div>

                    <!-- 保存按钮 -->
                    <div class="save-button-container">
                        <button class="save-btn" @click="saveAccountSettings">保存</button>
                    </div>
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script setup name="Set" lang="ts">
    import { listSet, getSet, delSet, addSet, updateSet } from '@/api/parameter/chargeSet';
    import { ChargeSetVO, ChargeSetQuery, ChargeSetForm } from '@/api/parameter/chargeSet/types';

    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const { charge_set_servicer, money_charge, fee_type } = toRefs < any > (proxy ?.useDict('charge_set_servicer', 'money_charge', 'fee_type'));

    import { useChargeSetStore } from '@/store/modules/chargeSet';
    const useStore = useChargeSetStore();
    const setList = ref < ChargeSetVO[] > ([]);
    const buttonLoading = ref(false);
    const loading = ref(true);
    const ids = ref < Array < string | number >> ([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);

    const queryFormRef = ref < ElFormInstance > ();
    const ChargeSetFormRef = ref < ElFormInstance > ();

    const dialog = reactive < DialogOption > ({
        visible: false,
        title: ''
    });

    import { ref, reactive } from 'vue';

    // Tab状态
    const activeTab = ref('charge');

    // 表单数据
    const chargeForm = reactive({
        forwardChargeItems: [
            { name: '营养筛查', code: '', price: null },
            { name: '营养评估', code: '', price: null },
            { name: '心理筛查', code: '', price: null },
            { name: '过敏性疾病评估', code: '', price: null },
            { name: '预后评估', code: '', price: null }
        ],
        // 组合收费项目
        combinedChargeItems: [{ name: '营养综合评估', code: '', price: null }],
        prescriptionTypes: ['3', '4'],
    });

    // 账户设置表单数据
    const accountForm = reactive({
        enableAccount: '1',
        chargeSetting: 'inpatient',
        creditLimit: '0.00',
        minRechargeAmount: '0.00',
        autoDeduction: '1',
        rechargeMethod: ['cash', 'unionpay']
    });

    // 订单有效时长增加
    const increaseDuration = () => {
        if (form.value.orderIndate < 365) {
            form.value.orderIndate++;
        }
    };

    // 订单有效时长减少
    const decreaseDuration = () => {
        if (form.value.orderIndate > 1) {
            form.value.orderIndate--;
        }
    };

    const initFormData: ChargeSetForm = {
        chargeId: undefined,
        servicer: '1',
        moneyCharge: '1',
        chargeMode: '1',
        chargeType: 1,
        oneWayCharge: undefined,
        groupCharge: undefined,
        nutritionChargeSet: '1',
        suitRecipe: undefined,
        patientOrderSet: '1',
        orderIndate: undefined,
        multiModeCharge: undefined,
        chargeItemArr: []
    }
    const data = reactive < PageData < ChargeSetForm,
        ChargeSetQuery >> ({
            form: { ...initFormData },
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                servicer: undefined,
                params: {}
            },
            rules: {
                servicer: [
                    { required: true, message: "服务商不能为空", trigger: "blur" }
                ],
                moneyCharge: [
                    { required: true, message: "是否开启现金收费不能为空", trigger: "blur" }
                ],
                chargeMode: [
                    { required: true, message: "收费模式不能为空", trigger: "blur" }
                ],
                chargeType: [
                    { required: true, message: "收费方式 1单项收费 2 组合收费不能为空", trigger: "change" }
                ],
                nutritionChargeSet: [
                    { required: true, message: "营养配置收费设置不能为空", trigger: "blur" }
                ],
                suitRecipe: [
                    { required: true, message: "适合处方类型不能为空", trigger: "blur" }
                ],
            }
        });

    const { queryParams, form, rules } = toRefs(data);

    /** 查询收费设置列表 */
    const getList = async () => {
        loading.value = true;
        const res = await listSet(queryParams.value);
        setList.value = res.rows;

        if (res.rows.length > 0) {
            useStore.setChargeInfo(res.rows[0]);
            // 回显数据到表单
            loadFormData(res.rows[0]);
        } else {
            // 如果没有数据，重置为默认值
            reset();
        }

        total.value = res.total;
        loading.value = false;
    };

    /** 表单重置 */
    const reset = () => {
        form.value = { ...initFormData };
        ChargeSetFormRef.value ?.resetFields();
    };

    /** 加载表单数据（回显） */
    const loadFormData = (data: ChargeSetVO) => {
        if (!data) {
            console.warn('loadFormData: 数据为空');
            return;
        }

        // 回显基本表单数据
        Object.assign(form.value, data);

        // 确保关键字段正确回显（处理数字和字符串兼容性）
        form.value.servicer = String(data.servicer || '1');
        form.value.moneyCharge = String(data.moneyCharge || '1');
        form.value.chargeMode = String(data.chargeMode || '1');
        form.value.nutritionChargeSet = data.nutritionChargeSet || '1';
        form.value.patientOrderSet = String(data.patientOrderSet || '1');
        // 回显收费项目数据（兼容数字和字符串类型的chargeMode）
        if ((data as any).chargeItemArr && (data as any).chargeItemArr.length > 0) {
            const chargeMode = String(data.chargeMode);
            if (chargeMode === '1') {
                chargeForm.forwardChargeItems = (data as any).chargeItemArr;
            } else if (chargeMode === '2') {
                chargeForm.combinedChargeItems = (data as any).chargeItemArr;
            }
        }

        // 回显其他复杂字段
        if (data.suitRecipe) {
            chargeForm.prescriptionTypes = data.suitRecipe.split(',');
        } else {
            // 如果没有处方类型数据，设置默认值
            chargeForm.prescriptionTypes = ['1', '2'];
        }

    };

    /** 搜索按钮操作 */
    const handleQuery = () => {
        queryParams.value.pageNum = 1;
        getList();
    }



    /** 多选框选中数据 */
    const handleSelectionChange = (selection: ChargeSetVO[]) => {
        ids.value = selection.map(item => item.chargeId);
        single.value = selection.length != 1;
        multiple.value = !selection.length;
    }



    /** 提交按钮 */
    const submitForm = async () => {
        if (form.value.chargeMode == '1') {
            (form.value as any).chargeItemArr = chargeForm.forwardChargeItems;
        } else {
            (form.value as any).chargeItemArr = chargeForm.combinedChargeItems;
        }
        // 根据页面选择的复选框动态拼接适合处方类型
        form.value.suitRecipe = chargeForm.prescriptionTypes.join(',');

        buttonLoading.value = true;

        try {
            // 单例配置表：如果已存在数据，则更新；如果不存在，则添加
            if (setList.value.length > 0) {
                // 更新现有的第一条数据
                form.value.chargeId = setList.value[0].chargeId;
                await updateSet(form.value);
            } else {
                // 添加新数据
                await addSet(form.value);
            }

            proxy ?.$modal.msgSuccess("操作成功");
            // 重新获取数据并回显
            await getList();
        } catch (error) {
            console.error('保存失败:', error);
        } finally {
            buttonLoading.value = false;
        }
    };

    /** 保存账户设置 */
    const saveAccountSettings = () => {
        console.log('保存账户设置:', accountForm);
        proxy ?.$modal.msgSuccess('账户设置保存成功');
    };

    onMounted(() => {
        getList();
    });
</script>
<style lang="scss">
    .charge-set-container {
        padding: 20px;
        background: #fff;

        .charge-tabs {
            .el-tabs__content {
                padding: 0;
            }
        }

        .charge-content,
        .account-content {
            .setting-group {
                display: flex;
                align-items: center;
                margin-bottom: 20px;

                .setting-label {
                    width: 180px;
                    color: #606266;
                    font-size: 14px;
                    flex-shrink: 0;
                    text-align: right;

                    .required {
                        color: #f56c6c;
                        margin-right: 4px;
                    }
                }

                .input-with-unit {
                    display: flex;
                    align-items: center;

                    .number-input {
                        width: 100px;
                    }

                    .unit {
                        margin-left: 8px;
                        color: #606266;
                    }
                }

                .duration-setting {
                    display: flex;
                    align-items: center;

                    .duration-btn {
                        width: 32px;
                        height: 32px;
                        padding: 0;
                        border-radius: 0;

                        &:first-child {
                            border-top-left-radius: 4px;
                            border-bottom-left-radius: 4px;
                        }

                        &:last-of-type {
                            border-top-right-radius: 4px;
                            border-bottom-right-radius: 4px;
                            border-left: none;
                        }
                    }

                    .duration-input {
                        width: 60px;

                        :deep(.el-input__wrapper) {
                            border-radius: 0;
                            border-left: none;
                            border-right: none;
                            text-align: center;
                        }
                    }

                    .unit {
                        margin-left: 8px;
                        color: #606266;
                    }
                }
            }
        }

        .table-container {
            margin: 30px 0;

            .charge-table {
                width: 100%;
                border-collapse: collapse;
                border: 1px solid #ebeef5;

                th,
                td {
                    padding: 12px;
                    text-align: left;
                    border-bottom: 1px solid #ebeef5;
                    border-right: 1px solid #ebeef5;

                    &:last-child {
                        border-right: none;
                    }
                }

                th {
                    background: #f5f7fa;
                    color: #909399;
                    font-weight: 500;

                    .required {
                        color: #f56c6c;
                    }
                }

                .table-input {
                    width: 100%;
                    padding: 6px 8px;
                    border: 1px solid #dcdfe6;
                    border-radius: 4px;
                    outline: none;

                    &:focus {
                        border-color: #409eff;
                    }
                }

                .price-cell {
                    display: flex;
                    align-items: center;

                    .price-input {
                        width: 80px;
                        margin-right: 8px;
                    }

                    .unit {
                        color: #606266;
                    }
                }
            }
        }

        .save-button-container {
            display: flex;
            justify-content: center;
            margin-top: 40px;

            .save-btn {
                padding: 12px 40px;
                background: #409eff;
                color: #fff;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;

                &:hover {
                    background: #66b1ff;
                }
            }
        }

        .account-content {
            .placeholder {
                text-align: center;
                color: #909399;
                padding: 60px 0;
                font-size: 16px;
            }
        }
    }
</style>