(function(){
    Vue.component('date-scource', {
        template: '<section class="mt30" name="date-section">\
                    <p class="c-f18">就诊日期</p>\
                    <div class="div-table">\
                        <div class="table-row">\
                            <div class="table-cell arrow-cell" :class="{\'active\': curPage!=1}" @click="prePage"><i class="fa fa-caret-left c-f20 c-909090"></i></div>\
                            <div v-for="(d, index) in planDate" v-show="showCol(index)" class="table-cell">{{d.dStr}} {{d.day}}</div>\
                            <div class="table-cell arrow-cell" :class="{\'active\': curPage != totalPage}" @click="nextPage"><i class="fa fa-caret-right c-f20 c-909090"></i></div>\
                        </div>\
                        <div class="table-row">\
                            <div class="table-cell arrow-cell c-f16 bgc-ebf4f3">上午</div>\
                            <div class="table-cell" v-for="(item, index) in amData" v-show="showCol(index)" :class="{\'active\': item.arrangeID == arrangeid && arrangeid!=undefined}" @click="getNumbers(item.arrangeID)">\
                                <span :class="getColor(item.arrangeStatus, item.numberStatus)">{{getStatusName(item.arrangeStatus, item.numberStatus)}}</span><br/>\
                                <span class="yy-tag" :class="{\'active\': item.arrangeStatus==1 && item.numberStatus==1}">预约</span>\
                            </div>\
                            <div class="table-cell arrow-cell"></div>\
                        </div>\
                        <div class="table-row">\
                            <div class="table-cell arrow-cell c-f16 bgc-ebf4f3">下午</div>\
                            <div class="table-cell" v-for="(item, index) in pmData" v-show="showCol(index)" :class="{\'active\': item.arrangeID == arrangeid && arrangeid!=undefined}" @click="getNumbers(item.arrangeID)">\
                                <span :class="getColor(item.arrangeStatus, item.numberStatus)">{{getStatusName(item.arrangeStatus, item.numberStatus)}}</span><br/>\
                                <span class="yy-tag" :class="{\'active\': item.arrangeStatus==1 && item.numberStatus==1}">预约</span>\
                            </div>\
                            <div class="table-cell arrow-cell"></div>\
                        </div>\
                    </div>\
                    <p class="c-f18 mt30">就诊时间</p>\
                    <div class="clearfix">\
                        <div v-for="it in numberSource" class="c-20 fl mb20">\
                            <div class="source-tag c-t-center" :class="{\'active\': registerNumber==it.numberSN}" @click="chooseNumber(it.numberSN, it.modeId)">\
                                {{it.commendTime || it.commendScope}}\
                            </div>\
                        </div>\
                    </div>\
                    <div class="mt30 c-t-center mb50">\
                        <button class="btn btn-primary" @click="submitForm">确认预约</button>\
                    </div>\
                </section>',
        props: ['doctorsn', 'arrangeid', 'registerdate'],
        data: function(){
            return {
                planDate: [],
                selectedDate: 0,
                amData: [],
                pmData: [],
                numberSource: [],
                registerNumber: '',
                modeId: '', //号源池模式:1：实时号源池, 0：非实时号源池
                baseInfo: {}, //记录医生医院等基础信息
                specialPrice: 0, //挂号费（单位：分）,
                curPage: 1, //当前页
                page: 1 , //日期分页,当有号源的日期数超过了7天,则需要分页展示
                totalPage: 5,
                pageSize: 31
            }
        },
        mounted: function(){
            getDoctorInfo(this);
            getNumbers(this.arrangeid, this);
        },
        methods: {
            getStatusName: function(arrangeStatus, numberStatus){
                return getStatusName(arrangeStatus, numberStatus);
            },
            getColor: function(arrangeStatus, numberStatus){
                return getStatusColor(arrangeStatus, numberStatus);
            },
            getNumbers: function(code, specialPrice){
                if(code && this.arrangeid != code){
                    getNumbers(code, this);
                    this.arrangeid = code;
                }
            },
            showCol: function(index){
                //默认分页一页展示7条数据,然后显示一个月的数据31天
                switch(this.curPage){
                    case 1:
                        return index < 7 ? true: false;
                        break;
                    case 2:
                        return index >=7 && index<14 ? true: false;
                        break;
                    case 3:
                        return index >=14 && index<21 ? true: false;
                        break;
                    case 4:
                        return index >=21 && index<28? true: false;
                        break;
                    case 5:
                        return index>=28 ? true : false;
                        break;
                    default:
                        return true;
                        break;
                }
            },
            chooseNumber: function(id, modeId){
                this.registerNumber = id;
                this.modeId = modeId;
            },
            prePage: function(){
                if(this.curPage > 1){
                    this.curPage --;
                }
            },
            nextPage: function(){
                if(this.curPage < this.totalPage){
                    this.curPage ++;
                }
            },
            submitForm: function(){
                if(!this.arrangeid){
                    dialog({
                        content: "请选择就诊日期",
                        contentType:'tipsbox',
                        skin:'bk-popup',
                        quickClose: true
                    }).showModal();
                    return false;
                }
                if(!this.registerNumber){
                    dialog({
                        content: "请选择就诊时间",
                        contentType:'tipsbox',
                        skin:'bk-popup',
                        quickClose: true
                    }).showModal();
                    return false;
                }
                
                var oauthInfo = JSON.parse(sessionStorage.getItem("oauthInfo"));
                if(!oauthInfo){
                    //要求登录
                    dialog({
                        title: "登录提醒",
                        skin: "my-dialog",
                        content: "需要登录才可以预约",
                        okValue: "跳转去登录",
                        ok: function(){
                            window.location.href = "../../login/html/login.html";
                        },
                        cancelValue: "我知道了",
                        cancel: function(){}
                    }).showModal();
                    return false;
                }
                
                submitForm(this);
            }
        }
    });
    
    //获取医生基本信息
    function getDoctorInfo(vm){
        var params = {
            doctorSn: vm.doctorsn
        }
        appointmentAPI.querySimpleDoctorBySn(params).then(function(res){
            if(res.successFlg){
                if(res.obj.Code == "10000"){
                    //触发父类获取医生信息
                    EventBus.$emit("get-doctor-info", {docInfo: res.obj});
                    getArrangeDate(vm, res.obj)
                    vm.baseInfo = res.obj;
                }else{
                    showErrorMessage(res.obj.Message);
                }
            }else{
                showErrorMessage(res.errorMsg);
            }
        })
    }
    
    //获取医生排班信息
    function getArrangeDate(vm, docInfo){
        var params = {
            hospitalId: docInfo.hospitalId, //'2h+klDvGn+Q=',
            hosDeptId: docInfo.hosDeptId, //'vp0N0lqGZgA=',
            doctorSn: vm.doctorsn, //'1jGMsR3q3nZawh/iQIuzYg==', //科室和医生必选一
            registerDate: '', //就诊日期 yyyy-MM-dd
            pageIndex: vm.page,
            pageSize: vm.pageSize
        };
        appointmentAPI.queryGhtArrangeWater(params).then(function(res){
            if(res.successFlg){
                if(res.obj.Code == "10000"){
                    var list = res.obj.Result;
                    //先groupby结果,判断有几天号源
                    var dateGroup = _.groupBy(list, 'registerDate');
                    //展示整个月的数据
                    var now = new Date();
                    var planDate = [],
                        selectedIndex;
                    for(i=0; i<31; i++){
                        var d = new Date();
                        d.setDate(now.getDate()+i);
                        var dStr = d.format("yyyy-MM-dd");
                        planDate.push({
                            date: dStr,
                            dStr: d.format("MM/dd"),
                            day: getWeekDay(d.getDay())
                        }); //日期记录
                        //记录选中的日期
                        if(vm.registerdate == dStr){
                            selectedIndex = i;
                        }
                        var objArr = dateGroup[dStr];
                        if(objArr && objArr.length > 0){
                            if(objArr.length == 1){
                                var obj = objArr[0];
                                if(obj.timeId == 1){ //1 上午 2下午 3 晚上
                                    vm.amData.push(obj);
                                    vm.pmData.push({
                                        arrangeID: '', //没有排号
                                        arrangeStatus: 0,
                                    });
                                }else{
                                    vm.pmData.push(obj);
                                    vm.amData.push({
                                        arrangeID: '', //没有排号
                                        arrangeStatus: 0,
                                    });
                                }
                            }else if(objArr.length == 2){
                                for(j=0; j<objArr.length; j++){
                                    var obj = objArr[j];
                                    if(obj.timeId == 1){ //1 上午 2下午 3 晚上
                                        vm.amData.push(obj);
                                    }
                                    if(obj.timeId == 2 || obj.timeId == 3){
                                        vm.pmData.push(obj);
                                    }
                                }
                            }
                        }else{
                            vm.amData.push({
                                arrangeID: '', //没有排号
                                arrangeStatus: 0,
                            });
                            vm.pmData.push({
                                arrangeID: '', //没有排号
                                arrangeStatus: 0,
                            });
                        }
                    }
                    vm.planDate = planDate;
                    if(selectedIndex || selectedIndex == 0){
                        vm.curPage = parseInt(selectedIndex / 7) + 1;
                    }
                }else{
                    showErrorMessage(res.obj.Message);
                }
            }else{
                showErrorMessage(res.errorMsg);
            }
        });
    }
    
    //获取号源信息
    function getNumbers(code, vm){
        var params = {
            arrangeID: code
        };
        appointmentAPI.queryNumbers(params).then(function(res){
            if(res.successFlg){
                if(res.obj.Code == "10000"){
                    vm.numberSource = res.obj.Result;
                }else{
                    showErrorMessage(res.Message);
                }
            }else{
                showErrorMessage(res.errorMsg);
            }
        });
    }
    
    //将挂号信息提交给下一个页面去确认
    function submitForm(vm){
        var dateInfo = {};
        var arr = _.where(vm.amData, {arrangeID: parseInt(vm.arrangeid)});
        if(arr.length == 0){
            arr = _.where(vm.pmData, {arrangeID: parseInt(vm.arrangeid)});
        }
        dateInfo = arr[0];
        var numberInfo = _.findWhere(vm.numberSource, {numberSN: vm.registerNumber});
        var patientInfo = JSON.parse(window.sessionStorage.getItem("oauthInfo"));
        
        //请求接口提交挂号单(我们自己系统)
        var params = {
            patientName: patientInfo.realName,
            userId: patientInfo.id,
            cardType: 1, //默认身份证
            cardNo: patientInfo.idCardNo,
            phoneNo: patientInfo.telephone,
            hospitalName: vm.baseInfo.hosName,
            hospitalId: vm.baseInfo.hospitalId,
            deptName: vm.baseInfo.deptName,
            deptId: vm.baseInfo.hosDeptId,
            doctorName: vm.baseInfo.doctorName,
            doctorId: vm.baseInfo.doctorSn,
            lczcName: vm.baseInfo.lczcName,
            photoUri: vm.baseInfo.photoUri,
            registerDate: dateInfo.registerDate,
            timeId: dateInfo.timeId,
            commendTime: numberInfo.commendTime || numberInfo.commendScope,
            serialNo: numberInfo.serialNo,
            invalidDate: dateInfo.invalidDate,
            originType: 1, //来源类型，1：PC，2：APP,
            registerType: 1 //挂号方式，1：预约挂号，2：现场挂号 
        };
        
        appointmentAPI.createRegistration({entityJson: JSON.stringify(params)}).then(function(res){
            if(res.successFlg){
                var id = res.obj.id;
                //存储这些数据传递去确认页面
                window.localStorage.setItem("dateInfo", JSON.stringify(dateInfo));
                window.localStorage.setItem("numberInfo", JSON.stringify(numberInfo));
                window.localStorage.setItem("baseInfo", JSON.stringify(vm.baseInfo));
        
                //跳转去确认信息页面
                window.location.href = "confirm-info.html?id="+id;
            }else{
                showErrorMessage(res.errorMsg);
            }
        })
        
        
    }
    
    function getWeekDay(val){
        switch(val){
            case 0:
                return "周日";
                break;
            case 1:
                return "周一";
                break;
            case 2:
                return "周二";
                break;
            case 3:
                return "周三";
                break;
            case 4:
                return "周四";
                break;
            case 5:
                return "周五";
                break;
            case 6:
                return "周六";
                break;
        }
    }
    
    function getStatusName(arrangeStatus, numberStatus){
        //arrangeStatus: 1正常 2停诊 3已取消 4暂停预约，自定义： 5无安排
        //numberStatus: 1可约 2已约满或无号源
        switch(arrangeStatus){
            case 1:
                if(numberStatus==1){
                    return "可预约";
                }else{
                    return "已满"
                }
                break;
            case 2:
                return "停诊";
                break;
            case 3:
                return "已取消";
                break;
            case 4:
                return "暂停预约";
                break;
            default:
                return "无安排";
                break;
        }
    }
    
    function getStatusColor(arrangeStatus, numberStatus){
        switch(arrangeStatus){
            case 1:
                if(numberStatus==1){
                    return "";
                }else{
                    return "c-909090"
                }
                break;
            case 2:
                return "c-ffb5b6";
                break;
            case 3:
            case 4:
                return "c-909090";
                break;
            default:
                return "c-f3be88";
                break;
        }
    }
    
    function showErrorMessage(content){
        layer.msg(content, {
            icon: 2,
            time: 3000
        });
    }
})()
