(function ($) {
    var HOST = '/icss-web';
    // var HOST = 'http://192.168.3.12:8080/icss-web';
    // var HOST = 'http://192.168.2.165:8080/icss-web';
    // var HOST = 'http://192.168.2.164:8080/icss-web';
    // var HOST = 'http://192.168.3.12:8080/icss-web';

    var draw_tmpl = {
        tooltip: {
            trigger: 'axis'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        yAxis: {
            type: 'value'
        },
        xAxis: {
            type: 'time',
            boundaryGap: ['10%', '10%']
        }
    };

    //绘制
    function draw($wrapper, option) {
        var eChart = echarts.init($wrapper[0]);
        eChart.setOption(option);
        $(window).resize(function () {
            eChart.resize();
        });
    }

    function _genOneDrawData(obj) {
        if (!obj) {
            return null;
        }
        var draw_option = {
            legend: {
                data: []
            },
            series: []
        };
        $.each(obj, function (k, v) {
            if(!v || !v.length){
                return;
            }
            var _data = v[0],
                name = _data.itemName,
                data = [];
            draw_option.legend.data.push(name);
            $.each(v, function (i, item) {
                data.push([parseInt(item.itemTime), item.itemValue]);
            });
            data.sort(function (item1, item2) {
                return new Date(item1[0]) - new Date(item2[0]);
            });
            draw_option.series.push({
                type: 'line',
                name: name,
                smooth: true,
                smoothMonotone: 'x',
                data: data
            });
        });
        return $.extend(true, draw_option, draw_tmpl);
    }

    function genDrawData(data) {
        var return_data = [],
            draw_data;

        for (var i = 1; i < 4; i++) {
            draw_data = _genOneDrawData(data[i]);
            if (draw_data) {
                return_data.push(draw_data);
            }
        }
        return return_data;
    }

    function genIndicatorInfo(data) {
        var $indicator = $('#indicator'),
            $wrapper = $indicator.find('.canvas-wrapper'),
            $proteins,$blood_sugar,is_odd,dif=0;
        var len = data.length;
        if (len === 0) {
            return;
        }
        $indicator.show();
        is_odd=len % 2 === 1;
        if (is_odd) {
            $wrapper.append('<div class="row"><div class="blood-sugar draw-wrapper"></div></div>');
        }
        for (var i = 1; i < len; i++) {
            $wrapper.append('<div class="row"><div class="protein draw-wrapper"></div><div class="protein draw-wrapper"></div></div>');
        }
        i=0;
        $proteins=$wrapper.find('.protein');
        if(is_odd){
            $blood_sugar=$wrapper.find('.blood-sugar');
            draw($blood_sugar, data[0]);
            i=1;
            dif=1;
        }
        for (; i < len; i++) {
            draw($proteins.eq(i-dif), data[i]);
        }
    }

    function addInfo(data) {
        return data ? data : '';
    }

    function genPersonInfoData(data) {
        var sex_map = {
                '1': '男',
                '2': '女'
            },
            birthday = new Date(data.cusBrithday),
            year = birthday.getFullYear(),
            month = birthday.getMonth() + 1,
            day = birthday.getDate(),
            now = new Date(),
            now_year = now.getFullYear(),
            now_month = now.getMonth() + 1,
            now_day = now.getDate(),
            age;
        age = now_year - year;
        if (now_month > month) {
            age += 1;
        } else if (now_month === month) {
            if (now_day >= day) {
                age += 1;
            }
        }

        return {
            'name': data.cusName,
            'sex': sex_map[data.cusSex] ? sex_map[data.cusSex] : '未知',
            'identity': data.cusIdentity,
            'phone': data.cusPhone,
            'birthday': year + '-' + month + '-' + day + '|' + age + '岁',
            'body': (data.cusHeight ? (data.cusHeight + 'cm|') : '') + (data.cusWeight ? (data.cusWeight + 'kg|') : '') + data.cusBim,
            'liveAddress': data.cusLiveAddress,
            'workUnit': data.cusWork
        }
    }

    //初始化个人基本信息
    function initPersonInfo(data) {
        var $personal = $('#personal'),
            $tds = $personal.children('.wrapper').find('td');
        $tds.filter('[data-type=name]').text(addInfo(data.name));
        $tds.filter('[data-type=sex]').text(addInfo(data.sex));
        $tds.filter('[data-type=birthday]').text(addInfo(data.birthday));
        $tds.filter('[data-type=identity]').text(addInfo(data.identity));
        $tds.filter('[data-type=phone]').text(addInfo(data.phone));
        $tds.filter('[data-type=body]').text(addInfo(data.body));
        $tds.filter('[data-type=work-unit]').text(addInfo(data.workUnit));
        $tds.filter('[data-type=live-address]').text(addInfo(data.liveAddress));
    }

    function genMedHistoryInfoData(data) {
        return {
            'pastInfo': data.pastInfoList,
            'medicineInfo': data.medicineInfoList,
            'mainQuestion': data.complicatInfoList
        }
    }

    function separate(str) {
        return str.replace(/;；|；；/,'；');
    }
    
    //初始化病史信息
    function initMedHistoryInfo(data) {
        var $medical_history = $('#medical-history'),
            $tds = $medical_history.children('.wrapper').find('td'),
            arr = [undefined, [], [], [], []],
            medication = [],
            main_question = [];
        if (!data.pastInfo && !data.medicineInfo && !data.mainQuestion) {
            return;
        }

        $.each(data.pastInfo, function (i, v) {
            var date='';
            if(v.recordDate){
                var data=new Date(v.recordDate);
                date+='('+data.getFullYear()+'-'+(data.getMonth()+1)+'-'+data.getDate()+')';
            }
            arr[v.pastType].push(date+v.pastSummary);
        });
        $.each(data.medicineInfo, function (i, v) {
            medication.push(v.drugName);
        });
        $.each(data.mainQuestion, function (i, v) {
            main_question.push(v.disName);
        });
        $tds.filter('[data-type=post]').text(separate((addInfo(arr[1].join('；')))));
        $tds.filter('[data-type=family]').text(separate(addInfo(arr[2].join('；'))));
        $tds.filter('[data-type=allergy]').text(separate(addInfo(arr[3].join('；'))));
        $tds.filter('[data-type=other]').text(separate(addInfo(arr[4].join('；'))));
        $tds.filter('[data-type=medication]').text(separate(addInfo(medication.join('；'))));
        $tds.filter('[data-type=main-question]').text(separate(addInfo(main_question.join('；'))));
        $medical_history.show();
    }

    //初始化就诊记录
    function initMedRec(data) {
        var $recording = $('<div class="recording-info"><div class="date-title"><p>' + data.time.split(' ')[0] + '</p></div></div>'),
            $content = $('<div class="content"></div>'),
            $group, $group_content;

        if (data.hpis.length) {
            $group = $('<div class="group"></div>');
            $group.append('<p class="title">' + '【现病史】' + '</p>');
            var str = '';
            $.each(data.hpis, function (i, v) {
                str += v;
            });
            $group.append('<p class="content" style="margin-left: ' + (byteLen('【现病史】') * 6) + 'px">' + str.replace(/#/g,'') + '</p>');
            $content.append($group);
        }

        if (data.vitals.length) {
            $group = $('<div class="group"></div>');
            $group.append('<p class="title">' + '【体征】' + '</p>');
            str = '';
            $.each(data.vitals, function (i, v) {
                str += v;
            });
            $group.append('<p class="content" style="margin-left: ' + (byteLen('【体征】') * 6) + 'px">' + str.replace(/#/g,'') + '</p>');
            $content.append($group);
        }

        // if (data.lisesStr.length) {
        //     $group = $('<div class="group assay"></div>');
        //     $group.append('<p class="title">' + '【化验】' + '</p>');
        //     $group_content = $('<p class="content" style="margin-left: ' + (byteLen('【化验】') * 6) + 'px"></p>');
        //     $group.append($group_content);
        //     $.each(data.lisesStr, function (i, v) {
        //         if (v.type === '1') {
        //             $group_content.append('<p>' + v.name + '<span class="space"></span>' + v.val + v.unit + '<span class="space"></span>（正常值：' + Number(v.minVal).toFixed(2) + '--' + Number(v.maxVal).toFixed(2) + '）</p>');
        //         } else if (v.type === '2') {
        //             $group_content.append('<p>' + v.name + '<span class="space"></span>' + v.val + '<span class="space"></span></p>');
        //         }
        //     });
        //     $content.append($group);
        // }

        if (data.lisesStr.length) {
            $group = $('<div class="group"></div>');
            $group.append('<p class="title">' + '【化验】' + '</p>');
            $.each(data.lisesStr, function (i, v) {
                $group.append('<p class="content" style="margin-left: ' + (byteLen('【化验】') * 6) + 'px">' + v.replace(/#/g,'') + '</p>');
            });
            $content.append($group);
        }


        if (data.pacses.length) {
            $group = $('<div class="group"></div>');
            $group.append('<p class="title">' + '【辅检】' + '</p>');
            $group_content = $('<p class="content" style="margin-left: ' + (byteLen('【辅检】') * 6) + 'px"></p>');
            $group.append($group_content);
            $.each(data.pacses, function (i, v) {
                $group_content.append('<p>' + v + '</p>');
            });
            $content.append($group);
        }

        $recording.append($content);
        if (data.intervenes) {
            var arr = data.intervenes.split('#');
            arr.pop();
            $group = $('<div class="group"></div>');
            $group.append('<p class="title">' + '【干预建议】' + '</p>');
            $group_content = $('<p class="content" style="margin-left: ' + (byteLen('【干预建议】') * 6) + 'px"></p>');
            $group.append($group_content);
            $.each(arr, function (i, v) {
                var one_arr = v.split(':'),
                    title_w = byteLen(one_arr[0]) * 7,
                    $title = $('<p data-re="y" style="position: absolute;left: 72px;">' + one_arr[0] + ':</p>'),
                    str = '';
                $group_content.append($title);
                if (one_arr.length > 1) {
                    var son_arr = one_arr[1].split('&&');
                    for (var i = 0, len = son_arr.length; i < len; i++) {
                        var _str = son_arr[i];
                        str += _str + '<br/>';
                    }
                }
                $group_content.append('<p style="padding-left: ' + title_w + 'px">' + str + '</p>');
            });
            $content.append($group);
        }
        return $recording;


        function byteLen(target) {
            var byteLength = target.length, i = 0;
            for (; i < byteLength; i++) {
                if (target.charCodeAt(i) > 255) {
                    byteLength++;
                }
            }
            return byteLength;
        }
    }


    //创建就诊信息
    function genMedInfo(data) {
        var $medical_records = $('#medical-records'),
            $recordings = $(),
            $wrapper = $medical_records.find('.recording-wrapper');
        if (data.length === 0) {
            return;
        }
        $.each(data, function (i, v) {
            $recordings = $recordings.add(initMedRec(v));
        });

        $wrapper.append($recordings);
        $medical_records.show();
        $recordings.find('p[data-re=y]').each(function () {
            var $p = $(this);
            $p.css('top', $p.next().position().top);
        });
    }

    function initMedRec2(details, time) {
        if (!details.length) {
            return null;
        }
        var arr = [[], [], [], [], [], [], [], [], [], []];
        var title_arr = ['【主诉】', '【现病史】', '【既往史】', '【其他史】', '【体征】', '【化验】', '【辅检】', '【诊断】', '【治疗】', '【干预建议】']
        var date = new Date(time);
        var $recording = $('<div class="recording-info"><div class="date-title"><p>' + (date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate()) + '</p></div></div>'),
            $content = $('<div class="content"></div>');
        $.each(details, function (i, v) {
            arr[v.type].push(v.itemDescribe);
        });
        $.each(arr, function (i, v) {
            if (!v.length) {
                return;
            }
            $content.append('<div class="group"><p class="title">' + title_arr[i] + '</p><p class="content">' + v.join('；') + '</p></div>')
        });
        $recording.append($content);
        return $recording;
    }

    function genMedInfo2(data) {
        var $medical_records = $('#medical-records'),
            $recordings = $(),
            $wrapper = $medical_records.find('.recording-wrapper');
        if (data.length === 0) {
            return;
        }
        $.each(data, function (i, v) {
            $recordings = $recordings.add(initMedRec2(v.details, v.clinicTime));
        });
        $wrapper.append($recordings);
        $medical_records.show();
    }

    //初始化整个页面
    function init() {
        var url_obj = (function () {
            var r = window.location.search.substr(1).split("&"),
                obj = {};
            $.each(r, function (i, v) {
                if (v) {
                    var arr = v.split("=");
                    obj[arr[0]] = arr[1];
                }
            });
            return obj;
        })();

        $.getJSON(HOST + '/ch/customer/get_customer_info_by_patient_id', {
            patientId: url_obj.patientId,
            hospitalId: url_obj.hospitalId
        }, function (res) {
            var data = res.data;
            initPersonInfo(genPersonInfoData(data));
            initMedHistoryInfo(genMedHistoryInfoData(data));
            genIndicatorInfo(genDrawData(data.map));
        });


        $.getJSON(HOST + '/chronic_controller/get_record_info', {
            patId: url_obj.patientId,
            hospitalId: url_obj.hospitalId
        }, function (res) {
            var data = res.data;
            if (data.recodeType === 1) {
                genMedInfo(data.recodeList);
            } else if (data.recodeType === 2) {
                genMedInfo2(data.recodeList);
            }

        });
    }

    init();


})(jQuery);
