<template>
    <view>
        <nav-bar :navbarData="navbarData"></nav-bar>
        <view class="allpatient" :style="'margin-top: ' + (height * 2 + 10) + 'rpx; height: calc(100vh - ' + (height * 2 + 10) + 'rpx)'">
            <view class="view-query">
                <view class="view-query-date">
                    <button
                        :data-code="item.code"
                        @tap="changeQueryDate"
                        :class="'view-query-dateBtn ' + (item.code == queryDateCode ? 'view-query-dateBtn-clicked' : '')"
                        :style="'width: ' + item.width"
                        :size="dateBtnSize"
                        v-for="(item, index) in queryDateRang"
                        :key="index"
                    >
                        <view class="buttontext" :style="'border-right:' + (index == queryDateRang.length - 1 ? '0px' : '3px solid #f2f2f2')">
                            {{ item.desc }}
                        </view>
                    </button>
                </view>
                <van-calendar
                    allow-same-day
                    :show="calendarShow"
                    color="#0079FE"
                    type="range"
                    :min-date="minCalendarDate"
                    :max-date="maxCalendarDate"
                    :default-date="defaultDate"
                    @close="onCalendarClose"
                    @confirm="onCalendarConfirm"
                />
                <view class="view-query-search">
                    <mp-icon class="view-query-search-icon" type="field" icon="search" color="#999999" :size="30" @tap.native="searchFun"></mp-icon>
                </view>
            </view>
            <view class="swiper-tab">
                <view
                    :class="'swiper-tab-list ' + (currentTab == item.statusCode ? 'on' : '')"
                    :data-current="item.statusCode"
                    @tap="swichNav"
                    v-for="(item, index) in videoStatus"
                    :key="index"
                >
                    {{ item.descripts }}
                </view>
            </view>
            <scroll-view class="scroll-view" :scroll-y="true" @scrolltolower="scrollLower">
                <view v-if="videoAdmList.length > 0">
                    <block v-for="(item, index) in videoAdmList" :key="index">
                        <patAdmRecord :adm-record="item" @offLine="offLine" @rejectAdm="handleRejectAdm" @cancelAdm="refreshAdmList" />
                    </block>
                </view>
                <block v-else>
                    <nothingData />
                </block>
                <view v-if="showRefusal">
                    <refusal @colseRefuse="colseRefuse" :showRefusal="showRefusal" @selectData="findVedioAdmList" :admID="admID"></refusal>
                </view>
                <van-toast id="van-toast" />
            </scroll-view>
        </view>
    </view>
</template>

