var year = new Date().getFullYear();
var x_m_array = new Array();
var x_m_array_temp = new Array();
var months = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
var monthsCH = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
var array_year_score = new Array();
var array_check_type = new Array();
var score_statistics;
var check_type;
var cur_status;
var hide = false;

var array_points = new Array();
var array_points2 = new Array();

// 仅选择日期
$.jeDate("#start-time", {
    isinitVal: true,
    format: 'YYYY/MM' // 分隔符可以任意定义，该例子表示只显示年月
});
$("#start-time").val(getCurrentTimeFormat());

var t = getTimeByMonth($("#start-time").val());
var start_date = getMomentTimeFormat(t.starttime);
var end_date = getMomentTimeFormat(t.endtime);

/**
 * 预加载方法
 */
$(function() {
    setVisit();

    // var temp_time = $.zui.store.get('page_data_param_temp_time');
    // if (temp_time) {

    //     var year = temp_time.split('/')[0];
    //     var month = temp_time.split('/')[1];

    //     var starty = year;
    //     var startm = parseInt(month) - 1;

    //     if (startm <= 0) {
    //         startm = 12;
    //         starty = parseInt(year) - 1;
    //     }

    //     $(".div-start input").val(starty + '-' + (startm >= 10 ? startm : ("0" + startm)) + '-25');
    //     $(".div-end input").val(year + '-' + month + '-25');
    //     $.zui.store.set('page_data_param_temp_time', null)
    // }

    //*************************************数据表格******************************************
    function initAppealPage(start_date, end_date, dept_id) {
        initQueryParams();
        queryAppeal(start_date, end_date, dept_id);
    }

    function initQueryParams() {
        //获取页面参数
        var page_params = $.zui.store.get("page_params");
        if (page_params && page_params.status) {
            cur_status = page_params.status;
        }
    }

    function queryAppeal(start_date, end_date, dept_id) {

        $("#station_name").html($("#select-dept").find("option:selected").text())

        // $("#station_user_name").html("-")

        //请求数据
        var data_t = {
            "start_date": start_date,
            "end_date": end_date,
            "dept_id": dept_id
        }
        var url_t = "f/statistics/employee/order/detail"
        post_common_service(url_t, data_t, function(res) {

            $("#c_com_ranking").html("-");
            $("#c_score_ranking").html("-");         
            $("#l_com_ranking").html("-");
            $("#l_score_ranking").html("-");

            var isshow_c = false;
            var isshow_l = false;
            if (typeof(res.currentP) != undefined && res.currentP != null) {
                var p = res.currentP;          
                $("#c_com_ranking").html(p.company_ranking == undefined ? "-" : p.company_ranking);
                $("#c_score_ranking").html(p.check_all_score + p.check_all_m_score);
                isshow_c = true;
            }
            if (typeof(res.lastP) != undefined && res.lastP != null) {
                var p = res.lastP;
                $("#l_com_ranking").html(p.company_ranking == undefined ? "-" : p.company_ranking);
                $("#l_score_ranking").html(p.check_all_score + p.check_all_m_score);
                isshow_l = true;
            }

            if (isshow_c && isshow_l) {
                var p_c = res.currentP;
                var p_l = res.lastP;
                // if (p_c.service_area_ranking != undefined && p_l.service_area_ranking != undefined) {
                    // var dept_r = p_c.service_area_ranking - p_l.service_area_ranking;
                    // if (dept_r != 0) {
                    //     $("#c_dept_ranking").html($("#c_dept_ranking").html() + "<i style='margin-left:10px;color:" + (dept_r > 0 ? "red" : "#0aef3d") + "' class='icon icon-long-arrow-" + (dept_r > 0 ? "down" : "up") + "'>" + Math.abs(dept_r) + "</i>");
                    // }
                    var com_r = p_c.company_ranking - p_l.company_ranking;
                    if (com_r != 0) {
                        $("#c_com_ranking").html($("#c_com_ranking").html() + "<i style='margin-left:10px;color:" + (com_r > 0 ? "red" : "#0aef3d") + "' class='icon icon-long-arrow-" + (com_r > 0 ? "down" : "up") + "'>" + Math.abs(com_r) + "</i>");
                    }
                    // var road_r = p_c.center_ranking - p_l.center_ranking;
                    // if (road_r != 0) {
                    //     $("#c_road_ranking").html($("#c_road_ranking").html() + "<i style='margin-left:10px;color:" + (road_r > 0 ? "red" : "#0aef3d") + "' class='icon icon-long-arrow-" + (road_r > 0 ? "down" : "up") + "'>" + Math.abs(road_r) + "</i>");
                    // }
                // }
            }
        }, function(error) {})

        $.ajax({
            type: "OPTIONS",
            url: base_ui_url,
            complete: function(x) {

                //计算当前周期
                var now_date_time = moment(new Date(x.getResponseHeader("Date")))
                var current_start_date = null;

                if (now_date_time.date() >= 25) {
                    current_start_date = moment(now_date_time.format("YYYY-MM") + "-25 23:00:00Z").subtract(0, "month");
                } else {
                    current_start_date = moment(now_date_time.format("YYYY-MM") + "-25 23:00:00Z").subtract(1, "month");
                }
                var end_date_time = moment(end_date + "Z");

                if (end_date_time.valueOf() > current_start_date.valueOf()) {
                    if (hasRole(ROLE_STATION_ADMIN) || hasRole(ROLE_STATION) || roleContains('STATION')) {
                        $(".score-select").val(1)
                    }
                }

                var data = {
                    "start_date": start_date,
                    "end_date": end_date,
                    "dept_id": dept_id,
                    "queryType": 0,
                }
                if ($(".score-select").val() == "0") {
                    data["score_flag"] = 0;
                }
                if ($(".score-select").val() == "1") {
                    data["score_flag"] = 1;
                }

                if (hasRole(ROLE_STATION_ADMIN) || hasRole(ROLE_STATION) || hasRole(ROLE_JICHA) || roleContains('STATION')) {
                    hide = true;
                }

                var cols = [
                    { width: 50, text: '序号', flex: true, colClass: 'text-center', field: 'num' },
                    { width: 100, text: '时间段', flex: true, colClass: 'text-center', field: 'check_task_time_name' },
                    // { width: 80, text: '扣分人', flex: true, colClass: 'text-center', field: 'checked_name' },
                    {
                        width: 100,
                        text: '服务区',
                        flex: true,
                        colClass: 'text-center',
                        field: 'dept_id',
                        func: function(value) {
                            return getfeeName(value);
                        }
                    },
                    { width: 40, text: '扣分数', flex: true, colClass: 'text-center', field: 'score', nullvalue: '0' },
                    { width: 120, text: '考核类型', flex: true, colClass: 'text-center', sort: 'down', field: 'parent_name' },
                    { width: 120, text: '考核项', flex: true, colClass: 'text-center', sort: 'down', field: 'name' },
                    { width: 120, text: '扣分凭证', type: 'imagedd', flex: true, hide: hide, field: 'pics' },
                ];
                if (cur_status == 12 || cur_status == 13) {
                    data.check_status_arr = [12, 13];
                }
                $('#personal_data_table').mytable({
                    'cols': cols,
                    'url': "f/statistics/one/checkedItem/detail/info",
                    'param': data
                });
            }
        })
    }

    function getfeeName(id) {
        for (var i in feeList) {
            var fee = feeList[i];
            if (fee.deptid == id) {
                return fee.name;
            }
        }
    }





    //*************************************画图******************************************

    // 加载图配置
    echart();

    $(".query button").click(function() {
        // var user_id = $("#select-personal").val();
        var dept_id = $("#select-dept").val();
        var t = getTimeByMonth($("#start-time").val());
        var start_date = getMomentTimeFormat(t.starttime);
        var end_date = getMomentTimeFormat(t.endtime);
        
        // 查询图一
        init_personal_score_statistics("f/statistics/one/serviceArea/year/info", dept_id);
        // 查询图二
        init_personal_check_type("f/statistics/one/serviceArea/checkedItem/info", dept_id, start_date, end_date);
        // 表格
        initAppealPage(start_date, end_date, dept_id);
        // 加载图配置
        echart();
    });

    /**
     * 初始化图一（服务区得分统计）
     * @param {*} url
     * @param {*} dept_id
     */
    function init_personal_score_statistics(url, dept_id) {

        var t = getTimeByMonth($("#start-time").val());
        var start_date = getMomentTimeFormat(t.starttime);
        var end_date = getMomentTimeFormat(t.endtime);        

        var date = moment(end_date);
        var y = date.get('y');
        var m = date.get('M') + 1;

        x_m_array = new Array();
        for (var i = 1; i <= 12; i++) {
            var month = parseInt(m) + i;
            var starty = parseInt(y) - 1
            if (month > 12) {
                month = month - 12;
                starty = y;
            }
            x_m_array.push(starty + "/" + (month >= 10 ? month : ("0" + month)));
        }

        var param = {
            "start_date": (y - 1) + "-" + new Date().getMonth() + "-25" + " 00:00:00",
            "end_date": end_date,
            "dept_id": dept_id
        }

        initRqueset(url, param, 1);
    }


    /**
     * 初始化图二
     * @param {*} url
     * @param {*} dept_id
     */
    function init_personal_check_type(url, dept_id, start_date, end_date) {
        var param = {
            "start_date": start_date,
            "end_date": end_date,
            "dept_id": dept_id
        }
        initRqueset(url, param, 2);
    }


    /**
     * 请求
     * @param {*} url
     * @param {*} param
     * @param {*} type
     */
    function initRqueset(url, param, type) {
        post_common_service(url, param, function(data) {
            data_array(data, type);
            if (type == 1) {
                // 画图
                score_statistics.setOption(personal_score_statistics());
            } else if (type == 2) {
                // 画图
                check_type.setOption(personal_check_type());
            }
        }, function(error) {
            return "";
        });
    }

    function getsymbol(score) {
        var sy = 'Circle';
        var col = 'green'

        if (score == 1000) {
            sy = "star"
            col = 'red'
        } else
        if (score > 990) {
            sy = "star"
            col = 'orange'
        } else {
            sy = "Triangle"
            col = 'green'
        }



        // itemStyle: {        // 数据级个性化折线样式
        //   normal: {
        //       color: 'yellowgreen'
        //   },
        // }

        return { value: (score), symbol: sy, symbolSize: 5, itemStyle: { normal: { color: col } } };

    }

    /**
     * 数组数据
     * @param {*} data
     * @param {*} type
     */
    function data_array(data, type) {
        if (type == 1) {
            array_year_score.length = 0;

            if (data != '' && data.length != 0) {

                x_m_array_temp = new Array();
                for (var i = 0; i < x_m_array.length; i++) {

                    var index = -1;
                    for (var j = 0; j < data.length; j++) {
                        if (x_m_array[i] == data[j].mth) {
                            index = j;
                            break;
                        }
                    }
                    if (index < 0) {

                    } else {

                        x_m_array_temp.push(x_m_array[i]);
                        var score = (1000 - (filter(data[index].all_check_score, data[index].checked_num, 1.0, 0)));
                        var data_s = getsymbol(score)

                        // console.log(data_s)
                        array_year_score.push(data_s);
                    }
                }
            } else {
                array_year_score.length = 0;
                x_m_array = new Array();
                x_m_array_temp = new Array();
            }

        } else if (type == 2) {
            array_points = new Array();
            array_points2 = new Array();
            var map = new HashMap();

            if (data.length != 0) {
                for (var i = 0; i < data.length; i++) {
                    if (typeof(data[i].all_check_score) == "undefined" || data[i].all_check_score == null) continue;
                    if (map.get(data[i].name) == null) {
                        map.set(data[i].name, data[i].all_check_score);
                    } else {
                        map.set(data[i].name, map.get(data[i].name) + data[i].all_check_score);
                    }
                    array_points2.push({ "value": (data[i].all_check_score), "name": data[i].name, "itemStyle": { "normal": { "color": getchildColor(data[i].name, i).hexStr() } } });
                }
            }
            map.forEach(function(value, key) {
                array_points.push({ "value": value, "name": key, "itemStyle": { "normal": { "color": getColor(key).hexStr() } } });
            });
        }
    }

    // var userid_t = $.zui.store.get("page_params").userid
    var dept_t = $.zui.store.get("page_params").deptid


    // 收费站下拉框
    var dept;
    // if (roleContains("STATION")) {
    //     dept = getCurrentUser().organid;
    // }
    if (dept_t) {
        dept = dept_t;
    }

    // var roadManager;
    // if (roleContains("ROAD_MANAGER")) {
    //     roadManager = getCurrentUser().organid;
    // }
    var feeList = $.zui.store.get("cache_service_area_list");
    // if (roadManager) feeList = cache_road_manager_fee_list_map.get(roadManager);
    setSASelectValueNoAll2(feeList, "#select-dept", dept);

    getInit();
    // setSecond();
    /**
     * 部门人员下拉框
     */
    // function setSecond() {
    //     var select_road = $("#select-dept").val();
    //     var sec = document.getElementById('select-personal');
    //     var tempStr = ''
    //     var param = {
    //         "organid": select_road
    //     }
    //     post_common_service("user/getFsUserList", param, function(data) {
    //         if (data.length != 0) {
    //             var userId;
    //             if (hasRole("ROLE_STATION")) {
    //                 userId = getCurrentUser().id;
    //             }
    //             if (userid_t) {
    //                 userId = userid_t;
    //             }

    //             for (var i = 0; i < data.length; i++) {
    //                 for (var j = 33; j <= 100; j++) {
    //                     if (select_road == j) {
    //                         if (data[i].id == userId) {
    //                             tempStr += "<option value=" + data[i].id + " selected='selected'>" + data[i].truename + "</option>";
    //                         } else {
    //                             tempStr += "<option value=" + data[i].id + ">" + data[i].truename + "</option>";
    //                         }
    //                     }
    //                 }
    //                 sec.innerHTML = tempStr;
    //             }

    //         } else {
    //             sec.innerHTML = '';
    //         }
    //         // 请求数据
    //         getInit();
    //     }, function(error) {
    //         return "";
    //     });
    // }

    function getInit() {
        var t = getTimeByMonth($("#start-time").val());
        var start_date = getMomentTimeFormat(t.starttime);
        var end_date = getMomentTimeFormat(t.endtime);
        // var user_id = $("#select-personal").val();
        var dept_id = $("#select-dept").val();
        // 页面初始化
        echart();

        initAppealPage(start_date, end_date, dept_id);
        init_personal_score_statistics("f/statistics/one/serviceArea/year/info", dept_id);
        init_personal_check_type("f/statistics/one/serviceArea/checkedItem/info", dept_id, start_date, end_date);
    }


    // $("#select-dept").change(function() {
    //     setSecond();
    // });

    // $("#select-personal").change(function() {
    //     getInit();
    // })
    $("#select-dept").change(function() {
        getInit();
    });


    /**
     * 除数为0处理
     * @param {*} num
     * @param {*} num1
     * @param {*} num2
     * @param {*} num4
     */
    function filter(num, num1, num2) {
        if (num1 == 0) {
            return num2;
        } else {
            return (num / num1).toFixed(2);
        }
    }

    function echart() {
        // 路径配置
        require.config({
            paths: {
                echarts: '/js/lib/echarts/build/dist'
            }
        });
        // 使用
        require(
            [
                'echarts',
                'echarts/theme/macarons',
                'echarts/chart/line',
                'echarts/chart/pie'
            ],
            function(ec, theme) {
                // 基于准备好的dom，初始化echarts图表
                score_statistics = ec.init(document.getElementById('personal-score-statistics'), theme);
                check_type = ec.init(document.getElementById('personal-check-type'), theme);
            }
        );
    }

    /**
     * 图一
     */
    function personal_score_statistics() {
        option = {
            color: ['#00ced1'],
            tooltip: {
                trigger: 'axis'
            },

            noDataLoadingOption: {
                text: '暂无数据',
                effect: 'bubble',
                effectOption: {
                    effect: {
                        n: 0 //气泡个数为0
                    }
                },
                textStyle: {
                    fontSize: 20,
                    fontFamily: 'cursive',
                    fontWeight: 'bold'
                }
            },
            grid: {
                width: "75%"
            },
            toolbox: {
                show: true,
            },
            calculable: true,
            xAxis: [{
                type: 'category',
                boundaryGap: false,
                data: x_m_array_temp
            }],
            yAxis: [{
                type: 'value',
                min: 700,
                max: 1000,
                axisLabel: {
                    formatter: '{value}'
                }
            }],
            series: [{
                    name: '平均分',
                    type: 'line',
                    data: array_year_score,
                    // markPoint: {
                    //     data: [
                    //         { type: 'max', name: '最大值' },
                    //         { type: 'min', name: '最小值' }
                    //     ]
                    // },
                    // markLine: {
                    //     data: [
                    //         { type: 'average', name: '平均值' }
                    //     ]
                    // }
                },

            ]
        };
        return option;
    }


    /**
     * 图二
     */
    function personal_check_type() {

        option = {
            tooltip: {
                trigger: 'item',
                formatter: "服务区温馨服务检查问题类别占比 <br/>{b} : {c}分 ({d}%)"
            },
            noDataLoadingOption: {
                text: '暂无数据',
                effect: 'bubble',
                effectOption: {
                    effect: {
                        n: 0 //气泡个数为0
                    }
                },
                textStyle: {
                    fontSize: 20,
                    fontFamily: 'cursive',
                    fontWeight: 'bold'
                }
            },
            toolbox: {
                show: true,
            },
            calculable: false,
            series: [{
                    name: '访问来源',
                    type: 'pie',
                    selectedMode: 'single',
                    radius: [0, 80],

                    // for funnel
                    x: '20%',
                    width: '40%',
                    funnelAlign: 'right',
                    max: 1548,

                    itemStyle: {
                        normal: {
                            label: {
                                show: true,
                                formatter: '{b}:\n{c}分({d}%)',
                                textStyle: {
                                    alias: 'center',
                                    fontSize: 10,
                                    color: '#888'
                                }
                            },
                            labelLine: {
                                show: true,
                                length: 80,
                                lineStyle: {
                                    color: '#888'
                                }

                            }
                        }
                    },
                    data: array_points
                },
                {
                    name: '访问来源',
                    type: 'pie',
                    radius: [100, 125],

                    // for funnel
                    x: '60%',
                    width: '35%',
                    funnelAlign: 'left',
                    max: 1048,
                    itemStyle: {
                        normal: {
                            label: {
                                show: false,
                                formatter: '{b}:{c}人({d}%)'
                            },
                            labelLine: {
                                show: false
                            }
                        }
                    },
                    data: array_points2
                }
            ]
        };

        return option;
    }

});

function setVisit() {
    if (roleContains("STATION")) {
        $("#select-dept").attr("disabled", "disabled");
    }
}

function getColor(name) {

    var color = new $.zui.Color('#52D017');
    switch (name) {
        case "环境卫生":
            { color = new $.zui.Color('#52D017'); break; }
        case "仪容仪表着装":
            { color = new $.zui.Color('#00FFFF'); break; }
        case "动作":
            { color = new $.zui.Color('#7F38EC'); break; }
        case "表情":
            { color = new $.zui.Color('#FFA500'); break; }
        case "文明用语":
            { color = new $.zui.Color('#0000A0'); break; }
        case "环境卫生":
            { color = new $.zui.Color('#52D017'); break; }
        case "工作纪律及行为举止":
            { color = new $.zui.Color('#48CCCD'); break; }
        case "便民服务":
            { color = new $.zui.Color('#FFFF00'); break; }
        case "安全管理":
            { color = new $.zui.Color('#00FF00'); break; }
    }
    return color;
}

function getchildColor(name, p) {
    var color1 = getColor(name);


    var color = new $.zui.Color(color1.r - p * 20, color1.g - p * 20, color1.b - p * 20);

    return color;
}