<template>
    <view class="refund-review-page">
        <!-- 顶部导航栏 -->
        <view class="nav-header">
            <view class="nav-back-btn" @tap="onBack">
                <text class="back-text">返回</text>
            </view>
            <text class="nav-title">退费审核</text>
            <view class="nav-placeholder"></view>
        </view>

        <!-- 查询条件栏 -->
        <view class="filter-bar">
            <view class="filter-row">
                <picker class="filter-date-picker" mode="date" :value="startDate" @change="onStartDateChange">
                    <view class="date-input">
                        <text class="date-text" :class="{ 'date-placeholder': !startDate }">{{ startDate || '开始日期' }}</text>
                        <view class="date-icon"></view>
                    </view>
                </picker>
                <text class="filter-to">至</text>
                <picker class="filter-date-picker" mode="date" :value="endDate" @change="onEndDateChange">
                    <view class="date-input">
                        <text class="date-text" :class="{ 'date-placeholder': !endDate }">{{ endDate || '结束日期' }}</text>
                        <view class="date-icon"></view>
                    </view>
                </picker>
                <view class="query-btn" @tap="onQuery">
                    <text class="query-btn-text">查 询</text>
                </view>
            </view>
            <view class="filter-chips">
                <view
                    class="filter-chip"
                    :class="{ 'filter-chip-active': filterStatus === opt.value }"
                    v-for="opt in statusOptions"
                    :key="opt.label"
                    @tap="onSelectStatus(opt)"
                >
                    <text class="filter-chip-text">{{ opt.label }}</text>
                </view>
            </view>
        </view>

        <!-- 退费申请列表 -->
        <view class="page-content">
            <view class="refund-list">
                <view class="refund-card" v-for="(item, index) in displayList" :key="index">
                    <!-- 头部：头像 + 姓名 + 状态 -->
                    <view class="card-header">
                        <view class="header-left">
                            <view class="avatar-circle">
                                <text class="avatar-text">{{ item.avatar }}</text>
                            </view>
                            <text class="patient-name">{{ item.name }}</text>
                        </view>
                        <view class="status-tag" :class="item.statusClass">
                            <text class="status-tag-text">{{ item.statusText }}</text>
                        </view>
                    </view>

                    <!-- 分隔线 -->
                    <view class="card-divider"></view>

                    <!-- 明细 -->
                    <view class="card-body">
                        <view class="info-row" v-if="item.dept">
                            <text class="info-label">就诊科室</text>
                            <text class="info-value">{{ item.dept }}</text>
                        </view>
                        <view class="info-row" v-if="item.doctor">
                            <text class="info-label">接诊医生</text>
                            <text class="info-value">{{ item.doctor }}</text>
                        </view>
                        <view class="info-row" v-if="item.admDate">
                            <text class="info-label">就诊日期</text>
                            <text class="info-value">{{ item.admDate }}</text>
                        </view>
                        <view class="info-row" v-if="item.tradeNo">
                            <text class="info-label">交易单号</text>
                            <text class="info-value">{{ item.tradeNo }}</text>
                        </view>
                        <view class="info-row" v-if="item.refundItem">
                            <text class="info-label">退费项目</text>
                            <text class="info-value">{{ item.refundItem }}</text>
                        </view>
                        <view class="info-row" v-if="item.refundAmount">
                            <text class="info-label">退费金额</text>
                            <text class="info-value">¥{{ item.refundAmount }}</text>
                        </view>
                        <view class="info-row" v-if="item.refundReason">
                            <text class="info-label">退费原因</text>
                            <text class="info-value">{{ item.refundReason }}</text>
                        </view>
                        <view class="info-row">
                            <text class="info-label">申请时间</text>
                            <text class="info-value">{{ item.applyTime }}</text>
                        </view>
                    </view>

                    <!-- 操作按钮：仅“申请”状态可审核 -->
                    <view class="card-actions" v-if="item.statusKey === 'pending'">
                        <view class="action-btn action-btn-pass" @tap="onPass(item)">
                            <text class="action-btn-text action-btn-text-pass">审核通过</text>
                        </view>
                        <view class="action-btn action-btn-reject" @tap="onReject(item)">
                            <text class="action-btn-text action-btn-text-reject">驳回</text>
                        </view>
                    </view>
                </view>
            </view>
            <view class="empty-tip" v-if="loading">
                <text class="empty-tip-text">加载中...</text>
            </view>
            <view class="empty-tip" v-else-if="displayList.length === 0">
                <text class="empty-tip-text">暂无符合条件的退费申请</text>
            </view>
        </view>

        <!-- 审核通过确认弹窗 -->
        <view class="dialog-mask" v-if="showPassDialog" @tap="closePassDialog">
            <view class="dialog-content" @tap.stop>
                <text class="dialog-title">确认审核通过？</text>
                <text class="dialog-desc">通过后系统将通知患者，患者可在患者端发起退款。</text>
                <view class="dialog-actions">
                    <view class="dialog-btn dialog-btn-cancel" @tap="closePassDialog">
                        <text class="dialog-btn-text dialog-btn-text-cancel">取消</text>
                    </view>
                    <view class="dialog-btn dialog-btn-confirm dialog-btn-pass" @tap="confirmPass">
                        <text class="dialog-btn-text dialog-btn-text-confirm">确认通过</text>
                    </view>
                </view>
            </view>
        </view>

        <!-- 驳回退款申请弹窗 -->
        <view class="dialog-mask" v-if="showRejectDialog" @tap="closeRejectDialog">
            <view class="dialog-content" @tap.stop>
                <text class="dialog-title">确认驳回退款申请？</text>
                <text class="dialog-desc">驳回后系统将通知患者。</text>
                <view class="dialog-actions">
                    <view class="dialog-btn dialog-btn-cancel" @tap="closeRejectDialog">
                        <text class="dialog-btn-text dialog-btn-text-cancel">取消</text>
                    </view>
                    <view class="dialog-btn dialog-btn-confirm dialog-btn-reject" @tap="confirmReject">
                        <text class="dialog-btn-text dialog-btn-text-confirm">确认驳回</text>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { $http } from '../../../config/https.js';
