<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div v-show="showSearch" class="mb-[10px]">
                <el-card shadow="hover">
                    <el-form ref="queryFormRef" :model="queryParams" :inline="true" :label-width="120">
                        <el-form-item label="账户余额范围：" prop="patientId">
                            <el-input v-model="queryParams.patientId" placeholder="请输入患者ID" clearable @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item>
                            <el-input v-model="queryParams.searchValue" placeholder="患者姓名/身份证号" style="width: 240px; " clearable />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>
        </transition>

        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['settlement:accountSettleAccounts:add']">新增</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table v-loading="loading" border :data="accountList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="主键ID" align="center" prop="id" v-if="false" />
                <el-table-column label="账户" align="center" prop="serialNo" />
                <el-table-column label="患者姓名" align="center" prop="patientName" />
                <el-table-column label="联系电话" align="center" prop="phone" />
                <el-table-column label="身份证号" align="center" prop="idCard" />
                <el-table-column label="授信金额" align="center" prop="creditAmount" />
                <el-table-column label="可用授信额度" align="center" prop="creditLimit" />
                <el-table-column label="账户充值" align="center" prop="totalIncome" />
                <el-table-column label="账户余额" align="center" prop="totalAmount" />
                <el-table-column label="账户消费" align="center" prop="totalExpand" />
                <el-table-column label="待缴金额" align="center" prop="unpaidAmount" />
                <el-table-column label="待处理事项" align="center" prop="waitingTask" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="260px">
                    <template #default="scope">
                        <el-tooltip content="充值" placement="top">
                            <el-button link type="primary" @click="handleIncome(scope.row)" v-hasPermi="['settlement:accountSettleAccounts:edit']">充值</el-button>
                        </el-tooltip>
                        <el-tooltip content="详情" placement="top">
                            <el-button link type="primary" @click="handleDetail(scope.row)" v-hasPermi="['settlement:accountSettleAccounts:add']">详情</el-button>
                        </el-tooltip>
                        <el-tooltip content="出院结算" placement="top">
                            <el-button link type="primary"  v-hasPermi="['settlement:accountSettleAccounts:remove']">出院结算</el-button>
                        </el-tooltip>
                        <el-tooltip content="授信额度" placement="top">
                            <el-button link type="primary" @click="handleCredit(scope.row)" v-hasPermi="['settlement:accountSettleAccounts:remove']">授信额度</el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>
        <!-- 账户充值对话框 -->
        <el-dialog :title="dialog.title" v-model="dialog.visible" width="40%" append-to-body>
            <el-form ref="accountIncomeFormRef" :model="{ totalIncome, rechargeIncome, currentChargeMode, remark: form.remark }" :rules="incomeRules" label-width="80px">
                <div class="patient-info">
                    <el-row :gutter="20">
                        <el-col :span="5">
                            <div class="info-item">
                                <span class="label">姓名：</span>
                                <span class="value">{{ form.patientName  || '' }}</span>
                            </div>
                        </el-col>
                        <el-col :span="5">
                            <div class="info-item">
                                <span class="label">性别：</span>
                                <span class="value">{{ form.sex=='1'?'男':'女' }}</span>
                            </div>
                        </el-col>
                        <el-col :span="5">
                            <div class="info-item">
                                <span class="label">身份证号：</span>
                                <span class="value">{{ form.idCard || '' }}</span>
                            </div>
                        </el-col>

                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="4">
                            <div class="info-item">
                                <span class="label">余额(元)：</span>
                                <span class="value">{{ form.totalAmount || '0.00' }}</span>
                            </div>
                        </el-col>
                        <el-col :span="5">
                            <div class="info-item">
                                <span class="label">待缴金额(元)：</span>
                                <span class="value">{{ form.unpaidAmount || '0.00' }}</span>
                            </div>
                        </el-col>
                    </el-row>
                    <el-form-item prop="currentChargeMode">
                        <div class="setting-group">
                            <label class="setting-label">
                                <span class="required">*</span>
                                充值方式：
                            </label>
                            <el-radio-group v-model="currentChargeMode">
                                <el-radio v-for="dict in filteredChargeWay" :key="dict.value" :value="dict.value">
                                    {{ dict.label }}
                                </el-radio>
                            </el-radio-group>
                        </div>
                    </el-form-item>
                    <el-form-item prop="totalIncome">
                        <div class="setting-group">
                            <label class="setting-label">
                                <span class="required">*</span>
                                充值金额(元)：
                            </label>
                            <el-input style="width:260px" v-model="totalIncome" placeholder="请输入" />
                        </div>
                    </el-form-item>
                    <el-form-item prop="rechargeIncome">
                        <div class="setting-group">
                            <label class="setting-label">
                                <span class="required">*</span>
                                确认充值金额(元)：
                            </label>
                            <el-input style="width:260px" v-model="rechargeIncome" placeholder="请输入" />
                        </div>
                    </el-form-item>
                    <el-form-item prop="remark">
                        <div class="setting-group">
                            <label class="setting-label">
                                备注：
                            </label>
                            <el-input style="width:260px" v-model="form.remark" type="textarea" :rows="5" placeholder="请输入" />
                        </div>
                    </el-form-item>
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-if="showQRCodeButton" :loading="buttonLoading" type="primary">二维码支付</el-button>
                    <el-button v-if="showQRCodeButton" :loading="buttonLoading" type="primary">扫码枪支付</el-button>
                    <el-button :loading="buttonLoading" type="primary" @click="handleAddIncome">确认</el-button>
                    <el-button :loading="buttonLoading" @click="incomeDialogCancel">取消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 授信对话框 -->
        <el-dialog :title="creditDialog.title" v-model="creditDialog.visible" width="40%" append-to-body>
            <el-form ref="creditFormRef" :model="{ creditAmount: form.creditAmount }" :rules="creditRules" label-width="80px">
                <div class="patient-info">
                    <el-row :gutter="20">
                        <el-col :span="5">
                            <div class="info-item">
                                <span class="label">姓名：</span>
                                <span class="value">{{ form.patientName  || '' }}</span>
                            </div>
                        </el-col>
                        <el-col :span="5">
                            <div class="info-item">
                                <span class="label">性别：</span>
                                <span class="value">{{ form.sex=='1'?'男':'女' }}</span>
                            </div>
                        </el-col>
                        <el-col :span="5">
                            <div class="info-item">
                                <span class="label">身份证号：</span>
                                <span class="value">{{ form.idCard || '' }}</span>
                            </div>
                        </el-col>
                    </el-row>
                
                    <el-form-item prop="creditAmount">
                        <div class="setting-group">
                            <label class="setting-label">
                                <span class="required">*</span>
                                原授信额度(元)：
                            </label>
                            <span>{{ form.creditAmount||'0.00' }}</span>
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <div class="setting-group">
                            <label class="setting-label">
                                <span class="required">*</span>
                                修改后授信额度(元)：
                            </label>
                            <el-input style="width:260px" v-model="creditAmount" placeholder="请输入" />
                        </div>
                    </el-form-item>

                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="handleAddCredit">确认</el-button>
                    <el-button :loading="buttonLoading" @click="creditDialogCancel">取消</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup name="Account" lang="ts">
    import { listAccount, getAccount, delAccount, addAccount, updateAccount } from '@/api/settlement/accountSettlementAccounts';
    import { AccountVO, AccountQuery, AccountForm } from '@/api/settlement/accountSettlementAccounts/types';
    import { ChargeSetVO } from '@/api/parameter/chargeSet/types';
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const { user_sex, charge_way } = toRefs < any > (proxy ?.useDict('user_sex', 'charge_way'));
    import { useChargeSetStore } from '@/store/modules/chargeSet';
    const useStore = useChargeSetStore();
    import { usePatientAccountStore } from '@/store/modules/settlementAccount';
    const useAccountStore = usePatientAccountStore();
    const chargeSetInfo = computed(() => useStore.chargeSetInfo as ChargeSetVO || {} as ChargeSetVO);
    const accountList = ref < AccountVO[] > ([]);
    const buttonLoading = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref < Array < string | number >> ([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const rowData = ref < AccountVO > ({} as any)
    const router = useRouter();
    const currentChargeMode = ref('1'); // 当前选择的充值方式，默认为现金收费
    // 是否显示二维码支付按钮 - 只有选择银联支付(值为2)时才显示
    const showQRCodeButton = computed(() => currentChargeMode.value === '2');
    const queryFormRef = ref < ElFormInstance > ();
    const accountFormRef = ref < ElFormInstance > ();
    const accountIncomeFormRef = ref < ElFormInstance > ();
    const creditFormRef = ref < ElFormInstance > ();
    const totalIncome = ref(0); //定义充值金额
    const rechargeIncome = ref(0); //定义确认充值金额
    const creditAmount = ref(0); //定义修改后授信额度
    const dialog = reactive < DialogOption > ({
        visible: false,
        title: ''
    });
    const creditDialog = reactive < DialogOption > ({
        visible: false,
        title: ''
    });

    const initFormData: AccountForm = {
        id: undefined,
        patientId: undefined,
        patientName: undefined,
        patientCaseId: undefined,
        idCard: undefined,
        sex: undefined,
        phone: undefined,
        serialNo: undefined,
        totalAmount: undefined,
        totalIncome: undefined,
        totalExpand: undefined,
        unpaidAmount: undefined,
        availableAmount: undefined,
        creditAmount: undefined,
        creditLimit: undefined,
        status: undefined,
        activated: undefined,
        remark: undefined,
        waitingTask: undefined
    }
    const data = reactive < PageData < AccountForm,
        AccountQuery >> ({
            form: { ...initFormData },
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                searchValue: undefined,
                params: {}
            },
            rules: {
                id: [
                    { required: true, message: "主键ID不能为空", trigger: "blur" }
                ],
            },
        });

    // 充值表单验证规则
    const incomeRules = reactive({
        totalIncome: [
            { required: true, message: "充值金额不能为空", trigger: "blur" },
            { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的金额格式", trigger: "blur" }
        ],
        rechargeIncome: [
            { required: true, message: "确认充值金额不能为空", trigger: "blur" },
            { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的金额格式", trigger: "blur" },
            {
                validator: (rule: any, value: any, callback: any) => {
                    const totalAmount = parseFloat(String(totalIncome.value)) || 0;
                    const rechargeAmount = parseFloat(String(value)) || 0;
                    if (rechargeAmount !== totalAmount) {
                        callback(new Error('输入的两次充值金额不一样，请重新输入'));
                    } else {
                        callback();
                    }
                },
                trigger: "blur"
            }
        ],
        currentChargeMode: [
            { required: true, message: "请选择充值方式", trigger: "change" }
        ],
    });
    // 充值表单验证规则
    const creditRules = reactive({
        creditAmount: [
            { required: true, message: "修改后授信额度不能为空", trigger: "blur" },
            { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的金额格式", trigger: "blur" }

        ],

    });

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

    /** 查询患者账户信息列表 */
    const getList = async () => {
        loading.value = true;
        const res = await listAccount(queryParams.value);
        accountList.value = res.rows;
        total.value = res.total;
        loading.value = false;
    }
    // 字典label工具
    function getDictLabel(dictList: any[], value: string) {
        if (!dictList || !Array.isArray(dictList)) return value || '--';
        const found = dictList.find((item) => item.value === value);
        return found ? found.label : value || '--';
    }
    /** 取消按钮 */
    const cancel = () => {
        reset();
        dialog.visible = false;
    }

    /** 表单重置 */
    const reset = () => {
        form.value = { ...initFormData };
        totalIncome.value = 0;
        rechargeIncome.value = 0;
        currentChargeMode.value = '1';
        accountFormRef.value ?.resetFields();
        accountIncomeFormRef.value ?.resetFields();
    }

    // 过滤收费方式选项
    const filteredChargeWay = computed(() => {
        if (!charge_way.value) return [];

        return charge_way.value.filter(dict => {
            // 银联支付(值为2)始终显示
            if (dict.value === '2') {
                return true;
            }
            // 现金收费(值为1)只有在 chargeSetInfo.moneyCharge = 1 时才显示
            if (dict.value === '1') {
                return chargeSetInfo.value ?.moneyCharge === 1 || chargeSetInfo.value ?.moneyCharge === '1';
            }
            // 其他选项不显示
            return false;
        });
    });

    const handleDetail = (row ? : AccountVO) => {
        useAccountStore.setAccountInfo(row)
        router.push('/settlement/accountDetail/' + row.id);
    }

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

    /** 重置按钮操作 */
    const resetQuery = () => {
        queryFormRef.value ?.resetFields();
        handleQuery();
    }

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

    /** 新增按钮操作 */
    const handleAdd = () => {
        reset();
        dialog.visible = true;
        dialog.title = "添加患者账户信息";
    }

    /** 充值按钮操作 */
    const handleIncome = async (row ? : AccountVO) => {
        reset();
        const _id = row ?.id || ids.value[0]
        const res = await getAccount(_id);
        Object.assign(form.value, res.data);
        // 设置默认收费方式为现金收费(值为1)，如果现金收费可选的话
        const availableOptions = filteredChargeWay.value;
        const cashOption = availableOptions.find(option => option.value === '1');
        if (cashOption) {
            currentChargeMode.value = '1';
        } else if (availableOptions.length > 0) {
            // 如果没有现金收费选项，默认选择第一个可用选项
            currentChargeMode.value = availableOptions[0].value;
        }
        dialog.visible = true;
        dialog.title = "充值";
    }

    const handleAddIncome = () => {
        // 先进行表单验证
        accountIncomeFormRef.value ?.validate(async (valid: boolean) => {
            if (valid) {
                try {
                    buttonLoading.value = true;

                    // 构建充值数据
                    const incomeData = {
                        ...form.value,
                        totalIncome: Number(totalIncome.value),
                        totalAmount: (form.value.totalAmount || 0) + Number(totalIncome.value),
                        paymentMethod: currentChargeMode.value
                    };

                    // 发送充值请求
                    if (form.value.id) {
                        await updateAccount(incomeData);
                    }

                    proxy ?.$modal.msgSuccess('充值成功');
                    dialog.visible = false;
                    await getList();
                } catch (error) {
                    console.error('充值失败:', error);
                    proxy ?.$modal.msgError('充值失败，请重试');
                } finally {
                    buttonLoading.value = false;
                }
            } else {
                proxy ?.$modal.msgWarning('请完善表单信息');
            }
        });
    }
    const incomeDialogCancel = () => {
        dialog.visible = false
    }
    const creditDialogCancel = () => {
        creditDialog.visible = false
    }
    /** 充值按钮操作 */
    const handleCredit = async (row ? : AccountVO) => {
        reset();
        const _id = row ?.id || ids.value[0]
        const res = await getAccount(_id);
        Object.assign(form.value, res.data);
        creditDialog.visible = true;
        creditDialog.title = "授信额度";
    }

    const handleAddCredit = () => {
        // 先进行表单验证
        creditFormRef.value ?.validate(async (valid: boolean) => {
            if (valid) {
                try {
                    buttonLoading.value = true;

                    // 构建授信数据
                    const creditData = {
                        ...form.value,
                        creditAmount: Number(creditAmount.value)
                    };

                    // 发送充值请求
                    if (form.value.id) {
                        await updateAccount(creditData);
                    }

                    proxy ?.$modal.msgSuccess('操作成功');
                    creditDialog.visible = false;
                    creditAmount.value = 0;
                    await getList();
                } catch (error) {
                    console.error('操作失败:', error);
                    proxy ?.$modal.msgError('操作失败，请重试');
                } finally {
                    buttonLoading.value = false;
                }
            }
        });
    }

    /** 提交按钮 */
    const submitForm = () => {
        accountFormRef.value ?.validate(async (valid: boolean) => {
            if (valid) {
                buttonLoading.value = true;
                if (form.value.id) {
                    await updateAccount(form.value).finally(() => buttonLoading.value = false);
                } else {
                    await addAccount(form.value).finally(() => buttonLoading.value = false);
                }
                proxy ?.$modal.msgSuccess("操作成功");
                dialog.visible = false;
                await getList();
            }
        });
    }

    /** 删除按钮操作 */
    const handleDelete = async (row ? : AccountVO) => {
        const _ids = row ?.id || ids.value;
        await proxy ?.$modal.confirm('是否确认删除患者账户信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
        await delAccount(_ids);
        proxy ?.$modal.msgSuccess("删除成功");
        await getList();
    }

    /** 导出按钮操作 */
    const handleExport = () => {
        proxy ?.download('system/account/export', {
            ...queryParams.value
        }, `account_${new Date().getTime()}.xlsx`)
    }

    onMounted(() => {
        getList();
    });
</script>
<style lang="scss" scoped>
    .patient-info {
        background-color: #f5f7fa;
        padding: 16px;
        border-radius: 4px;
        margin-bottom: 20px;
    }

    .info-item {
        display: flex;
        margin-bottom: 12px;
    }

    .info-item .label {
        font-weight: bold;
        color: #606266;
        min-width: 100px;
        flex-shrink: 0;
    }

    .info-item .value {
        color: #303133;
        flex: 1;
    }

    .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;
            }
        }
    }
</style>