layui.use('element', function () {
    element = layui.element//Tab的切换功能，切换事件监听等，需要依赖element模块
    function Progress(dom, num) {
        window.setTimeout(function () {
            element.progress(dom, num)
        }, 360)
    }
    function showInfoMessage(msg) {
        layer.msg(msg, {
            icon: 6
        })
    }
    function showErrorMessage(msg) {
        layer.msg(msg, {
            icon: 5
        })
    }
    function conFirm(msg, num, isStop, planid, getDat) {
    	if (num == 1) {
    		layer.confirm('<p class="c-333 mb10">请说明中止计划的原因?</p><textarea class="plr5 ptb5 w-100 h200 c-333 set-textarea" maxlength="300" placeholder="请简要描述一下原因，不多于300字"></textarea>', { 
	    		btn: ['确定', '取消'],
	    		area: ["400px", "auto"],
	    		title: "提示"
	    	}, function (index) {
	    		var reason = $(".set-textarea").val()
	    		if (!reason) {
	    			showErrorMessage("请填写中止计划原因！");
	    			return false;
	    		}
	            if (num == 2) {
	                showInfoMessage("计划已完成")
	                $("#stopBtn_" + planid).attr('disabled', true).addClass("falsebutton")
	                return false;
	            } else {
	                isStop = num == 0 ? 1 : 0
	            }
	            if (isStop == 0) {
	                $("#progress_" + planid).css({
	                    "background-color": "gray"
	                })
	                $("#stopBtn_" + planid).html("激活计划")
	                $("#stopBtn_" + planid).css({
	                    "background-color": "#2dbe55"
	                })
	            } else {
	                $("#progress_" + planid).css({
	                    "background-color": "#ff9526"
	                })
	                $("#stopBtn_" + planid).html("中止计划")
	                $("#stopBtn_" + planid).css({
	                    "background-color": "#ff3b30"
	                })
	            }
	            var params = {
	                status: isStop,
	                planId: planid,
	                abortReason: reason
	            }
	            healthAPI.updatePlanStatusById(params).then(function (res) {
	                if (res.status == 200) {
	                    getDat()
	                }
	            })
	            layer.close(index);
	        });
    	} else {
      		layer.confirm('您确定要执行该操作吗?', { btn: ['确定', '取消'], title: "提示" }, function (index) {
			  	if (num == 2) {
			      	showInfoMessage("计划已完成")
			      	$("#stopBtn_" + planid).attr('disabled', true).addClass("falsebutton")
			      	return false;
			  	} else {
			      	isStop = num == 0 ? 1 : 0
			  	}
			  	if (isStop == 0) {
			      	$("#progress_" + planid).css({
			          	"background-color": "gray"
			      	})
			      	$("#stopBtn_" + planid).html("激活计划")
			      	$("#stopBtn_" + planid).css({
			          	"background-color": "#2dbe55"
			      	})
			  	} else {
			      	$("#progress_" + planid).css({
			          	"background-color": "#ff9526"
			      	})
			      	$("#stopBtn_" + planid).html("中止计划")
			      	$("#stopBtn_" + planid).css({
			          	"background-color": "#ff3b30"
		          	})
		      	}
		      	var params = {
		          	status: isStop,
		          	planId: planid
		      	}
		      	healthAPI.updatePlanStatusById(params).then(function (res) {
		          	if (res.status == 200) {
		              	getDat()
		          	}
		      	})
		      	layer.close(index);
		  	});
    	}
    }
    new Vue({
        el: '#app',
        data: {
            code: "",
            modal: "",
            type: "",
            status: "",
            plan: "",
            name: "",
            isDanger: "0",
            pagesize: 10,
            total: "",
            pagetotal: '', //总页数
            currentPage: 1, //当前页数
            tablelist: [],
            diseaselist: [],
            types: [],
            Statics: {},
            wujilu: false,
            datamodelshow: true,
            plantype: 1,
            todaylog: 1,
            isTotayTodo: 1,
            progress: "",
            allFinishCount: "",
            allCount: "",
            planid: "",
            isStop: 1, //
            isActive: true,
            doctorType: "",
            docCode: "",
            docInfo: [],
            isLeader: 0,
            planCreateUser: "",
            healthyConditionType:0

        },
        watch: {
            tablelist: function (val) {
                var vm = this
                this.$nextTick(function () {
                    element.init()
                    for (var i = 0; i < val.length; i++) {
                        var allFinishCount = val[i].allFinishCount
                        var allCount = val[i].allCount
                        var isStop = val[i].status
                        var ishospitalName = val[i].hospitalName
                        vm.planCreateUser = val[i].planCreateUser
                        vm.healthyConditionType=val[i].healthyConditionType//1住院 2康复期 3日常健康 4健康筛查
                        if(vm.healthyConditionType==1){
                            $("#quote_"+val[i].id).css("backgroundColor","#FF3B30")
                        }
                        if(vm.healthyConditionType==2){
                            $("#quote_"+val[i].id).css("backgroundColor","#FF9526")
                        }
                        if(vm.healthyConditionType==3){
                            $("#quote_"+val[i].id).css("backgroundColor","#2DBE55")
                        }
                        if(vm.healthyConditionType==4){
                            $("#quote_"+val[i].id).css("backgroundColor","#02CFB9")
                        }
                        if (ishospitalName == null) {
                            $("#hospitalName_" + val[i].id).html("暂无社区信息")
                        }
                        if (allCount == 0) {
                            Progress(val[i].id, 0 + "%")

                        } else {
                            var progressNum = Math.ceil((allFinishCount / allCount) * 100)
                            Progress(val[i].id, progressNum + "%")
                        }
                        if (isStop == 0) {
                            $("#progress_" + val[i].id).css({
                                "background-color": "gray"
                            })
                            $("#stopBtn_" + val[i].id).html("激活计划")
                            $("#stopBtn_" + val[i].id).css({
                                "background-color": "#2dbe55"
                            })
                        } else {
                            $("#progress_" + val[i].id).css({
                                "background-color": "#ff9526"
                            })
                            $("#stopBtn_" + val[i].id).html("中止计划")
                            if(val[i].status == 2) {
                            	$("#stopBtn_" + val[i].id).css({
	                                "background-color": "gray"
	                            })
                            } else {
                            	$("#stopBtn_" + val[i].id).css({
	                                "background-color": "#ff3b30"
	                            })
                            }
                        }

                    }
                    var lastColor = 'red';
                    for (var i = 0; i < val.length; i++) {
                        if (i == 0) {
                            $($(".quote")[i]).css("background-color", "#12b7f5")
                            continue
                        }
                        if (val[i].patientName == val[i - 1].patientName) {
                            $($(".quote")[i]).css("background-color", "#02cfb9")

                            if (lastColor === 'red') {
                                $($(".quote")[i]).css("background-color", "#12b7f5")
                            }
                        } else {
                            if (lastColor !== 'red') {
                                $($(".quote")[i]).css("background-color", "#12b7f5")
                                lastColor = 'red'
                            } else {
                                lastColor = 'white'
                                $($(".quote")[i]).css("background-color", "#02cfb9")

                            }

                        }

                    }

                })

            },


        },
        mounted: function() {
            var vm = this
            vm.getDatas()
            vm.gettypes()


        },
        methods: {
            setImgSrc: function (src) {
                var str = httpRequest.getImgUrl(src)
                return str
            },
            getDatas: function () {
                var vm = this
                var params = {
                    patientCondition: vm.name,//	居民条件，可以按身份证或者居民名称模糊匹配
                    diseaseCode: vm.type, //疾病类型
                    planType: vm.status,	//安排类型（1康复计划，2转社区医院，3转家庭病床）
                    todaybacklog: vm.isTotayTodo,	// 今日待办（1、今日待办，2、全部）
                    page: vm.currentPage,
                    pageSize: vm.pagesize,
                    isDanger: vm.isDanger,
                }

                healthAPI.getSpecialList(params).then(function (res) {
                    console.log(res)
                    if (res.status == 200) {
                        vm.wujilu = false
                        vm.total = res.data.totalCount
                        vm.pagetotal = Math.ceil(res.data.totalCount / vm.pagesize)
                        vm.tablelist = _.sortBy(res.data.detailModelList, "patientName")
                        if (vm.tablelist.length == 0) {
                            vm.wujilu = true
                        }
                        vm.docInfo = JSON.parse(window.localStorage.getItem('wlyyAgent'))
                        vm.doctorType = vm.docInfo.doctorType
                        if (vm.doctorType != 1) {
                            $(".neironglef>button:nth-child(1)").attr('disabled', "true")
                            $(".neironglef>button:nth-child(1)").addClass("falsebutton")
                            $(".neironglef>button:nth-child(1)").css("color", "white")

                        }

                        healthAPI.doctorBaseinfo().then(function (res) {
                            vm.isLeader = res.data.isLeader//0非团队长 1团队长
                            vm.level=res.data.level//1专科医生，2全科医生，3健康管理师
                            vm.planCreateUser //创建者跟登录者相等可中止操作
                            vm.docCode=res.data.code
                            for (var i = 0; i < vm.tablelist.length; i++) {
                                if(vm.docCode!=vm.planCreateUser){
                                    $("#stopBtn_" + vm.tablelist[i].id).attr('disabled', "true")
                                    $("#stopBtn_" + vm.tablelist[i].id).addClass("falsebutton")
                                }
                               
                            }
                            if (vm.isLeader == 0||vm.level != 1) {
                                $(".neironglef>button:nth-child(2)").attr('disabled', "true")
                                $(".neironglef>button:nth-child(2)").addClass("falsebutton")
                                $(".neironglef>button:nth-child(2)").css("color", "white")

                            }


                        })


                    } else {

                        showErrorMessage(res.msg);
                    }

                })

            },
            gettypes: function () {
                var vm = this
                var search = true
                $("#Status").bsSuggest({
                    data: {
                        value: [{
                            code: "",
                            name: "全部"
                        },
                        {
                            code: "1",
                            name: "康复计划"
                        },
                        {
                            code: "2",
                            name: "(转)社区医院"
                        },
                        {
                            code: "3",
                            name: "(转)家庭病床"
                        }

                        ]
                    },
                    getDataMethod: "data",
                    effectiveFields: ["name"],
                    idField: "code",
                    keyField: "name"
                });
                healthAPI.getSpecialDisease().then(function (res) {
                    if (res.status == 200) {
                        console.log(res)
                        var data = {}
                        data.value = _.map(res.data, function (v) {
                            return {
                                code: v.code,
                                name: v.name
                            }
                        })
                        if (search) {
                            data.value = [{
                                code: "",
                                name: "全部"
                            }].concat(data.value)
                        }
                        $("#Type").bsSuggest({
                            data: data,
                            getDataMethod: "data",
                            effectiveFields: ["name"],
                            idField: "code",
                            keyField: "name"
                        });
                        vm.types = res.data;
                    } else {
                        showErrorMessage(res.msg);
                    }
                })
            },
            search: function (page) {
                var vm = this
                vm.type = $("#Type").attr("data-id");
                vm.status = $("#Status").attr("data-id");
                vm.currentPage = page
                vm.getDatas()
            },
            daiban: function (page) {
                var vm = this
                vm.isTotayTodo = $("#c").prop("checked") ? 2 : 1
                $(".icon-chkbox").toggleClass("icon-bgchkbox");
                vm.currentPage = page
                console.log(vm.currentPage)
                vm.getDatas()
            },
            morePlan: function (data) {
                location.href = "moreplan.html?patientCode=" + data.patientCode
            },

            stop: function (data) {
                var vm = this
                vm.planid = data.id
                conFirm("确定终止该计划吗", data.status, vm.isStop, vm.planid, vm.getDatas)


            },
            newRecover: function () {
                location.href = "../../recover/html/new_recover.html"
            },
            checkPlan: function (data) {
                var vm = this
                location.href = "../../rehabilitation/html/rehabilitation_management.html?planId=" + data.id+"&patientCode=" + data.patientCode

            },
            modelControl: function () {
                location.href = "../../rehabilitation/html/management.html"

            },
            checkPatient: function (data) {
                var vm = this
                layer.open({
                    type: 2,
                    area: ['750px', '650px'],
                    shade: 0.5,
                    title: '居民信息',
                    fixed: true, //不固定
                    maxmin: true,
                    closeBtn: 1,
                    shift: 5,
                    shadeClose: false, //点击遮罩关闭层
                    content: '../../temporary/html/userInfo.html?patient=' + data.patientCode
                })
               
                // location.href = "" + 

            },
            recoveryPlan:function (data){
                location.href = "../../recover/html/personal-manage.html?patientCode="+data.patientCode
                    
            }

        }

    })
});