import Cache from '../../../utils/cache.js';

// 接口编码
const API_CODE = {
    list: '05210086', // 查询退费列表
    audit: '05100397' // 退费审核（status: 01-审核通过 02-拒绝）
};
// 审核状态入参
const AUDIT_STATUS = {
    pass: '01',
    reject: '02'
};

export default {
    data() {
        return {
            // 退费申请列表（接口返回）
            refundList: [],
            // 加载状态
            loading: false,
            // 提交状态（防止重复提交）
            submitting: false,
            // 查询条件
            startDate: '',
            endDate: '',
            statusOptions: [
                // { label: '全部', value: '' },
                { label: '申请', value: '113||832' },
                { label: '审核通过', value: '113||833' },
                { label: '拒绝', value: '113||834' }
            ],
            // 默认查询「申请」状态
            filterStatus: '113||832',
            // 弹窗状态
            showPassDialog: false,
            showRejectDialog: false,
            // 当前操作的申请项
            currentItem: null
        };
    },
    computed: {
        displayList() {
            return this.refundList;
        }
    },
    onLoad() {
        // 默认查询近 30 天
        const end = new Date();
        const start = new Date();
        start.setDate(start.getDate() - 30);
        this.endDate = this.formatDate(end);
        this.startDate = this.formatDate(start);
        this.loadRefundList();
    },
    methods: {
        // 格式化日期 YYYY-MM-DD
        formatDate(date) {
            const y = date.getFullYear();
            const m = String(date.getMonth() + 1).padStart(2, '0');
            const d = String(date.getDate()).padStart(2, '0');
            return `${y}-${m}-${d}`;
        },
        // 登录用户信息（列表接口需要 locID / docID）
        getUserParams() {
            const userData = Cache.get('userData') || {};
            return {
                locID: userData.locID || '',
                docID: userData.userID || ''
            };
        },
        // 状态文案 -> 状态标识（pending 可操作）
        getStatusKey(text) {
            const s = String(text || '').trim();
            if (!s) return 'pending';
            if (s.indexOf('申请') > -1 || s.indexOf('待审') > -1 || s.indexOf('审核中') > -1) return 'pending';
            if (s.indexOf('通过') > -1 || s.indexOf('同意') > -1) return 'passed';
            if (s.indexOf('拒绝') > -1 || s.indexOf('驳回') > -1) return 'rejected';
            return 'other';
        },
        // 接口数据 -> 页面展示数据
        mapRefundItem(item) {
            const statusText = item.status || '';
            const statusKey = this.getStatusKey(statusText);
            return Object.assign({}, item, {
                appID: item.appID || '',
                avatar: (item.patName || '').substring(0, 1) || '?',
                name: item.patName || '',
                dept: item.admLocDesc || '',
                doctor: item.admDocDesc || '',
                admDate: item.admDate || '',
                tradeNo: item.hisTradeNum || '',
                statusText: statusText || '未知',
                statusKey: statusKey,
                statusClass: 'status-' + statusKey,
                applyTime: [item.createDate, item.createTime].filter(Boolean).join(' '),
                refundItem: item.refundItem || item.itemDesc || '',
                refundAmount: item.refundAmount || item.amt || item.totalAmt || '',
                refundReason: item.refundReason || item.reason || ''
            });
        },
        // 查询退费列表
        loadRefundList() {
            const that = this;
            if (that.loading) return;
            that.loading = true;
            const params = Object.assign({}, that.getUserParams(), {
                startDate: that.startDate,
                stopDate: that.endDate,
                status: that.filterStatus
            });
            $http.post('urlDeault', this, {
                code: API_CODE.list,
                data: { params: [params] },
                success: function (res) {
                    that.loading = false;
                    if (res.errorCode != '0') return;
                    const result = res.result || [];
                    // 兼容 result 为数组或对象两种返回形式
                    const list = Array.isArray(result) ? result : result.list || result.data || [];
                    that.refundList = (Array.isArray(list) ? list : []).map(item => that.mapRefundItem(item));
                },
                fail: function () {
                    that.loading = false;
                }
            });
        },
        // 提交审核（01-通过 02-拒绝）
        submitAudit(auditStatus) {
            const that = this;
            const item = that.currentItem;
            if (!item) return;
            if (!item.appID) {
                uni.showToast({ title: '数据异常，缺少申请ID', icon: 'none' });
                return;
            }
            if (that.submitting) return;
            that.submitting = true;
            $http.post('urlDeault', this, {
                code: API_CODE.audit,
                data: {
                    params: [
                        {
                            status: auditStatus,
                            refundAppData: [String(item.appID)]
                        }
                    ]
                },
                success: function (res) {
                    that.submitting = false;
                    if (res.errorCode != '0') return;
                    uni.showToast({ title: res.errorMessage || '操作成功', icon: 'success' });
                    that.showPassDialog = false;
                    that.showRejectDialog = false;
                    that.currentItem = null;
                    // 审核后刷新列表
                    that.loadRefundList();
                },
                fail: function () {
                    that.submitting = false;
                }
            });
        },
        onBack() {
            uni.navigateBack();
        },
        onStartDateChange(e) {
            this.startDate = e.detail.value;
        },
        onEndDateChange(e) {
            this.endDate = e.detail.value;
        },
        onSelectStatus(opt) {
            if (this.filterStatus === opt.value) return;
            this.filterStatus = opt.value;
            this.loadRefundList();
        },
        onQuery() {
            if (this.startDate && this.endDate && this.startDate > this.endDate) {
                uni.showToast({ title: '开始日期不能晚于结束日期', icon: 'none' });
                return;
            }
            this.loadRefundList();
        },
        onPass(item) {
            this.currentItem = item;
            this.showPassDialog = true;
        },
        onReject(item) {
            this.currentItem = item;
            this.showRejectDialog = true;
        },
        closePassDialog() {
            this.showPassDialog = false;
            this.currentItem = null;
        },
        closeRejectDialog() {
            this.showRejectDialog = false;
            this.currentItem = null;
        },
        confirmPass() {
            if (!this.currentItem) return;
            this.submitAudit(AUDIT_STATUS.pass);
        },
        confirmReject() {
            if (!this.currentItem) return;
            this.submitAudit(AUDIT_STATUS.reject);
        }
    }
};
</script>

