<template>
    <view class="visit-history">
        <nav-bar :navbar-data="navbarData" />
        <view class="page-body" :style="{ paddingTop: height + 'px' }">
            <view class="choose-patient">
                <choose-patient
                    id="choose-patient"
                    :hisPatID="patID"
                    @selectedChange="upDateUserData($event, { tagId: 'choose-patient' })"
                    backUrl="../../../tabBar/mine/mine"
                ></choose-patient>
            </view>

            <view class="filter-tabs">
                <view
                    v-for="item in tabs"
                    :key="item.value"
                    :class="['filter-tab', activeType === item.value ? 'active' : '']"
                    @tap="changeType(item.value)"
                >
                    {{ item.label }}
                </view>
            </view>

            <scroll-view scroll-y="true" class="record-scroll" :style="{ height: scrollHeight }">
                <view class="record-card" v-for="item in filteredRecords" :key="item._key" @tap="goDetail(item)">
                    <view class="card-head">
                        <view class="doctor-info">
                            <image class="doctor-img" :src="item.image || defaultDoctorImg" @error="imageError(item)" />
                            <view>
                                <view class="doctor-name">{{ item.doctorName || '-' }}</view>
                                <view class="loc-desc">{{ item.locDesc || '-' }}</view>
                            </view>
                        </view>
                        <view class="status" :class="statusClass(item.statusDesc)">{{ item.statusDesc || '-' }}</view>
                    </view>
                    <view class="card-content">
                        <view class="line">
                            <text class="label">服务类型</text>
                            <text class="value">{{ item._serviceType }}</text>
                        </view>
                        <view class="line">
                            <text class="label">就诊人</text>
                            <text class="value">{{ item.patName || symptomValue(item, 'patName') || '-' }}</text>
                        </view>
                        <view class="line">
                            <text class="label">就诊时间</text>
                            <text class="value">{{ item.orderTime || item.consultationDate || '-' }}</text>
                        </view>
                        <view class="symptom" v-if="symptomValue(item, 'symptom')">
                            {{ symptomValue(item, 'symptom') }}
                        </view>
                    </view>
                    <view class="card-foot">
                        <text>查看历程</text>
                        <uni-icons type="forward" size="18" color="#007aff" />
                    </view>
                </view>

                <view class="no-data" v-if="filteredRecords && filteredRecords.length === 0">
                    <van-icon name="orders-o" size="50px" color="#cccccc" />
                    <view class="txt">暂无记录</view>
                </view>
            </scroll-view>
        </view>
    </view>
</template>

<script>
import $http from '@/utils/https';
import Util from '@/utils/utils';
import httpConfig from '@/utils/httpConfig';
import NavBar from '@/components/navBar/index.vue';
import VanIcon from '@/components/icon/index.vue';

const app = getApp();

