require(prefixPath(["hCore.js"]), function (hCore) {

    function getUrlParam(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
        var result = window.location.search.substr(1).match(reg);
        return result ? decodeURIComponent(result[2]) : null;
    }

    var taskId = getUrlParam("taskId");
    var patientId = getUrlParam("patientId");
    var userCode = getUrlParam("userCode");
    var isMobile = getUrlParam("isMobile");
    var barthelId = getUrlParam("barthelId");
    var barthelDate = getUrlParam("barthelDate");
    if (1 == isMobile) {
        $(".barthel_exponent").height('100%');
    }
    var isUpdate = false;// 是否更新过
    sessionStorage.setItem('barthel', 0);

    layui.use(['laytpl', 'form', 'layer'], function () {
        var laytpl = layui.laytpl;

        /** 查询barthel指数等级表 */
        var barthelLevelListCache = [];
        hCore.request({
            url: "getAllBarthelLevel",
            success: function (data) {
                barthelLevelListCache = data;
            }
        });

        /** 查询barthel指数 */
        (function getFullBarthelItems() {
            var param = {
                'taskId': taskId,
                'barthelId': barthelId
            };
            hCore.request({
                url: "mobile/getBarthelItemsById",
                data: param,
                success: function (data, msg) {
                    if (data) {
                        if (data.residentInfo) {
                            var residentInfo = data.residentInfo;
                            $("#resident").html(residentInfo.name);
                            $("#gender").html(residentInfo.gender);
                            $("#age").html(residentInfo.age);
                            $("#country").html(residentInfo.country);
                            $("#nation").html(residentInfo.nation);
                            $("#job").html(residentInfo.job);
                            $("#married").html(residentInfo.married);
                            $("#educationLevel").html(residentInfo.educationLevel);
                            $("#residentStatus").html(residentInfo.residentStatus);
                        }
                        if (data.barthelBean) {
                            var barthelBean = data.barthelBean;
                            setData(barthelBean.barthelItemTypeBeans);
                            // 总分
                            $("#totalScore").html(barthelBean.totalScore);
                            // 自理能力等级
                            $("#selfCareAbility").html(barthelBean.selfCareAbility);
                            // 责任护士签名
                            responsibleNurse.Value(barthelBean.responsibleNurse == null
                                ? (userCode == null ? '' : userCode)
                                : barthelBean.responsibleNurse);
                            // 护士长签名
                            // headNurse.Value(barthelBean.headNurse == null ? '' : barthelBean.headNurse);
                            isUpdate = false;// 是否更新过
                            sessionStorage.setItem('barthel', 0);
                        }
                    }
                }
            });
        })();

        /** 删除 */
        $("#deleteImg").click(function () {
            if(barthelId == 'null') {
                document.location = window.location.href + '&DELETE';
            } else {
                var param = {'barthelId': barthelId};
                hCore.request({
                    url: "mobile/deleteBarthel",
                    data: param,
                    success: function (data, msg) {
                        hCore.successTips(msg);
                        setTimeout(function () {
                            document.location = window.location.href + '&DELETE';
                        }, 200);
                    }
                });
            }
            // if (barthelId == 'null') {
            //     return layer.msg('不能删除空的barthel指数!', {icon: 5, shift: 6});
            // }
            // SmallConfirm("确定要删除该张barthel指数!", "警告", function (result) {
            //     if (result) {
            //
            //     }
            // });
        });

        /** 保存 */
        var barthelItemTypeList = [];
        $("#saveBtn").click(function () {
            // 单选校验
            for (var i = 0; i < barthelItemTypeList.length; i++) {
                var item = barthelItemTypeList[i];
                var radioVal = $('input[name='+ item.typeCode +']:checked').val();
                if (radioVal == undefined) {
                    return layer.msg(item.typeName + '不能为空', {icon: 5, shift: 6});
                }
            }
            // 校验下拉框
            var $select = $('select');
            for (var i = 0; i < $select.length; i++) {
                var select = $select[i];
                if (select.value == '') {
                    select.focus();
                    $(select).parent().find('button').click();
                    $(select).parent().click();
                    var idVal = select.getAttribute('id');
                    if ('responsibleNurse' == idVal) {
                        return layer.msg('责任护士签名不能为空', {icon: 5, shift: 6});
                    } else {
                        return layer.msg('护士长签名不能为空', {icon: 5, shift: 6});
                    }
                }
            }
            if (!isUpdate) {
                return hCore.errorTips("信息没有变更，不需要重复保存!");
            }
            // 保存
            layer.load();
            hCore.request({
                method: 'POST',
                url: "mobile/saveOrUpdateBarthel",
                data: JSON.stringify(getData()),
                success: function (data, msg) {
                    if (data && data > 0) {
                        hCore.successTips("保存成功!");
                        barthelId = data;
                        isUpdate = false;
                        sessionStorage.setItem('barthel', 0);
                        setTimeout(function () {
                            document.location = window.location.href + '&SAVE';
                        }, 200);
                    } else {
                        hCore.errorTips("保存失败!");
                    }
                    layer.closeAll('loading');
                },
                error: function () {
                    hCore.errorTips("保存失败!");
                    layer.closeAll('loading');
                }
            });
        });

        // 计算totalScore分数、评估等级
        function calculatorTotalScore() {
            var totalScore = 0;
            $.each($("body input[type='radio']"), function (index, item) {
                if (item.checked) {
                    totalScore += $(item).data('val');
                }
            });
            $("#totalScore").html(totalScore);

            // 根据分数计算其评估等级
            var filter = barthelLevelListCache.filter(function (item) {
                return totalScore >= item.under && totalScore <= item.upper;
            });
            if (filter.length > 0) {
                $("#selfCareAbility").html(filter[0].describe);
            }
        }

        function setData(barthelItemTypeBeans) {
            barthelItemTypeList = barthelItemTypeBeans;
            $.each(barthelItemTypeBeans, function (index, item) {
                var typeCode = item.typeCode;
                var data = item.barthelItemBeanList;
                laytpl(tableData.innerHTML).render({"list": data}, function (html) {
                    $("#"+typeCode).html(html);
                });
            });
            // 监听修改
            $("input[type='radio']").click(function () {
                calculatorTotalScore();
                isUpdate = true;// 是否更新过
                sessionStorage.setItem('barthel', 1);
            });
            $("select").parent().find('button').click(function () {
                isUpdate = true;// 是否更新过
                sessionStorage.setItem('barthel', 1);
            });
            $("select").click(function () {
                isUpdate = true;// 是否更新过
                sessionStorage.setItem('barthel', 1);
            });
        }

        function getData() {
            var data = {
                'barthelDateString': barthelDate,
                'barthelId': barthelId,
                'patientId': patientId,
                'taskId': taskId,
                'creator': userCode || sessionStorage.getItem('userCode') || 'admin',
                'modifier': userCode || sessionStorage.getItem('userCode') || 'admin',
                // 进食
                'eat': getRadioVal('eat'),
                // 洗澡
                'shower': getRadioVal('shower'),
                // 修饰
                'modification': getRadioVal('modification'),
                // 穿衣
                'dressing': getRadioVal('dressing'),
                // 控制大便
                'controllingStool': getRadioVal('controllingStool'),
                // 控制小便
                'controllingUrination': getRadioVal('controllingUrination'),
                // 如厕
                'toilet': getRadioVal('toilet'),
                // 床椅转移
                'chairTransfer': getRadioVal('chairTransfer'),
                // 平地行走
                'walkingFlat': getRadioVal('walkingFlat'),
                // 上下楼梯
                'upDownStairs': getRadioVal('upDownStairs'),
                // 总分
                'totalScore': getTextVal('#totalScore'),
                // 自理能力等级
                'selfCareAbility': getTextVal('#selfCareAbility'),
                // 责任护士签名
                'responsibleNurse': getSelectVal('#responsibleNurse'),
                // 护士长签名
                'headNurse': '',//getSelectVal('#headNurse'),
                'responsibleNurseAutograph': getSelectVal('#responsibleNurse'),
                'headNurseAutograph': '',//getSelectVal('#headNurse')
            };
            return data;
        }

        // 获取单选框
        function getRadioVal(name) {
            return getTrim($("input[name='" + name + "']:checked").val());
        }

        // 获取下拉框
        function getSelectVal(id) {
            return getTrim($(id).selectpicker('val'))
        }

        // 获取文本框
        function getTextVal(id) {
            return getTrim($(id).html())
        }

        function getTrim(val) {
            return $.trim(val);
        }

    });
});