<style scoped>
.refund-review-page {
    min-height: 100vh;
    background-color: #f5f6f8;
}

/* 顶部导航栏 */
.nav-header {
    height: 88rpx;
    background: linear-gradient(135deg, #4a9fff 0%, #2B84FF 100%);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24rpx;
    padding-top: var(--status-bar-height, 44rpx);
}

.nav-back-btn {
    width: 120rpx;
    height: 48rpx;
    display: flex;
    align-items: center;
    justify-content: flex-start;
}

.back-text {
    font-size: 28rpx;
    color: #ffffff;
}

.nav-title {
    font-size: 34rpx;
    font-weight: 600;
    color: #ffffff;
    flex: 1;
    text-align: center;
}

.nav-placeholder {
    width: 120rpx;
    height: 48rpx;
}

/* 内容区 */
.page-content {
    padding: 20rpx 24rpx;
}

/* 查询条件栏 */
.filter-bar {
    background: #f5f6f8;
    padding: 20rpx 24rpx;
    display: flex;
    flex-direction: column;
    gap: 20rpx;
}

.filter-row {
    display: flex;
    flex-direction: row;
    align-items: center;
}

.filter-to {
    font-size: 26rpx;
    color: #1f2329;
    margin: 0 12rpx;
    flex-shrink: 0;
}

.filter-date-picker {
    flex: 1;
}

.date-input {
    height: 64rpx;
    background: #ffffff;
    border-radius: 12rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 0 16rpx;
}

.date-text {
    font-size: 26rpx;
    color: #1f2329;
}

.date-placeholder {
    color: #b4b8c0;
}

.date-icon {
    width: 26rpx;
    height: 26rpx;
    border: 2rpx solid #e84747;
    border-radius: 4rpx;
    position: relative;
    flex-shrink: 0;
}

.date-icon::before {
    content: '';
    position: absolute;
    top: -7rpx;
    left: 3rpx;
    right: 3rpx;
    height: 3rpx;
    background: #e84747;
}

.date-icon::after {
    content: '17';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 14rpx;
    line-height: 1;
    color: #e84747;
}

.query-btn {
    width: 128rpx;
    height: 64rpx;
    background: #2B84FF;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    margin-left: 16rpx;
}

.query-btn-text {
    font-size: 26rpx;
    font-weight: 500;
    color: #ffffff;
}

/* 状态筛选标签 */
.filter-chips {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 20rpx;
    flex-wrap: wrap;
}

.filter-chip {
    height: 56rpx;
    padding: 0 32rpx;
    background: #e9ebee;
    border-radius: 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.filter-chip-active {
    background: #2B84FF;
}

.filter-chip-text {
    font-size: 26rpx;
    color: #1f2329;
}

.filter-chip-active .filter-chip-text {
    color: #ffffff;
}

/* 空状态 */
.empty-tip {
    padding: 80rpx 0;
    display: flex;
    justify-content: center;
}

.empty-tip-text {
    font-size: 26rpx;
    color: #8b98a8;
}

.refund-list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
}

/* 卡片 */
.refund-card {
    background: #ffffff;
    border-radius: 16rpx;
    padding: 24rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
}

/* 头部 */
.card-header {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
}

.header-left {
    display: flex;
    flex-direction: row;
    align-items: center;
}

.avatar-circle {
    width: 72rpx;
    height: 72rpx;
    border-radius: 50%;
    background: #e8f1ff;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16rpx;
}

.avatar-text {
    font-size: 32rpx;
    font-weight: 600;
    color: #2B84FF;
}

.patient-name {
    font-size: 32rpx;
    font-weight: 600;
    color: #1f2329;
}

/* 状态标签 */
.status-tag {
    padding: 6rpx 18rpx;
    border-radius: 20rpx;
}

.status-pending {
    background: #fff4e6;
}

.status-pending .status-tag-text {
    color: #ff8c42;
    font-size: 24rpx;
}

.status-passed {
    background: #e6f7eb;
}

.status-passed .status-tag-text {
    color: #2ea44f;
    font-size: 24rpx;
}

.status-rejected {
    background: #fdecec;
}

.status-rejected .status-tag-text {
    color: #e84747;
    font-size: 24rpx;
}

.status-other {
    background: #f2f3f5;
}

.status-other .status-tag-text {
    color: #8b98a8;
    font-size: 24rpx;
}

/* 分隔线 */
.card-divider {
    height: 1rpx;
    background: #f0f2f5;
    margin: 20rpx 0;
}

/* 明细 */
.card-body {
    display: flex;
    flex-direction: column;
    gap: 14rpx;
}

.info-row {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    font-size: 28rpx;
}

.info-label {
    width: 160rpx;
    color: #8b98a8;
    flex-shrink: 0;
}

.info-value {
    flex: 1;
    color: #1f2329;
    word-break: break-all;
}

/* 操作按钮 */
.card-actions {
    display: flex;
    flex-direction: row;
    gap: 20rpx;
    margin-top: 24rpx;
}

.action-btn {
    flex: 1;
    height: 72rpx;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.action-btn-pass {
    background: #e6f7eb;
}

.action-btn-reject {
    background: #fdecec;
}

.action-btn-text {
    font-size: 28rpx;
    font-weight: 600;
}

.action-btn-text-pass {
    color: #2ea44f;
}

.action-btn-text-reject {
    color: #e84747;
}

/* 弹窗 */
.dialog-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
}

.dialog-content {
    width: 560rpx;
    background: #ffffff;
    border-radius: 24rpx;
    padding: 40rpx 32rpx 32rpx;
    display: flex;
    flex-direction: column;
}

.dialog-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #1f2329;
    margin-bottom: 20rpx;
}

