<template>
    <view class="myloc-page">
        <!-- pages/MyLoc/MyLoc.wxml -->

        <nav-bar :navbarData="navbarData"></nav-bar>
        <van-dialog id="van-dialog" />

        <view class="myloc" :style="'margin-top: ' + (height * 2 + 10) + 'rpx; height: calc(100vh - ' + (height * 2 + 10) + 'rpx)'">
            <view class="search-wrap">
                <mp-searchbar @selectresult="selectResult" placeholder="输入病人姓名查找" @input="selectPatient" @cancel="searchCancel" :search="search"></mp-searchbar>
            </view>

            <view class="tile-row" @tap.stop.prevent="lookPatient" data-type="all">
                <view class="tile">
                    <view class="tile-icon-wrap tile-icon-blue">
                        <image class="tile-icon" :src="imgDomain + '/images/icon/doctor/graphic.png'"></image>
                    </view>
                    <text class="tile-title">全部患者</text>
                    <text class="tile-desc">{{ patientInfo.totalNum }} 位</text>
                </view>

                <view class="tile" @tap.stop.prevent="lookPatient" data-type="video">
                    <view class="tile-icon-wrap tile-icon-green">
                        <image class="tile-icon" :src="imgDomain + '/images/icon/doctor/video.png'"></image>
                    </view>
                    <text class="tile-title">线上门诊</text>
                    <text class="tile-desc">{{ patientInfo.videoNum }} 位</text>
                </view>

                <view class="tile" @tap.stop.prevent="lookPatient" data-type="face">
                    <view class="tile-icon-wrap tile-icon-orange">
                        <image class="tile-icon" :src="imgDomain + '/images/icon/doctor/offline.png'"></image>
                    </view>
                    <text class="tile-title">线下门诊</text>
                    <text class="tile-desc">{{ patientInfo.outpatientNum }} 位</text>
                </view>
            </view>

            <view class="summary-card">
                <view class="summary-header">
                    <text class="summary-bar"></text>
                    <text class="summary-title">今日待完成</text>
                </view>
                <view class="summary-stats">
                    <view class="stat">
                        <text class="stat-num">{{ patientInfo.waitNum }}</text>
                        <text class="stat-label">等待完成</text>
                    </view>
                    <view class="stat-divider"></view>
                    <view class="stat">
                        <text class="stat-num">{{ patientInfo.waitVideoNum }}</text>
                        <text class="stat-label">线上门诊</text>
                    </view>
                    <view class="stat-divider"></view>
                    <view class="stat">
                        <text class="stat-num">{{ patientInfo.waitOutpatientNum }}</text>
                        <text class="stat-label">线下门诊</text>
                    </view>
                </view>
            </view>

            <view class="body" v-if="dataList.length > 0">
                <view class="card" v-for="(item, index) in dataList" :key="index">
                    <view class="card-head">
                        <text class="card-status" :class="'status-' + item.statusCode">{{ item.status }}</text>
                        <text class="card-time" v-if="item.statusCode == 'A'">{{ item.receiveDate }} {{ item.receiveTime }}</text>
                        <text class="card-time" v-if="item.statusCode == 'F'">{{ item.finishDate }} {{ item.finishTime }}</text>
                        <text class="card-time card-time-warn" v-if="item.statusCode == 'R' || item.statusCode == 'CI'">距离取消：{{ item.countdown }}</text>
                    </view>

                    <view class="card-body">
                        <view class="avatar-wrap">
                            <image v-if="item.patImage && !imgErrorSet[item.patID]" class="avatar" :src="getFullImageUrl(item.patImage)" @error="onImageError(item.patID)"></image>
                            <text v-else class="avatar-fallback">{{ getAvatarText(item.patName) }}</text>
                        </view>
                        <view class="pat-info">
                            <view class="pat-row">
                                <text class="pat-name">{{ item.patName }}</text>
                                <image
                                    class="sex-icon"
                                    :src="item.patSexDesc == '男' ? imgDomain + '/images/icon/doctor/male.png' : imgDomain + '/images/icon/doctor/female.png'"
                                ></image>
                                <text class="age-pill">{{ item.patAge }}</text>
                            </view>
                            <text class="pat-no">{{ item.patNo }}</text>
                            <text class="adm-time">就诊时间：{{ item.admDate }} {{ item.admTime }}</text>
                        </view>
                    </view>

                    <view class="card-desc" v-if="item.symptom">{{ item.symptom }}</view>

                    <view class="card-meta">
                        <text class="meta-label">服务类型</text>
                        <text class="meta-value">{{ item.resourceTypeDesc }}</text>
                    </view>

                    <view class="card-foot">
                        <button
                            @tap.stop.prevent="enterLoc"
                            v-if="item.statusCode == 'A' || item.statusCode == 'R'"
                            :data-value="index"
                            data-status="开始接诊"
                            class="btn btn-primary"
                        >
                            <text>开始接诊</text>
                        </button>
                        <button
                            @tap.stop.prevent="enterLoc"
                            v-if="item.statusCode == 'R'"
                            :data-value="index"
                            data-status="拒绝接诊"
                            class="btn btn-danger"
                        >
                            <text>拒绝接诊</text>
                        </button>
                        <button
                            :disabled="btnState"
                            @tap.stop.prevent="enterLoc"
                            v-if="item.statusCode == 'A'"
                            :data-value="index"
                            data-status="取消接诊"
                            class="btn btn-danger"
                        >
                            <text>取消接诊</text>
                        </button>
                        <button @tap.stop.prevent="enterLoc" :data-value="index" data-status="查看详情" class="btn btn-ghost">
                            <text>查看详情</text>
                        </button>
                    </view>
                </view>

                <view v-if="showRefusal">
                    <refusal @colseRefuse="colseRefuse" :showRefusal="showRefusal" @selectData="selectData"></refusal>
                </view>
            </view>

            <view class="empty" v-else>
                <image class="empty-img" :src="imgDomain + 'ttps://chis.e24health.com/images/icon/doctor/none.png'"></image>
                <view class="empty-text">暂无患者</view>
            </view>
        </view>
    </view>