<script>
import Cache from '../../../../utils/cache';
import refusal from '../refusal/refusal';
import patAdmRecord from '@/pages/components/patAdmRecord/patAdmRecord';
import nothingData from '@/pages/components/nothingData/nothingData';
import navBar from '@/pages/components/navbar/index';
// pages/graphicConsult/graphicConsult.js
import { $http } from '../../../../config/https.js';
import Toast from '../../../../utils/toast';
const userData = Cache.get('userData');
const nowDate = new Date();
const app = getApp();
export default {
    components: {
        refusal,
        patAdmRecord,
        nothingData,
        navBar
    },
    data() {
        return {
            winWidth: 0,
            winHeight: 0,
            msg: 'helloWorld',
            patID: '',
            videoAdmList: [],
            searchPlaceholder: '输入病人姓名查找',
            inputShowed: false,
            inputVal: '',
            dateBtnSize: 'mini',

            queryDateRang: [
                {
                    id: 0,
                    code: 'currentDay',
                    desc: '今日',
                    width: '20%'
                },
                {
                    id: 1,
                    code: 'threeDay',
                    desc: '3天',
                    width: '20%'
                },
                {
                    id: 2,
                    code: 'sevenDay',
                    desc: '7天',
                    width: '20%'
                },
                {
                    id: 3,
                    code: 'dayRang',
                    desc: '自定义日期',
                    width: '40%'
                }
            ],

            queryDateCode: 'currentDay',
            videoStatus: [],
            pageSize: 10,

            // 条数
            currentPage: 1,

            // 页数
            currentTab: '',

            dateFrom: '',
            dateTo: '',
            videoAdmList: [],
            showRefusal: false,
            calendarShow: false,

            // default-date="{{defaultDate}}",
            defaultDate: [
                new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate() - 2).getTime(),
                new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate()).getTime()
            ],

            //
            minCalendarDate: new Date(nowDate.getFullYear(), nowDate.getMonth() - 1, 1).getTime(),

            maxCalendarDate: new Date(nowDate.getFullYear(), nowDate.getMonth() + 1, 1).getTime(),
            patientData: {},
            hasMoreData: false,

            navbarData: {
                isGoBack: true,
                background: '',
                title: '全部患者',
                //导航栏 中间的标题
                bottom: false,
                cleanPat: 'Y'
            },

            height: app.globalData.height,
            search: '',
            admID: ''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.goHome == 'Y') {
            let { navbarData } = this;
            navbarData.isGoHome = true;
            this.setData({
                navbarData
            });
        }
        this.setData({
            search: this.search.bind(this)
        });
        this.findVedioStatusList();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        var that = this;
        uni.getSystemInfo({
            success: function (res) {
                that.setData({
                    winWidth: res.windowWidth,
                    winHeight: res.windowHeight
                });
            }
        });
        uni.setNavigationBarTitle({
            title: '全部患者'
        });
    },
    /*** 生命周期函数--监听页面显示*/
    onShow: function () {
        if (this.currentTab !== '') {
            this.findVedioAdmList(false);
        }
    },
    /*** 生命周期函数--监听页面隐藏*/
    onHide: function () {},
    /*** 生命周期函数--监听页面卸载*/
    onUnload: function () {},
    /*** 页面相关事件处理函数--监听用户下拉动作*/
    onPullDownRefresh: function () {},
    /**   * 页面上拉触底事件的处理函数   */
    onReachBottom: function () {},
    /**   * 用户点击右上角分享   */
    onShareAppMessage: function () {},
    methods: {
        /**  *    * @param {*} e    */
        initData: function () {},

        /**刷新列表 */
        refreshAdmList: function () {
            console.log('refreshAdmList');
            this.findVedioAdmList(false);
        },

        /**
         * 获取表头数据
         * @param {*} e
         */
        findVedioStatusList: function () {
            let data = {
                params: [
                    {
                        locID: userData.locID,
                        hospID: userData.hospID,
                        userID: userData.userID
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100021',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        if (res.result.length > 0) {
                            let currentTab = '';
                            res.result.map((element) => {
                                if (element['defaultFlag'] !== undefined && element['defaultFlag'] === 'Y') {
                                    currentTab = element['statusCode'];
                                }
                            });
                            this.setData(
                                {
                                    videoStatus: res.result,
                                    currentTab
                                },
                                () => {
                                    this.findVedioAdmList(false);
                                }
                            );
                        } else {
                            uni.showToast({
                                title: '未查询到视频问诊状态列表数据',
                                icon: 'none'
                            });
                        }
                    }
                }
            });
        },

        /**
         * 切换日期
         * @param {*} e
         */
        changeQueryDate: function (e) {
            // console.log(e.currentTarget.dataset.code)
            let queryDateCode = e.currentTarget.dataset.code;
            this.setData({
                queryDateCode: queryDateCode
            });
            if (queryDateCode === 'dayRang') {
                this.setData({
                    calendarShow: true,
                    currentPage: 1
                });
            } else {
                //清空日期范围
                this.setData({
                    dateFrom: '',
                    dateTo: '',
                    currentPage: 1
                });
                this.findVedioAdmList(false);
            }
        },

        /**
         * 关闭日历
         */
        onCalendarClose: function () {
            this.setData({
                calendarShow: false
            });
        },

        /**
         * 选中日历
         */
        onCalendarConfirm: function (e) {
            console.log(e);
            this.setData({
                calendarShow: false,
                dateFrom: e.detail[0],
                dateTo: e.detail[1],
                currentPage: 1
            });
            this.findVedioAdmList(false);
        },

        /**
         * 切换tabs
         */
        swichNav: function (e) {
            // console.log(e);
            let currentTab = e.target.dataset.current;
            let that = this;
            if (this.currentTab === currentTab) {
                return false;
            } else {
                this.setData({
                    currentTab: currentTab,
                    currentPage: 1
                });
                // console.log("currentTab", this.data.currentTab);
                //获取就诊记录
                this.findVedioAdmList(false);
            }
        },

        /**
         * 获取就诊记录
         */

        findVedioAdmList: function (searchType) {
            let { dateFrom, currentTab, dateTo, queryDateCode, videoAdmList, pageSize, currentPage } = this;
            let userData = Cache.get('userData');
            if (Cache.get('userData') == undefined) {
                uni.showToast({
                    title: '未获取到用户信息',
                    icon: 'none'
                });
                return;
            }
            if (queryDateCode === 'dayRang') {
                if (dateFrom != '' && dateTo != '') {
                    dateFrom = `${dateFrom.getFullYear()}-${dateFrom.getMonth() + 1}-${dateFrom.getDate()}`;
                    dateTo = `${dateTo.getFullYear()}-${dateTo.getMonth() + 1}-${dateTo.getDate()}`;
                }
                queryDateCode = '';
            }
            let data = {
                params: [
                    {
                        locID: userData.locID,
                        hospID: userData.hospID,
                        userID: userData.userID,
                        statusCode: currentTab,
                        dateFrom: dateFrom,
                        dateTo: dateTo,
                        dateRangeCode: queryDateCode
                    }
                ],
                pagination: [
                    //页码信息
                    {
                        pageSize: pageSize,
                        currentPage: currentPage
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100022',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        if (res.result.data) {
                            // console.log("res-data", res.result.data)
                            let newHasMoreData = false;
                            if (res.result.data.length === pageSize) {
                                newHasMoreData = true;
                            }
                            let newVideoAdmList = [];
                            if (searchType == true) {
                                newVideoAdmList = videoAdmList.concat(res.result.data);
                            } else {
                                newVideoAdmList = res.result.data;
                            }
                            this.setData({
                                videoAdmList: newVideoAdmList,
                                hasMoreData: newHasMoreData
                            });
                        } else {
                        }
                    }
                }
            });
        },

        /**
         * 点击取消接诊
         */
        handleRejectAdm: function (event) {
            console.log('就诊ID:', event);
            let { admID, patientData } = event.detail;
            if (admID == '') {
                uni.showToast({
                    title: '请选择患者操作',
                    icon: 'none'
                });
                return;
            }
            this.setData({
                showRefusal: true,
                admID: event.detail.admID
            });
            Cache.set('patientData', {
                patID: patientData.patID,
                admID: admID
            });
        },

        colseRefuse: function () {
            this.setData({
                showRefusal: false
            });
        },

        /**屏幕下滑至最底部 */
        scrollLower: function () {
            let { hasMoreData, currentPage } = this;
            if (hasMoreData) {
                Toast.loading({
                    mask: true,
                    message: '加载中...'
                });
                this.setData(
                    {
                        currentPage: currentPage + 1
                    },
                    () => {
                        this.findVedioAdmList(true); // 传参标识 表示是滚动加载
                    }
                );
            } else {
                uni.showToast({
                    title: '没有更多数据啦',
                    icon: 'none'
                });
            }
        },

        /**
         * 搜索患者
         */
        searchFun: function (value) {
            let { queryDateCode, dateFrom, dateTo } = this;
            if (queryDateCode === 'dayRang') {
                if (dateFrom != '' && dateTo != '') {
                    dateFrom = `${dateFrom.getFullYear()}-${dateFrom.getMonth() + 1}-${dateFrom.getDate()}`;
                    dateTo = `${dateTo.getFullYear()}-${dateTo.getMonth() + 1}-${dateTo.getDate()}`;
                }
                queryDateCode = '';
            }
            let params = `dateRangeCode=${queryDateCode}&dateFrom=${dateFrom}&dateTo=${dateTo}`;
            uni.navigateTo({
                url: '../searchPatient/searchPatient?' + params,
                // events: {
                //   // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                //   acceptDataFromOpenedPage: function(data) {
                //     console.log(data)
                //   },
                //   someEvent: function(data) {
                //     console.log(data)
                //   }
                // },
                success: function (res) {
                    // 通过eventChannel向被打开页面传送数据
                    res.eventChannel.emit('acceptDataFromOpenerPage', {
                        queryDateCode,
                        dateFrom,
                        dateTo
                    });
                }
            });
            // return new Promise((resolve, reject) => {
            //   setTimeout(() => {
            //     resolve([{
            //       text: '彭若谷',
            //       value: 1
            //     }, {
            //       text: '刘建安',
            //       value: 2
            //     }])
            //   }, 200)
            // })
        },

        /**
         * 选中患者
         */
        selectedPat: function (e) {
            console.log('select result', e.detail.item.value);
            this.setData({
                patID: e.detail.item.value
            });
        },

        /**
         * 接诊
         */
        acceptAdm: function (event) {
            // console.log(event)
            let { admid, statuscode, url, patient } = event.target.dataset;
            let admType = '';
            let admTypeCode = patient.admTypeCode;
            if (admTypeCode == 'W') {
                admType = 'video';
            }
            if (admid !== '') {
                uni.navigateTo({
                    url: url + '?admtype=' + admType
                });
                // console.log('patientData', patient)
                try {
                    Cache.set('patientData', patient);
                } catch (error) {
                    console.log('CatchClause', error);
                    console.log('CatchClause', error);
                    console.log(error);
                }
                this.findVedioAdmList(false);
            }
        },

        offLine: function (data) {
            let { navbarData } = this;
            navbarData.overlayVisible = true;
            navbarData.message = '您处于离线状态，请先登录';
            navbarData.login = true;
            this.setData({
                navbarData
            });
        }
    }
};
</script>
<style>
/* pages/graphicConsult/graphicConsult.wxss */