.dialog-desc {
    font-size: 28rpx;
    color: #666666;
    line-height: 1.6;
    margin-bottom: 32rpx;
}

.dialog-input-wrap {
    width: 100%;
    height: 180rpx;
    background: #f7f8fa;
    border-radius: 12rpx;
    padding: 20rpx;
    box-sizing: border-box;
    margin-bottom: 32rpx;
}

.dialog-textarea {
    width: 100%;
    height: 100%;
    font-size: 28rpx;
    color: #1f2329;
    line-height: 1.5;
}

.dialog-textarea-placeholder {
    font-size: 28rpx;
    color: #b4b8c0;
}

.dialog-actions {
    display: flex;
    flex-direction: row;
    gap: 24rpx;
}

.dialog-btn {
    flex: 1;
    height: 80rpx;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.dialog-btn-cancel {
    background: #f2f3f5;
}

.dialog-btn-confirm {
    background: #2B84FF;
}

.dialog-btn-pass {
    background: #2B84FF;
}

.dialog-btn-reject {
    background: #ff4d4f;
}

.dialog-btn-text {
    font-size: 28rpx;
    font-weight: 500;
}

.dialog-btn-text-cancel {
    color: #666666;
}

.dialog-btn-text-confirm {
    color: #ffffff;
}
</style>
