/// <reference path="../lib/jquery-1.4.1-vsdoc.js" />

function getDefault() {                                                     //默认
    try {
        var sdate = $("#sday").val();
        var edate = $("#eday").val();

        if (checkDatePattern(sdate) && checkDatePattern(edate)) {
            if ($("#sjday").combobox("getValue") == "历史以来") {
                var sdate = "0";
                var edate = "0";
            }
            var records = ParseData(window.external.DoOptions("Tp0513", "GetList", '{"edate":"' + edate + '","sdate":"' + sdate + '"}'));

            if (records.ReturnCode == 0 && records.Records1 instanceof Array && records.Records2 instanceof Array) {
                $("#left_tree_0,#center_tree_0,#right_tree_0").next("ul").empty();
                var srlist = records.Records1;
                var zclist = records.Records2;
                var srdata = getTotalMoney(srlist);
                var zcdata = getTotalMoney(zclist);

                $("#left_tree_0 label").text(srdata.total.toFixed(window.parent.strMoneyPlace));
                $("#center_tree_0 label").text(zcdata.total.toFixed(window.parent.strMoneyPlace));
                $("#right_tree_0 label").text((srdata.total - zcdata.total).toFixed(window.parent.strMoneyPlace));

                appendNode(srlist, "left_tree");
                appendNode(zclist, "center_tree");

                createPieChart("left_pie", srdata.list, "", " 元");
                createPieChart("center_pie", zcdata.list, "", " 元");
                createPieChart("right_pie", [{ name: "利润", y: (srdata.total - zcdata.total), isMinus: ""}], "", " 元");
            }
        } else {
            window.parent.cihoAlert("日期格式不正确！", msgBox.dlgBtn.Ok);
            return false;
        }
    } catch (e) { }
}

function getTrend() {                                                                           //趋势
    try {
        var smonth = $("#smonth").val();
        var emonth = $("#emonth").val();
        if (smonth && emonth) {
            var title = smonth + "~" + emonth;
            var id = "";
            if ($("#panel div.side_active").length <= 0) {
                title = " 收入、支出、净利润 " + "趋势";
            } else {
                title = $("#panel div.side_active label").text() + " 趋势分析";
                id = $("#panel div.side_active")[0].code;
            }

            var xAxis = getMonths(smonth, emonth, 1);
            var yAxis = "金额（元）";
            var subTitle = xAxis.length > 0 ? xAxis[0] + " ~ " + xAxis[xAxis.length - 1] : "";
            var records = ParseData(window.external.DoOptions("Tp0513", "GetSingle", '{ "id":"' + id + '","sdate":"' + smonth + '","edate":"' + emonth + '", flag: "1" }'));
            var data = ParseData(records.Records);

            createLineChart("chartPosition", title, subTitle, xAxis, yAxis, data, "元");
        } else {
            window.parent.cihoAlert("月份不能为空！", msgBox.dlgBtn.Ok);
        }
    } catch (e) { }
}

function getTerm() {                                                                            //同期
    try {
        var xAxis = getMonths();
        var yAxis = "金额(元)";

        var id = "";
        var title = "净利润  同期比较";
        var subTitle = $("#syear").combobox("getText") + "~" + $("#eyear").combobox("getText") + "  " + $("#sMonth").combobox("getText") + "~" + $("#eMonth").combobox("getText");

        if ($("#panel div.side_active").length > 0) {
            id = $("#panel div.side_active")[0].code;
            title = $("#panel div.side_active label").text() + " 同期比较";
        }

        var syear = $("#syear").combobox("getValue");
        var eyear = $("#eyear").combobox("getValue");
        var smonth = $("#sMonth").combobox("getValue");
        var emonth = $("#eMonth").combobox("getValue");

        var records = ParseData(window.external.DoOptions("Tp0513", "GetSingle", '{"id":"' + id + '","syear":"' + syear + '","eyear":"' + eyear + '","smonth":"' + smonth + '","emonth":"' + emonth + '","flag":"2"}'));

        var data = ParseData(records.Records);
        createColumnChart("chartPosition", title, subTitle, xAxis, yAxis, data, "元");
    } catch (e) { }
}