Page {
    background-color: #f1f1f1;
    overflow: hidden;
    height: 100%;
}

.allpatient {
    width: 100%;
}

.view-query {
    display: flex;
    flex-direction: row;
    height: 90rpx;
}

.view-query-date {
    margin-top: 10rpx;
    margin-left: 24rpx;
    width: calc(100% - 115rpx);
}

.view-query-dateBtn {
    /* margin-left: 5rpx; */
    height: 80rpx !important;
    padding: 15rpx 0 !important;
    border-radius: 0;
    background: #fff;
    width: 25%;
    font-size: 32rpx !important;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: rgba(102, 102, 102, 1);
    line-height: 50rpx;
}

button:after {
    border-radius: 0;
    border: 0px;
}

.buttontext {
    height: 50rpx !important;
    margin: auto 0;
    line-height: 50rpx !important;
}

.view-query-dateBtn-clicked {
    border-radius: 0;
    font-size: 36rpx;
    font-family: Microsoft YaHei;
    font-weight: bold;
    color: rgba(24, 144, 255, 1);
}

/* .van-calendar__footer {
  padding: none;
}
.van-calendar__footer--safe-area-inset-bottom {
  margin-left: 150rpx !important
  padding-left: 150rpx !important;
} */

.view-query-search {
    margin-top: 12rpx;
    height: 70rpx;
    width: 79rpx;
    background-color: #fff;
    margin-left: 12rpx;
    padding-top: 7rpx;
    margin-right: 24rpx;
}