</template>

<script>
import Cache from '../../../../utils/cache';
import refusal from '../refusal/refusal';
import navBar from '@/pages/components/navbar/index';
// pages/MyLoc/MyLoc.js
import { $http } from '../../../../config/https.js';
import { httpconfig } from '../../../../config/httpconfig';
import messageUtil from '../../../../utils/message.js';
import Util from '../../../../utils/util.js';
import Dialog from '../../../../utils/dialog';
const app = getApp();
export default {
    components: {
        refusal,
        navBar
    },
    data() {
        return {
            imgDomain: httpconfig.imgDomain,
            inputShowed: false,
            inputVal: '',
            dataList: [],

            patientInfo: {
                totalNum: '',
                videoNum: '',
                outpatientNum: '',
                waitNum: '',
                waitVideoNum: '',
                waitOutpatientNum: ''
            },

            showRefusal: false,
            patName: '',

            // 头像加载失败记录（按 patID 存）
            imgErrorSet: {},

            navbarData: {
                isGoBack: true,
                background: '',
                title: '我的诊室',
                //导航栏 中间的标题
                bottom: false,
                cleanPat: 'Y'
            },

            height: app.globalData.height,
            btnState: false,
            search: ''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {},
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.selectData();
        this.patientListInfo();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        /**
         * 拼接图片完整 URL
         * 后端返回的 image / patImage 可能是相对路径（如 /images/photo/xxx.png），
         * H5 端需要拼上 imgDomain 才能正确加载
         */
        getFullImageUrl: function (url) {
            if (!url) return '';
            if (/^(https?:)?\/\//i.test(url) || url.startsWith('data:')) {
                return url;
            }
            return this.imgDomain + url;
        },

        /**
         * 头像为空时显示首字作为占位
         */
        getAvatarText: function (name) {
            if (!name) return '?';
            return String(name).charAt(0);
        },

        /**
         * 头像 <image> 加载失败回调
         * 后端返回的 patImage 可能是个失效的 CDN 资源（如 404），
         * 加载失败时回退到首字占位
         */
        onImageError: function (patID) {
            if (!patID || this.imgErrorSet[patID]) return;
            this.setData({
                ['imgErrorSet.' + patID]: true
            });
        },

        searchFun: function (value) {
            return new Promise((resolve, reject) => {
                resolve([
                    {
                        text: '搜索结果',
                        value: 1
                    },
                    {
                        text: '搜索结果2',
                        value: 2
                    }
                ]);
            });
        },

        searchCancel: function (e) {
            this.setData(
                {
                    patName: ''
                },
                () => {
                    this.selectData();
                }
            );
        },

        selectResult: function (e) {
            // console.log('select result', e.detail)
        },

        lookPatient: function (e) {
            uni.navigateTo({
                // url: '../prescriptionTemplate/prescriptionTemplate',
                url: '../allPatient/allPatient'
            });
        },

        selectPatient: function (e) {
            this.setData(
                {
                    patName: e.detail.value
                },
                () => {
                    this.selectData();
                }
            );
        },

        formatDate: function (date, beginTime, endTime) {
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            var yearStr = year + '-' + month + '-' + day;
            var beginArr = beginTime.split(' ');
            var endArr = endTime.split(' ');
            if (yearStr != beginArr[0] || yearStr != endArr[0]) {
                return false;
            }
            var hour = date.getHours();
            var minute = date.getMinutes();
            var second = date.getSeconds();
            var beginTimeArr = beginArr[1].split(':');
            var endTimeArr = endArr[1].split(':');
            if (hour > beginTimeArr[0] && hour < endTimeArr[0]) {
                if (endTimeArr[0] != beginTimeArr[0]) {
                    return true;
                }
            }
            if (endTimeArr[0] == hour && hour == beginTimeArr[0]) {
                if (minute >= beginTimeArr[1] && minute <= endTimeArr[1]) {
                    return true;
                }
            }
            if (hour == beginTimeArr[0]) {
                if (minute <= endTimeArr[1]) {
                    return true;
                }
            }
            if (endTimeArr[0] == hour) {
                if (minute >= beginTimeArr) {
                    return true;
                }
            }
            return false;
        },

        enterLoc: Util.debounce(function (e) {
            var index = e.currentTarget.dataset.value;
            var status = e.currentTarget.dataset.status;
            Cache.set('patientData', this.dataList[index]);
            let TIMInfo = Cache.get('TIMInfo');
            let { navbarData } = this;
            if (TIMInfo.loginStatus == 'N' && (status == '开始呼叫' || status == '开始接诊')) {
                navbarData.overlayVisible = true;
                navbarData.message = '您处于离线状态，请先登录';
                navbarData.login = true;
                this.setData({
                    navbarData
                });
                return;
            }
            if (e.currentTarget.dataset.status == '开始呼叫') {
                let path = '../trtcRoom/trtcRoom';
                messageUtil.allowToJoin(path);
            }
            if (e.currentTarget.dataset.status == '查看详情') {
                uni.navigateTo({
                    url: '../graphicDateil/graphicDateil'
                });
            }
            if (e.currentTarget.dataset.status == '开始接诊') {
                var admType = 'video';
                uni.navigateTo({
                    url: '/pages/myConsultRoom/page/treatment/treatment?admtype=' + admType
                });
            }
            if (e.currentTarget.dataset.status == '取消接诊') {
                this.setData({
                    btnState: true
                }); //请求前禁用标记改为true,防止重复请求
                let _this = this;
                let userData = Cache.get('userData');
                let data = {
                    params: [
                        {
                            hospID: userData.hospID,
                            userID: userData.userID,
                            admID: _this.dataList[index].admID
                        }
                    ]
                };
                $http.post(
                    'urlDeault',
                    this,
                    {
                        code: '03100107',
                        data: data,
                        success: function (res) {
                            if (res.errorCode == '0') {
                                this.setData({
                                    btnState: false
                                });
                                // this.setData({
                                //   dataList: res.result.data
                                // })
                            } else {
                                this.setData({
                                    btnState: false
                                });
                                Dialog.alert({
                                    title: '提示',
                                    message: res.errorMessage,
                                    context: this
                                });
                            }
                        }
                    },
                    {
                        error: 'Y'
                    }
                );
            }
            if (e.currentTarget.dataset.status == '拒绝接诊') {
                this.setData({
                    showRefusal: true
                });
            }
        }),

        selectData: function (e) {
            let that = this;
            let userData = Cache.get('userData');
            let data = {
                params: [
                    {
                        hospID: userData.hospID,
                        userID: userData.userID,
                        locID: userData.locID,
                        patName: this.patName,
                        statusCode: 'R^A'
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100022',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        this.setData({
                            dataList: res.result.data
                        });
                    }
                }
            });
        },

        patientListInfo: function (e) {
            let that = this;
            let userData = Cache.get('userData');
            let data = {
                params: [
                    {
                        hospID: userData.hospID,
                        userID: userData.userID,
                        locID: userData.locID
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100023',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        this.setData({
                            patientInfo: res.result
                        });
                    }
                }
            });
        },

        colseRefuse: function () {
            this.setData({
                showRefusal: false
            });
        }
    }
};
</script>
<style>
/* ============== 全局 ============== */
page {
    background-color: #f4f6fa;
}