function initInputs() {
    try {
        $("#sjday,#sjmonth,#sMonth,#eMonth,#syear,#eyear").combobox();
        addArrowClass();
        //绑定日期控件
        inputAndBindData("sday", false, "", dateChange);
        inputAndBindData("eday", false, "", dateChange);

        $("#sjday").combobox({
            width: _iWidth80,
            valueField: "dm",
            textField: "mc",
            editable: false,
            panelHeight: 162,
            onSelect: function () {
                var newValue = $(this).combobox("getValue");
                dateExtentCalculation(newValue, "sday", "eday");
                if (newValue == "历史以来") {
                    $("#sday,#eday").attr("disabled", true);
                } else {
                    $("#sday,#eday").attr("disabled", false);
                }
            },
            enterDown: function () {
                var newValue = $(this).combobox("getValue");
                dateExtentCalculation(newValue, "sday", "eday");
                if (newValue == "历史以来") {
                    $("#sday,#eday").attr("disabled", true);
                } else {
                    $("#sday,#eday").attr("disabled", false);
                }
            }
        });
        $("#sjmonth").combobox({
            width: _iWidth80,
            valueField: "dm",
            textField: "mc",
            editable: false,
            panelHeight: 82,
            onSelect: function () {
                var newValue = $(this).combobox("getValue");
                dateExtentCalculation(newValue, "smonth", "emonth");
                var sdate = $("#smonth").val().match(/^(\d{4}-\d{2})-\d{2}$/)[1];
                var edate = $("#emonth").val().match(/^(\d{4}-\d{2})-\d{2}$/)[1];
                $("#smonth").val(sdate);
                $("#emonth").val(edate);
            },
            enterDown: function () {
                var newValue = $(this).combobox("getValue");
                dateExtentCalculation(newValue, "smonth", "emonth");
                var sdate = $("#smonth").val().match(/^(\d{4}-\d{2})-\d{2}$/)[1];
                var edate = $("#emonth").val().match(/^(\d{4}-\d{2})-\d{2}$/)[1];
                $("#smonth").val(sdate);
                $("#emonth").val(edate);
            }
        });

        var sjday = [{ dm: "本月", mc: "本月" }, { dm: "上一月", mc: "上一月" }, { dm: "过去三个月", mc: "过去三个月" }, { dm: "本季度", mc: "本季度" }, { dm: "本年", mc: "本年" }, { dm: "上一年", mc: "上一年" }, { dm: "前年", mc: "前年" }, { dm: "历史以来", mc: "历史以来"}];
        $("#sjday").combobox("loadData", sjday);

        var sjmonth = [{ dm: "过去三个月", mc: "过去三个月" }, { dm: "本季度", mc: "本季度" }, { dm: "近半年", mc: "近半年" }, { dm: "年初至今", mc: "年初至今"}];
        $("#sjmonth").combobox("loadData", sjmonth);

        $("#sjday").combobox("setValue", "本月");
        $("#sjmonth").combobox("setValue", "近半年");

        $("#sMonth,#eMonth").combobox({
            width: 50,
            listWidth: 50,
            panelHeight: 242,
            editable: false
        });
        var startDate = window.top._startDate.replace(/\//g, "-");
        var endDate = window.top._endDate.replace(/\//g, "-");
        var edate = endDate.match(/^(\d{4})-(\d{2})-(\d{2})$/);
        endDate = (edate[1] * 1 + 2) + "-" + edate[2] + "-" + edate[3];

        var now = new Date();
        var years = getYears(startDate, endDate, 3);
        $("#syear,#eyear").combobox({
            valueField: "val",
            textField: "txt",
            width: 70,
            editable: false,
            listWidth: 70
        });
        $("#syear,#eyear").combobox("loadData", years);
        $("#syear").combobox("setValue", years[0]);
        $("#eyear").combobox("setValue", now.getFullYear());

        dateExtentCalculation("本月", "sday", "eday");
        dateExtentCalculation("近半年", "smonth", "emonth");
        var sdate = $("#smonth").val().match(/^(\d{4}-\d{2})-\d{2}$/)[1];
        var edate = $("#emonth").val().match(/^(\d{4}-\d{2})-\d{2}$/)[1];
        $("#smonth").val(sdate);
        $("#emonth").val(edate);

        $("#smonth,#emonth").monthpicker({ onSelect: function () {
            $("#sjmonth").combobox("setText", "自定义");
            $("#sjmonth").combobox("setValue", "自定义");
        }

        });

    } catch (e) { }
}

function initEvent() {
    try {
        $("#chk_default").click(function () {
            if (this.checked) {
                $("#panel").switchClass("side_box", "mary", 0);
                $("#chartPosition").width($("div.overflo").width() - 250);
                $("#chartPosition,#p_trend,#p_term").hide();
                $("li span,div.mary_top > div >font,div.report_map,#p_default").show();
                getDefault();
            }
        });

        $("#chk_trend").click(function () {
            if (this.checked) {
                $("#panel").switchClass("mary", "side_box", 0);
                $("#chartPosition").width($("div.overflo").width() - 250);
                $("#p_default,#p_term,div.report_map,div.mary_top li span,div.mary_top > div >font").hide();
                $("#chartPosition,#p_trend").show();
                getTrend();
            }
        });

        $("#chk_term").click(function () {
            if (this.checked) {
                $("#chartPosition,#p_term").show();
                $("#panel").switchClass("mary", "side_box", 0);
                $("#chartPosition").width($("div.overflo").width() - 250);
                $("#p_default,#p_trend,div.report_map,div.mary_top li span,div.mary_top > div >font").hide();
                getTerm();
            }
        });

        //为父节点设置展开事件
        $("div.overflo").delegate(".parent", "click", function () {
            $(this).next().slideToggle("slow").end().children("div").toggleClass("expand");
            return false;
        });

        //执行查询
        $("#panel").delegate(".side_box .mary_top ul li>div", "click", function () {                   //节点单击事件
            if (!$(this).is("div.side_active")) {

                //切换样式
                $(".side_box .mary_top ul li div").removeClass("side_active");
                $(this).addClass("side_active");

                //执行查询
                var chk_trend = $("#chk_trend")[0].checked;
                var chk_term = $("#chk_term")[0].checked;
                if (chk_term) {
                    getTerm();
                } else if (chk_trend) {
                    getTrend();
                }
            }
        });
        $("#p_trend,#p_term").hide();
    } catch (e) { }
}

function appendNode(data, range) {
    try {
        for (var i = 0; i < data.length; i++) {
            if (data[i].isleaf == "false") {
                var $node = $('<li><div id="' + range + "_" + data[i].id + '" code="' + data[i].id + '"  parent="' + data[i].parent + '" class="parent"><div style="float:left;width:' + (data[i].level * 10 + 20) + 'px;"></div> <span>' + (data[i].money * 1).toFixed(window.parent.strMoneyPlace) + '</span>  <label>' + data[i].txt + '</label></div><ul></ul></li>');
            }
            else {
                var $node = $('<li><div id="' + range + "_" + data[i].id + '" code="' + data[i].id + '" parent="' + data[i].parent + '"><div style="float:left;width:' + (data[i].level * 10 + 20) + 'px"></div><span>' + (data[i].money * 1).toFixed(window.parent.strMoneyPlace) + '</span><label>' + data[i].txt + '</label></div></li>');
            }
            $("#" + range + "_" + data[i].parent).next().append($node);
        }
    } catch (e) { }
}

function createColumnChart(bindId, title, subtitle, xAxis, yAxisTitle, data, unit) {
    try {
        chart = new Highcharts.Chart({
            "chart": { renderTo: bindId, defaultSeriesType: "column", marginRight: 130, marginBottom: 25, backgroundColor: "none" },
            "title": { text: title, x: -20 },
            "subtitle": { text: subtitle, x: -20 },
            "xAxis": { categories: xAxis },
            "yAxis": { title: { text: yAxisTitle }, plotLines: [{ value: 0, width: 1, color: '#808080'}] },
            "tooltip": { formatter: function () { return '<b>' + this.series.name + '</b><br/>' + this.x + ': ' + (this.y * 1).toFixed(window.parent.strMoneyPlace) + unit } },
            "legend": { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -10, y: 100, borderWidth: 0 },
            "series": data
        });
    } catch (e) { }
}

function createLineChart(bindId, title, subtitle, xAxis, yAxisTitle, data, unit) {
    try {
        chart = new Highcharts.Chart({
            "chart": { renderTo: bindId, defaultSeriesType: "line", marginRight: 130, marginBottom: 25, backgroundColor: "none" },
            "title": { text: title, x: -20 },
            "subtitle": { text: subtitle, x: -20 },
            "xAxis": { categories: xAxis },
            "yAxis": { title: { text: yAxisTitle }, plotLines: [{ value: 0, width: 1, color: '#808080'}] },
            "tooltip": { formatter: function () { return '<b>' + this.series.name + '</b><br/>' + this.x + ': ' + (this.y * 1).toFixed(window.parent.strMoneyPlace) + unit } },
            "legend": { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -10, y: 100, borderWidth: 0 },
            "series": data
        });
    } catch (e) { }
}

function createPieChart(bindId, data, title, unit) {
    try {
        chart = new Highcharts.Chart({
            chart: { renderTo: bindId, plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false, backgroundColor: "none"
            },
            title: { text: title },
            tooltip: { formatter: function () { return this.point.name + ' : ' + this.point.isMinus + (this.y * 1).toFixed(window.parent.strMoneyPlace); } },
            plotOptions: {
                pie: {
                    showInLegend: false,
                    allowPointSelect: true,
                    cursor: 'pointer',
                    size: "80%",
                    slicedOffset: 15,
                    dataLabels: {
                        enabled: false,
                        distance: 10,
                        color: '#000000',
                        connectorColor: '#000000',
                        rotation: 0,
                        formatter: function () { return this.point.name + ':' + this.y + unit; }
                    }
                },
                series: { animation: { duration: 2000} }
            },
            series: [{
                type: 'pie',
                data: data
            }]
        });
    } catch (e) { }
}

//日期范围修改方法
function dateChange() {
    try {
        if ($("#sjday").combobox("getText") != "自定义") {
            $("#sjday").combobox("setValue", "");
            $("#sjday").combobox("setText", "自定义");
        }
    } catch (e) { }
}

function getTotalMoney(arr) {
    try {
        var total = 0;
        var pielist = [];
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].level == 0) {
                total += arr[i].money * 1;
                var item = {};
                item.name = arr[i].txt;
                item.y = Math.abs(arr[i].money * 1);
                item.isMinus = arr[i].money * 1 < 0 ? "-" : "";
                //var item = [];
                //            item.name = arr[i].txt;
                //            item.y = arr[i].money * 1;
                // item.push(arr[i].txt, arr[i].money * 1)
                pielist.push(item);
            }
        }
        return { total: total, list: pielist };
    } catch (e) { }
}