.view-query-search-icon {
    margin-left: 10rpx !important;
}

.swiper-tab {
    background-color: #fff;
    width: calc(100% - 48rpx);
    text-align: center;
    line-height: 80rpx;
    margin: 8rpx 24rpx;
    height: 85rpx;
}

.swiper-tab-list {
    font-size: rpx;
    display: inline-block;
    width: 20%;
    color: #797979;
}

.on {
    color: #1890ff;
    border-bottom: 5rpx solid #1890ff;
}

.patAdmRecord {
    overflow: hidden;
}

.scroll-view {
    height: calc(100% - 90rpx - 105rpx - 16rpx);
    padding-bottom: 20rpx;
}

.scroll-view-item {
    display: flex;
    flex-direction: row;
}

.scroll-view-item-Info {
    display: flex;
    flex-direction: column;
    font-size: 14px;
}

.scroll-view-item-image {
    width: 40px;
    height: 40px;
    padding-left: 8px;
    padding-top: 8px;
    /* border-radius:50%;  */
}

.scroll-view-item-baseInfo {
    display: flex;
    font-size: 15px;
    flex-wrap: nowrap;
}

.scroll-view-item-baseInfo-surplusTime {
    /* align-items: flex-end; */
    margin-left: 20px;
    font-size: 13px;
}

.noStart {
    color: #f93;
}

.scroll-view-item-timeRang {
    margin-top: 3px;
    font-size: 13px;
    flex-wrap: nowrap;
}

.scroll-view-item-status {
    align-self: flex-end;
    margin-left: 64px;
}

.noOverTime {
    color: #0079fe;
}

.scroll-view-item-admType {
    font-size: 13px;
    color: #f93;
}

.btn-view {
    margin-top: 3px;
    align-self: flex-end;
    display: flex;
    flex-wrap: nowrap;
}

.btn-view-botBtn {
    font-size: 12px !important;
    color: #0079fe !important;
    border: 1px solid #0079fe !important;
    margin-left: 9rpx !important;
    /* margin-left: 34px; */
}

.btn-view-botBtn2 {
    font-size: 12px !important;
    color: rgb(247, 247, 248) !important;
    background-color: #0079fe !important;
    margin-left: 9rpx !important;
}
.none {
    height: 100%;
    width: 408rpx;
    margin: 50rpx 0 10rpx 150rpx;
}
.weui-half-screen-dialog__hd .weui-icon-btn {
    display: none;
    width: 0;
    height: 0;
}
</style>