export default {
    components: {
        'nav-bar': NavBar,
        'van-icon': VanIcon
    },
    data() {
        return {
            height: app.globalData.height,
            navHeight: app.globalData.navHeight,
            windowHost: httpConfig && httpConfig.ipDeault,
            imgHost: httpConfig && httpConfig.imgHost,
            navbarData: {
                isGoHome: true,
                isGoBack: true,
                title: '就诊历程'
            },
            tabs: [
                { label: '全部', value: 'all' },
                { label: '图文问诊', value: 'graphic' },
                { label: '线上门诊', value: 'online' }
            ],
            activeType: 'all',
            records: [],
            patID: '',
            userData: {},
            defaultDoctorImg: ''
        };
    },
    computed: {
        scrollHeight() {
            return 'calc(100vh - ' + (this.height + 104) + 'px)';
        },
        filteredRecords() {
            if (this.activeType === 'all') {
                return this.records;
            }
            return this.records.filter((item) => item._serviceCode === this.activeType);
        }
    },
    onLoad() {
        this.defaultDoctorImg = this.imgHost + '/images/icon/avatar_doctor_act.png';
        const userData = this.$cache.get('userData') || {};
        this.setData(
            {
                userData,
                patID: userData.hisPatID || ''
            },
            () => {
                this.queryRecords();
            }
        );
    },
    methods: {
        upDateUserData(e, _dataset) {
            this.handleDataset(e, _dataset);
            const newUserData = this.$cache.get('userData') || {};
            if (!(this.userData && this.userData.hisPatID === newUserData.hisPatID)) {
                this.setData(
                    {
                        userData: newUserData,
                        patID: newUserData.hisPatID || ''
                    },
                    () => {
                        this.queryRecords();
                    }
                );
            }
        },
        changeType(value) {
            this.setData({
                activeType: value
            });
        },
        queryRecords: Util.debounce(function () {
            const userData = this.$cache.get('userData') || {};
            const data = {
                params: [
                    {
                        patID: userData.hisPatID || '',
                        typeCode: []
                    }
                ]
            };
            uni.showLoading({
                title: '加载中...',
                mask: true
            });
            $http.post('urlS', this, {
                code: '02090009',
                data,
                namespace: 'Y',
                success: function (res) {
                    uni.hideLoading();
                    if (+res.errorCode === 0) {
                        const rows = res.result && res.result.rows instanceof Array ? res.result.rows : [];
                        this.setData({
                            records: rows.map((item, index) => this.normalizeRecord(item, index))
                        });
                    } else {
                        this.setData({
                            records: []
                        });
                    }
                },
                error: function () {
                    uni.hideLoading();
                    this.setData({
                        records: []
                    });
                }
            });
        }),
        normalizeRecord(item, index) {
            const record = {
                ...item
            };
            const img = record.image || record.doctorImageUrl || '';
            record.image = img && img.indexOf('http') !== -1 ? img : img ? this.windowHost + img : this.defaultDoctorImg;
            record._serviceCode = this.serviceCode(record);
            record._serviceType = record._serviceCode === 'graphic' ? '图文问诊' : '线上门诊';
            record._key = (record.admID || record.consultID || 'record') + '-' + index;
            return record;
        },
        serviceCode(item) {
            const text = [item.consultType, item.consultTypeDesc, item.businessDesc, item.admReasonDesc].filter(Boolean).join('');
            if (text.indexOf('图文') > -1) {
                return 'graphic';
            }
            return 'online';
        },
        symptomValue(item, key) {
            const symptom = item && item.patSymptomInfo ? item.patSymptomInfo : {};
            return symptom && symptom[key] ? symptom[key] : '';
        },
        statusClass(status) {
            if (status === '进行中') return 'status-blue';
            if (status === '已结束') return 'status-green';
            if (status === '取消' || status === '已取消') return 'status-orange';
            if (status === '拒绝') return 'status-red';
            return '';
        },
        goDetail(item) {
            const params = [
                ['admID', item.admID],
                ['consultID', item.consultID],
                ['consultTypeID', item.consultTypeID],
                ['doctorID', item.doctorID],
                ['toUser', item.toUserID],
                ['serviceType', item._serviceType]
            ]
                .filter((pair) => pair[1])
                .map((pair) => pair[0] + '=' + encodeURIComponent(pair[1]))
                .join('&');
            uni.navigateTo({
                url: '/pages/mine/medical/visitHistoryDetail/visitHistoryDetail?' + params
            });
        },
        imageError(item) {
            item.image = this.defaultDoctorImg;
        }
    }
};
</script>

<style lang="scss" scoped>
.visit-history {
    min-height: 100vh;
    background: #f6f6f6;
}

.page-body {
    box-sizing: border-box;
}

.choose-patient {
    background: #fff;
}

.filter-tabs {
    display: flex;
    padding: 18rpx 30rpx;
    background: #fff;
    border-top: 1rpx solid #f1f1f1;
}

.filter-tab {
    flex: 1;
    height: 64rpx;
    line-height: 64rpx;
    text-align: center;
    font-size: 28rpx;
    color: #666;
    background: #f5f7fa;
    border-radius: 8rpx;
    margin-right: 16rpx;
}

.filter-tab:last-child {
    margin-right: 0;
}

.filter-tab.active {
    color: #007aff;
    background: #e8f3ff;
    font-weight: 600;
}

.record-scroll {
    box-sizing: border-box;
    padding: 20rpx 30rpx 40rpx;
}

.record-card {
    background: #fff;
    border-radius: 8rpx;
    padding: 28rpx;
    margin-bottom: 20rpx;
}

.card-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 22rpx;
    border-bottom: 1rpx solid #eee;
}

.doctor-info {
    display: flex;
    align-items: center;
}

.doctor-img {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    margin-right: 20rpx;
    background: #f5f5f5;
}

.doctor-name {
    color: #333;
    font-size: 32rpx;
    font-weight: 600;
}

.loc-desc {
    color: #999;
    font-size: 26rpx;
    margin-top: 6rpx;
}

.status {
    color: #999;
    font-size: 26rpx;
}

.status-blue {
    color: #007aff;
}

.status-green {
    color: #20a735;
}

.status-orange {
    color: #ff8f37;
}

.status-red {
    color: #fb3349;
}

.card-content {
    padding-top: 20rpx;
}

.line {
    display: flex;
    margin-bottom: 12rpx;
    font-size: 28rpx;
}

.label {
    flex: 0 0 160rpx;
    color: #666;
}

.value {
    flex: 1;
    color: #333;
}

.symptom {
    margin-top: 16rpx;
    padding: 18rpx;
    color: #333;
    font-size: 28rpx;
    line-height: 40rpx;
    background: #f7f8fa;
    border-radius: 8rpx;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.card-foot {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    color: #007aff;
    font-size: 28rpx;
    padding-top: 22rpx;
}

.no-data {
    height: 500rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.no-data .txt {
    margin-top: 20rpx;
    color: #999;
    font-size: 28rpx;
}
</style>