//返回年份 列配置信息
//startDate 起始时间
//endDate 结束时间
//type：1.数组
//          2.主标题
//          3.副标题
//          4.药品列配置
function getYears(startDate, endDate, type) {
    try {
        var sYear = parseInt(startDate.split('-')[0], 10);
        var eYear = parseInt(endDate.split('-')[0], 10);
        var years = [];
        while (sYear <= eYear) {
            switch (type) {
                case 1:
                    years.push(sYear + "年");
                    break;
                case 2:
                    years.push({ sortable: false, editable: false, name: sYear, index: sYear, width: 70, align: "center", formatter: numFormatter });
                    break;
                case 3:
                    years.push({ val: sYear, txt: sYear + "年" });
                    break;
                case 4:
                    years.push({ sortable: false, editable: false, name: sYear + "_je", index: sYear + "_je", width: 70, align: "center", formatter: numFormatter });
                    break;
            }
            sYear++;
        }
        return years;
    } catch (e) { }
}

//调整窗口层的大小。
function resizeMyDiv() {
    //设定饼状图所在层的高度：过滤条件47，全部展开30
    $(".overflo").css("height", window.parent.document.documentElement.clientHeight - _iHtMenu - _iHtTab - _iHtCopyright - 47 - 26);
}


function getMonths(startDate, endDate, type) {
    try {
        if (arguments.length == 0) {
            var smonth = $("#sMonth").combobox("getValue") * 1;
            var emonth = $("#eMonth").combobox("getValue") * 1;

            var max = smonth > emonth ? smonth : emonth;
            var min = smonth > emonth ? emonth : smonth;

            var month = [];
            while (min <= max) {
                month.push(min + "月");
                min++;
            }
            return month;
        } else {

            var sYear = parseInt(startDate.split('-')[0], 10) * 1;
            var sMonth = parseInt(startDate.split('-')[1], 10) * 1;
            var eYear = parseInt(endDate.split('-')[0], 10) * 1;
            var eMonth = parseInt(endDate.split('-')[1], 10) * 1;

            var months = [];
            while (sYear <= eYear) {
                if (sYear == eYear && sMonth == (eMonth + 1)) {
                    break;
                }
                if (sMonth == 13) {
                    sYear++;
                    sMonth = 1;
                }
                switch (type) {
                    case 1:
                        if (sMonth < 10) {
                            months.push(sYear + "年0" + sMonth + "月");
                        } else {
                            months.push(sYear + "年" + sMonth + "月");
                        }
                        break;
                    case 2:
                        if (sMonth < 10) {
                            months.push({ sortable: false, editable: false, name: sYear + "-0" + sMonth, index: sYear + "-0" + sMonth, width: 70, align: "center", formatter: numFormatter });
                        } else {
                            months.push({ sortable: false, editable: false, name: sYear + "-" + sMonth, index: sYear + "-" + sMonth, width: 70, align: "center", formatter: numFormatter });
                        }
                        break;
                    case 3:
                        if (sMonth < 10) {
                            months.push({ val: sYear + "-0" + sMonth, txt: sYear + "年0" + sMonth + "月" });
                        } else {
                            months.push({ val: sYear + "-" + sMonth, txt: sYear + "年" + sMonth + "月" });
                        }
                        break;
                    case 4:
                        if (sMonth < 10) {
                            months.push({ sortable: false, editable: false, name: sYear + "-0" + sMonth + "_je", index: sYear + "-0" + sMonth + "_je", width: 70, align: "center", formatter: numFormatter });
                        } else {
                            months.push({ sortable: false, editable: false, name: sYear + "-" + sMonth + "_je", index: sYear + "-" + sMonth + "_je", width: 70, align: "center", formatter: numFormatter });
                        }
                        break;
                }
                sMonth++;
            }
            return months;
        }
    } catch (e) { }
}