<template>
    <view class="history-diagnosis">
        <view class="hd-header">
            <view class="hd-header-left">
                <picker @change="bindPickerChange" range-key="descripts" :value="index" :range="templateType">
                    <view class="hd-picker">
                        <text>{{ templateType[index].descripts }}</text>
                        <mp-icon type="outline" icon="arrow" color="#999" :size="12"></mp-icon>
                    </view>
                </picker>
            </view>
        </view>

        <view class="hd-body">
            <!-- 左侧就诊列表 -->
            <view class="hd-left">
                <scroll-view scroll-y class="hd-left-scroll">
                    <view v-if="admList.length === 0" class="hd-empty">
                        <text>暂无历史就诊记录</text>
                    </view>
                    <radio-group @change="radioChange">
                        <view
                            class="hd-visit-item"
                            :class="{ 'hd-visit-item--active': item.checked }"
                            v-for="(item, index) in admList"
                            :key="index"
                        >
                            <radio :id="item.admID" hidden :value="item.admID" :checked="item.checked"></radio>
                            <label :for="item.admID" class="hd-visit-label">
                                <view class="hd-visit-date">{{ item.admDate }}</view>
                                <view class="hd-visit-loc">{{ item.admLocDesc }}</view>
                            </label>
                        </view>
                    </radio-group>
                </scroll-view>
            </view>

            <!-- 右侧诊断列表 -->
            <view class="hd-right">
                <scroll-view scroll-y class="hd-right-scroll">
                    <view v-if="isHistoryDiagLoading" class="hd-loading">
                        <view class="hd-loading__spinner"></view>
                        <text>加载中...</text>
                    </view>
                    <view v-else-if="diagDetailList.length === 0" class="hd-empty">
                        <text>请选择左侧就诊记录</text>
                    </view>
                    <view v-else class="diag-list">
                        <view
                            class="diag-item"
                            :class="{ 'diag-item--selected': isSelected(item, index) }"
                            v-for="(item, index) in diagDetailList"
                            :key="getItemKey(item, index)"
                            @tap="toggleItem(item, index)"
                        >
                            <view class="diag-item__info">
                                <text class="diag-item__title">{{ item.diagDesc || item.descripts }}</text>
                                <text class="diag-item__code" v-if="item.diagCode">{{ item.diagCode }}</text>
                            </view>
                            <view class="diag-item__checkbox" @tap.stop="toggleItem(item, index)">
                                <view
                                    class="custom-checkbox"
                                    :class="{ 'custom-checkbox--checked': isSelected(item, index) }"
                                >
                                    <text v-if="isSelected(item, index)" class="custom-checkbox__icon">✓</text>
                                </view>
                            </view>
                        </view>
                    </view>
                </scroll-view>
            </view>
        </view>

        <!-- 底部按钮 -->
        <view class="hd-footer">
            <view class="hd-footer-tip">
                已选择 <text class="hd-count">{{ selectedArr.length || 0 }}</text> 条诊断
            </view>
            <button
                class="hd-btn"
                :class="{ 'hd-btn--disabled': isLoading }"
                :disabled="isLoading"
                @tap="diagInsuFlag"
            >
                {{ isLoading ? '保存中...' : '添加诊断' }}
            </button>
        </view>
    </view>
</template>

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