.myloc-page {
    width: 100%;
    min-height: 100vh;
    background-color: #f4f6fa;
    overflow-x: hidden;
}

.myloc {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    width: 100%;
    max-width: 100%;
    padding: 0 24rpx 24rpx;
    overflow: hidden;
}

/* ============== 搜索框 ============== */
.search-wrap {
    width: 100%;
    padding: 16rpx 0 8rpx;
    background-color: transparent;
}

/* ============== 顶部三个功能 tile ============== */
.tile-row {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: stretch;
    width: 100%;
    box-sizing: border-box;
    background-color: #ffffff;
    border-radius: 20rpx;
    padding: 28rpx 16rpx;
    box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.04);
    margin-top: 8rpx;
}

.tile {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    padding: 8rpx 0;
}

.tile-icon-wrap {
    width: 96rpx;
    height: 96rpx;
    border-radius: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 14rpx;
}

.tile-icon-blue {
    background: linear-gradient(135deg, #e8f1ff 0%, #d6e6ff 100%);
}

.tile-icon-green {
    background: linear-gradient(135deg, #e6f9ee 0%, #ccf2dc 100%);
}

.tile-icon-orange {
    background: linear-gradient(135deg, #fff4e6 0%, #ffe4c2 100%);
}

.tile-icon {
    width: 64rpx;
    height: 64rpx;
}

.tile-title {
    font-size: 28rpx;
    color: #1f2329;
    line-height: 1.4;
    font-weight: 500;
}

.tile-desc {
    font-size: 22rpx;
    color: #8a93a0;
    margin-top: 4rpx;
}

/* ============== 今日待完成 卡片 ============== */
.summary-card {
    width: 100%;
    box-sizing: border-box;
    margin-top: 24rpx;
    background-color: #ffffff;
    border-radius: 20rpx;
    box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.04);
    padding: 24rpx;
}

.summary-header {
    display: flex;
    align-items: center;
    margin-bottom: 18rpx;
}

.summary-bar {
    display: inline-block;
    width: 6rpx;
    height: 28rpx;
    background-color: #1e90ff;
    border-radius: 4rpx;
    margin-right: 12rpx;
}

.summary-title {
    font-size: 30rpx;
    color: #1f2329;
    font-weight: 600;
}

.summary-stats {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-around;
}

.stat {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.stat-num {
    font-size: 40rpx;
    color: #1e90ff;
    font-weight: 600;
    line-height: 1.2;
}

.stat-label {
    font-size: 24rpx;
    color: #8a93a0;
    margin-top: 6rpx;
}

.stat-divider {
    width: 1px;
    height: 50rpx;
    background-color: #eef0f3;
}

/* ============== 患者列表 ============== */
.body {
    flex: 1;
    width: 100%;
    box-sizing: border-box;
    overflow-y: auto;
    margin-top: 24rpx;
    padding-bottom: 12rpx;
}

.card {
    width: 100%;
    box-sizing: border-box;
    background-color: #ffffff;
    border-radius: 20rpx;
    box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.04);
    margin-bottom: 24rpx;
    overflow: hidden;
}

/* 卡片头部 */
.card-head {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 24rpx;
    border-bottom: 1rpx solid #f0f2f5;
}

.card-status {
    font-size: 26rpx;
    color: #ffffff;
    background-color: #1e90ff;
    padding: 4rpx 16rpx;
    border-radius: 20rpx;
    font-weight: 500;
}

.card-status.status-F {
    background-color: #8a93a0;
}

.card-status.status-R {
    background-color: #fa8c16;
}

.card-status.status-CI {
    background-color: #f56c6c;
}

.card-time {
    font-size: 24rpx;
    color: #8a93a0;
}

.card-time-warn {
    color: #f56c6c;
}

/* 卡片主体 */
.card-body {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    padding: 20rpx 24rpx 12rpx;
}

.avatar-wrap {
    width: 96rpx;
    height: 96rpx;
    border-radius: 50%;
    overflow: hidden;
    background-color: #f0f2f5;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}

.avatar {
    width: 100%;
    height: 100%;
}

.avatar-wrap .avatar-fallback {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #ffffff;
    font-size: 40rpx;
    font-weight: 500;
    background: #5cadff;
    line-height: 1;
}

.pat-info {
    flex: 1;
    margin-left: 20rpx;
    display: flex;
    flex-direction: column;
    min-width: 0;
}

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

.pat-name {
    font-size: 32rpx;
    color: #1f2329;
    font-weight: 600;
    margin-right: 12rpx;
}

.sex-icon {
    width: 28rpx;
    height: 28rpx;
    margin-right: 8rpx;
}

.age-pill {
    display: inline-block;
    background-color: #fff4e6;
    color: #fa8c16;
    font-size: 22rpx;
    line-height: 1;
    padding: 6rpx 12rpx;
    border-radius: 16rpx;
}

.pat-no {
    font-size: 24rpx;
    color: #8a93a0;
    margin-top: 8rpx;
}

.adm-time {
    font-size: 24rpx;
    color: #8a93a0;
    margin-top: 6rpx;
}

/* 主诉描述 */
.card-desc {
    margin: 4rpx 24rpx 16rpx;
    padding: 16rpx 20rpx;
    background-color: #f7f9fc;
    border-radius: 12rpx;
    font-size: 26rpx;
    color: #4a5160;
    line-height: 1.5;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 服务类型 */
.card-meta {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 16rpx 24rpx;
    border-top: 1rpx solid #f0f2f5;
}

.meta-label {
    font-size: 26rpx;
    color: #4a5160;
}

.meta-value {
    font-size: 26rpx;
    color: #fa8c16;
    font-weight: 500;
}

/* 底部按钮 */
.card-foot {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    align-items: center;
    padding: 16rpx 24rpx 20rpx;
    border-top: 1rpx solid #f0f2f5;
    flex-wrap: wrap;
}

.card-foot .btn {
    height: 64rpx;
    line-height: 64rpx;
    min-width: 160rpx;
    padding: 0 28rpx;
    font-size: 26rpx;
    border-radius: 32rpx;
    margin: 8rpx 0 0 16rpx;
    box-sizing: border-box;
    border: 1rpx solid transparent;
}

.card-foot .btn::after {
    border: none;
}

.btn-primary {
    background-color: #fa8c16;
    color: #ffffff;
}

.btn-primary[disabled] {
    background-color: #fdc88a;
    color: #ffffff;
}

.btn-danger {
    background-color: #ffffff;
    color: #f56c6c;
    border-color: #f56c6c;
}

.btn-ghost {
    background-color: #ffffff;
    color: #1e90ff;
    border-color: #1e90ff;
}

/* ============== 空状态 ============== */
.empty {
    flex: 1;
    width: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-top: 60rpx;
}

.empty-img {
    width: 280rpx;
    height: 280rpx;
}

.empty-text {
    margin-top: 12rpx;
    font-size: 26rpx;
    color: #8a93a0;
}

/* ============== 兼容旧 dialog ============== */
.weui-half-screen-dialog__hd .weui-icon-btn {
    display: none;
    width: 0;
    height: 0;
}
</style>