export default {
    components: {},
    data() {
        return {
            index: 0,
            templateTypeID: '',
            templateType: [
                { id: '1', descripts: '门诊' },
                { id: '2', descripts: '住院' }
            ],
            admList: [],
            diagDetailList: [],
            selectedArr: [],
            isLoading: false,
            isHistoryDiagLoading: false,
            historyDiagRequestId: 0,
            select: 0,
            descripts: '',
            listKey: 0
        };
    },
    options: {
        addGlobalClass: true
    },
    props: {
        arryLength: String
    },
    mounted() {
        this.attached();
        this.$nextTick(() => this.ready());
    },
    destroyed: function () {},
    methods: {
        ready: function () {
            this.getHistoryAdmList();
        },
        attached: function () {},

        getHistoryAdmList: function () {
            const userData = Cache.get('userData');
            const patientData = Cache.get('patientData');
            $http.post('urlDeault', this, {
                code: '03050052',
                data: {
                    params: [
                        {
                            patID: patientData.patID,
                            hospID: userData.hospID
                        }
                    ]
                },
                success: (res) => {
                    if (res.errorCode === '0') {
                        this.admList = res.result.data || [];
                    }
                }
            });
        },

        getHistoryDiagList: function (admID) {
            var that = this;
            const requestId = ++this.historyDiagRequestId;
            this.isHistoryDiagLoading = true;
            this.diagDetailList = [];
            this.selectedArr = [];
            $http.post('urlDeault', this, {
                code: '03050033',
                data: {
                    params: [
                        {
                            admID,
                            historyFlag: 'Y',
                            historyType: 'O',
                            syFlag: 'Y'
                        }
                    ]
                },
                success: function (res) {
                    if (requestId !== that.historyDiagRequestId) return;
                    if (res.errorCode === '0') {
                        var list = res.result && res.result.diagList || [];
                        that.diagDetailList = list;
                        that.selectedArr = [];
                        that.listKey = that.listKey + 1;
                    }
                },
                complete: function () {
                    if (requestId === that.historyDiagRequestId) {
                        that.isHistoryDiagLoading = false;
                    }
                }
            });
        },

        bindPickerChange: function (e) {
            this.index = e.detail.value;
            this.templateTypeID = this.templateType[e.detail.value].id;
        },

        radioChange: function (e) {
            let checked = e.detail.value;
            for (let i = 0; i < this.admList.length; i++) {
                if (checked == this.admList[i].admID) {
                    this.admList[i].checked = true;
                    this.getHistoryDiagList(e.detail.value);
                } else {
                    this.admList[i].checked = false;
                }
            }
        },

        onChange(event) {
            this.selectedArr = event.detail;
        },

        // 历史诊断接口返回的数据结构不稳定，id 可能为空，这里做统一降级取唯一 key
        getItemKey: function (item, index) {
            if (!item) return 'idx_' + index;
            if (item.id !== undefined && item.id !== null && item.id !== '') return item.id;
            if (item.diagID !== undefined && item.diagID !== null && item.diagID !== '') return 'diag_' + item.diagID;
            return 'idx_' + index;
        },

        isSelected: function (item, index) {
            return this.selectedArr.indexOf(this.getItemKey(item, index)) > -1;
        },

        toggleItem: function (item, index) {
            const key = this.getItemKey(item, index);
            if (!key) return;
            let selectedArr = [...this.selectedArr];
            const idx = selectedArr.indexOf(key);
            if (idx > -1) {
                selectedArr.splice(idx, 1);
            } else {
                selectedArr.push(key);
            }
            this.selectedArr = selectedArr;
        },

        saveDiag: Util.debounce(function () {
            const { diagDetailList, selectedArr } = this;

            // 校验是否选择了诊断
            if (!selectedArr || selectedArr.length === 0) {
                uni.showToast({
                    title: '请先选择诊断',
                    icon: 'none',
                    duration: 2000
                });
                this.isLoading = false;
                return;
            }

            const userData = Cache.get('userData');
            const patientData = Cache.get('patientData');
            let diagData = [];
            diagDetailList.forEach((item, index) => {
                if (this.isSelected(item, index)) {
                    let clone = { ...item };
                    clone.id = '';
                    diagData.push(clone);
                }
            });

            if (diagData.length === 0) {
                uni.showToast({
                    title: '请先选择诊断',
                    icon: 'none',
                    duration: 2000
                });
                this.isLoading = false;
                return;
            }

            let data = {
                params: [
                    {
                        admID: patientData.admID,
                        userID: userData.userID,
                        locID: userData.locID,
                        diagData: diagData
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03050032',
                data: data,
                success: (res) => {
                    this.isLoading = false;
                    if (res.errorCode == '0') {
                        uni.showToast({
                            title: res.errorMessage || '保存成功',
                            icon: 'none'
                        });
                        uni.$emit('refreshDiagnostic');
                        uni.navigateBack({});
                    } else {
                        uni.showToast({
                            title: res.errorMessage || '保存失败',
                            icon: 'none'
                        });
                    }
                },
                fail: () => {
                    this.isLoading = false;
                    uni.showToast({
                        title: '网络异常，请重试',
                        icon: 'none'
                    });
                }
            });
        }),

        diagInsuFlag: function () {
            this.isLoading = true;
            var that = this;

            // 先校验是否有选中诊断
            if (!this.selectedArr || this.selectedArr.length === 0) {
                uni.showToast({
                    title: '请先选择诊断',
                    icon: 'none',
                    duration: 2000
                });
                this.isLoading = false;
                return;
            }

            if (this.arryLength == 0) {
                var diagDetailList = this.diagDetailList;
                let patientData = Cache.get('patientData');
                let userData = Cache.get('userData');
                let firstSelected = diagDetailList.find((item, index) => this.isSelected(item, index));
                if (!firstSelected) {
                    this.isLoading = false;
                    that.saveDiag();
                    return;
                }
                let params = {
                    params: [
                        {
                            admID: patientData.admID,
                            hospID: userData.hospID,
                            diagID: firstSelected.diagID,
                            ICDID: firstSelected.ICDID,
                            CMark: firstSelected.diagCMarkID
                        }
                    ]
                };
                $http.post('urlDeault', this, {
                    code: '03100139',
                    data: params,
                    success: function (res) {
                        if (res.errorCode == '0') {
                            if (res.result.reasonFlag == 'Y' && res.result.insuFlag == 'N') {
                                uni.showModal({
                                    content: res.result.insuDesc,
                                    success(modalRes) {
                                        if (modalRes.confirm) {
                                            that.saveDiag();
                                        } else {
                                            that.isLoading = false;
                                        }
                                    }
                                });
                            } else {
                                that.saveDiag();
                            }
                        } else {
                            that.isLoading = false;
                        }
                    },
                    fail: function () {
                        that.isLoading = false;
                    }
                });
            } else {
                that.saveDiag();
            }
        }
    },
    created: function () {}
};
</script>
<style scoped>
.history-diagnosis {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    min-height: 0;
    background: #f4f7fb;
}

/* 头部 */
.hd-header {
    flex-shrink: 0;
    background: #fff;
    padding: 0 24rpx;
    border-bottom: 1rpx solid #edf1f6;
}

.hd-header-left {
    height: 80rpx;
    display: flex;
    align-items: center;
}

.hd-picker {
    display: flex;
    align-items: center;
    gap: 8rpx;
    font-size: 28rpx;
    color: #1f2937;
    font-weight: 500;
}

/* 主体左右分栏 */
.hd-body {
    flex: 1;
    min-height: 0;
    display: flex;
    overflow: hidden;
}

/* 左侧就诊列表 */
.hd-left {
    width: 260rpx;
    flex-shrink: 0;
    height: 100%;
    min-height: 0;
    background: #fff;
    border-right: 1rpx solid #edf1f6;
}

.hd-left-scroll {
    height: 100%;
}

.hd-visit-item {
    padding: 24rpx 20rpx;
    border-bottom: 1rpx solid #f5f6f8;
    transition: all 0.2s;
}

.hd-visit-item--active {
    background: #eaf4ff;
    border-left: 6rpx solid #1687ff;
}

.hd-visit-label {
    display: flex;
    flex-direction: column;
    gap: 6rpx;
}

.hd-visit-date {
    font-size: 26rpx;
    color: #1f2937;
    font-weight: 500;
}

.hd-visit-loc {
    font-size: 22rpx;
    color: #8b98a8;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 右侧诊断列表 */
.hd-right {
    flex: 1;
    min-width: 0;
    height: 100%;
    min-height: 0;
    background: #f8fafc;
}

.hd-right-scroll {
    height: 100%;
    padding: 8rpx;
}

.hd-right .van-cell {
    margin: 6rpx 8rpx;
    border-radius: 10rpx;
    background: #fff;
    box-shadow: 0 2rpx 8rpx rgba(15, 23, 42, 0.03);
}

.hd-right .van-hairline--top-bottom:after {
    border: none;
}

.hd-right .van-cell__title {
    font-size: 28rpx;
    color: #1f2937;
}

.hd-checkbox-cell {
    flex: none !important;
}

/* 诊断列表 */
.diag-list {
    padding: 8rpx;
}

.diag-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 28rpx;
    margin: 6rpx 8rpx;
    border-radius: 10rpx;
    background: #fff;
    box-shadow: 0 2rpx 8rpx rgba(15, 23, 42, 0.03);
    transition: all 0.2s;
}

.diag-item:active {
    background: #f0f7ff;
}

.diag-item--selected {
    background: #eaf4ff;
    border: 1rpx solid #1687ff;
}

.diag-item__info {
    display: flex;
    flex-direction: column;
    flex: 1;
    gap: 8rpx;
}

.diag-item__title {
    font-size: 28rpx;
    color: #1f2937;
    font-weight: 500;
}

.diag-item__code {
    font-size: 22rpx;
    color: #8b98a8;
}

.diag-item__checkbox {
    flex-shrink: 0;
    margin-left: 16rpx;
}

.custom-checkbox {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    border: 2rpx solid #d1d5db;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}

.custom-checkbox--checked {
    background: #1687ff;
    border-color: #1687ff;
}

.custom-checkbox__icon {
    color: #fff;
    font-size: 22rpx;
    font-weight: bold;
}

/* 空状态 */
.hd-empty {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200rpx;
    color: #8b98a8;
    font-size: 26rpx;
}

.hd-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200rpx;
    gap: 16rpx;
    color: #8b98a8;
    font-size: 26rpx;
}

.hd-loading__spinner {
    width: 36rpx;
    height: 36rpx;
    border: 4rpx solid #dbeafe;
    border-top-color: #1687ff;
    border-radius: 50%;
    animation: hd-spinner-rotate 0.8s linear infinite;
}

@keyframes hd-spinner-rotate {
    to {
        transform: rotate(360deg);
    }
}

/* 底部操作栏 */
.hd-footer {
    flex-shrink: 0;
    width: 100%;
    background: #fff;
    padding: 16rpx 24rpx;
    padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
    box-shadow: 0 -4rpx 16rpx rgba(15, 23, 42, 0.04);
    /* display: flex;
    align-items: center;
    justify-content: flex-end; */
}

.hd-footer-tip {
    display: inline-block;
    line-height: 80rpx;
    min-width: 0;
    font-size: 24rpx;
    color: #8b98a8;
}

.hd-count {
    color: #1687ff;
    font-weight: 600;
}

.hd-btn {
    float: right;
    height: 72rpx;
    line-height: 72rpx;
    padding: 0 48rpx;
    border-radius: 36rpx;
    background: #1687ff;
    color: #fff;
    font-size: 28rpx;
    font-weight: 500;
    border: none;
    box-shadow: 0 6rpx 16rpx rgba(22, 135, 255, 0.25);
}

.hd-btn::after {
    border: none;
}

.hd-btn--disabled {
    opacity: 0.6;
    background: #93c5fd;
}
</style>
