var bLoadComplete = false;

//初始化表单元素
function initInputs() {
    try {
        //隐藏日期
        $("#date").hide();

        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 startMonth = now.getFullYear() + "-01";
        var endMonth = (now.getMonth() + 1) < 10 ? (now.getFullYear() + "-0" + (now.getMonth() + 1)) : (now.getFullYear() + "-" + (now.getMonth() + 1));

        var seasons = getSeasons(startDate, endDate, 3);
        var years = getYears(startDate, endDate, 3);

        //查询类型
        $("#spdm,#zydm,#khdm,#lxtype,#sjtype,#cxtype").combobox();
        addArrowClass();

        $("#spdm").combobox({
            valueField: "dm",
            textField: "mc",
            width: 95,
            onblur: function () {
                if ($(this).combobox("getText") == "") {
                    $(this).combobox("setValue", "");
                }
            },
            onfocus: function () {
                if ($(this).combobox("getText") == "全部药品") {
                    $(this).combobox("setText", "");
                }
            }
        });
        $("#zydm").combobox({
            valueField: "dm",
            textField: "mc",
            width: 85,
            onblur: function () {
                if ($(this).combobox("getText") == "") {
                    $(this).combobox("setValue", "");
                }
            },
            onfocus: function () {
                if ($(this).combobox("getText") == "全部销售员") {
                    $(this).combobox("setText", "");
                }
            }
        });
        $("#khdm").combobox({
            valueField: "dm",
            textField: "mc",
            width: 104,
            afterChange: function (newValue, newText) {
                $(this).combobox("setText", newText.replace(/&nbsp;/g, ""));
            },
            onblur: function () {
                if ($(this).combobox("getText") == "") {
                    $(this).combobox("setValue", "");
                }
            },
            onfocus: function () {
                if ($(this).combobox("getText") == "全部客户") {
                    $(this).combobox("setText", "");
                }
            }
        });

        $("#lxtype").combobox({
            width: 73,
            panelHeight: 62,
            editable: false,
            onSelect: function () { showChartOrTable(); },
            enterDown: function () { showChartOrTable(); }
        });
        $("#sjtype").combobox({
            width: 62,
            panelHeight: 62,
            editable: false,
            onSelect: function () {
                var formatNow = getNowDate();
                var newValue = $(this).combobox("getValue");
                switch (newValue) {
                    case "1":                   //月份
                        $("#date").hide();
                        $("#month").show();
                        $("#smonth").val(startMonth);
                        $("#emonth").val(endMonth);
                        break;
                    case "2":                   //季度
                        $("#date").show();
                        $("#month").hide();
                        $("#sdate,#edate").combobox();
                        $("#sdate,#edate").combobox("loadData", seasons);
                        $("#sdate").combobox("setValue", seasons[0].val);
                        $("#edate").combobox("setValue", format(formatNow, 3));
                        break;
                    case "3":                   //年
                        $("#date").show();
                        $("#month").hide();
                        $("#sdate,#edate").combobox();
                        $("#sdate,#edate").combobox("loadData", years);
                        $("#sdate").combobox("setValue", years[0].val);
                        $("#edate").combobox("setValue", format(formatNow, 1));
                        break;
                }
            },
            enterDown: function () {
                var formatNow = getNowDate();
                var newValue = $(this).combobox("getValue");
                switch (newValue) {
                    case "1":                   //月份
                        $("#date").hide();
                        $("#month").show();
                        $("#smonth").val(startMonth);
                        $("#emonth").val(endMonth);
                        break;
                    case "2":                   //季度
                        $("#date").show();
                        $("#month").hide();
                        $("#sdate,#edate").combobox();
                        $("#sdate,#edate").combobox("loadData", seasons);
                        $("#sdate").combobox("setValue", seasons[0].val);
                        $("#edate").combobox("setValue", format(formatNow, 3));
                        break;
                    case "3":                   //年
                        $("#date").show();
                        $("#month").hide();
                        $("#sdate,#edate").combobox();
                        $("#sdate,#edate").combobox("loadData", years);
                        $("#sdate").combobox("setValue", years[0].val);
                        $("#edate").combobox("setValue", format(formatNow, 1));
                        break;
                }
            }
        });

        //查询类型
        $("#cxtype").combobox({
            width: 62,
            panelHeight: 42,
            editable: false
        });

        //加载药品、客户、销售员combobox数据
        var yplist = getComboboxData("Tspxx2");
        var khlist = getComboboxData("Tkhxx2");
        var zylist = getComboboxData("TZyxx2");

        khlist.unshift({ "dm": "", "mc": "全部客户" });
        yplist.unshift({ "dm": "", "mc": "全部药品" });
        zylist.unshift({ "dm": "", "mc": "全部销售员" });
        zylist.push({ "dm": "-1", "mc": "其他销售员" });

        $("#khdm").combobox("loadData", khlist);
        $("#spdm").combobox("loadData", yplist);
        $("#zydm").combobox("loadData", zylist);
        $("#zydm,#spdm,#khdm").combobox("setValue", "");

        //起始时间和结束时间
        $("#sdate,#edate").combobox({
            valueField: "val",
            textField: "txt",
            width: 89,
            editable: false
        });

        $("#smonth").val(startMonth);
        $("#emonth").val(endMonth);

        bLoadComplete = true;
        $("#showChartOrTable").click(function () {
            if (showState == 1) {                               //查看曲线图
                showState = 2;
                showChartOrTable();
                this.src = "../../Content/Default/images/qs.png";
                this.title = "查看曲线图";
                $("#lihb").show();
            } else {
                showState = 1;
                showChartOrTable();
                this.src = "../../Content/Default/images/table.png";
                this.title = "查看表格";
                $("#lihb").hide();
            }
            $("#bgdiv").toggleClass("reportline");
        });
        $("#smonth,#emonth").monthpicker();
        addArrowClass();
        khlist = yplist = zylist = null;
    } catch (e) { }
}

//显示表格或曲线图
function showChartOrTable() {
    try {
        if (showState == 1) {
            $("#divTable").hide();
            $("#divChart").show();
            showChart();
        } else {
            $("#divChart").hide();
            $("#divTable").show();
            search();
        }
    } catch (e) { }
}

//生成图表
function showChart() {
    try {
        var lxtype = $("#lxtype").combobox("getValue");
        var sjtype = $("#sjtype").combobox("getValue");
        var cxtype = $("#cxtype").combobox("getValue");
        var place = cxtype == 1 ? window.parent.strMoneyPlace : window.parent.strCountPlace;

        var khdm = $("#khdm").combobox("getValue");
        var spdm = $("#spdm").combobox("getValue");
        var zydm = $("#zydm").combobox("getValue");


        if (khdm == undefined) { khdm = ""; $("#khdm").combobox("setValue", ""); }
        if (spdm == undefined) { spdm = ""; $("#spdm").combobox("setValue", ""); }
        if (zydm == undefined) { zydm = ""; $("#zydm").combobox("setValue", "") }

        var bhth = $("#includeTH").is(":checked");
        var sdate = (sjtype == "1") ? $("#smonth").val() : $("#sdate").combobox("getValue");
        var edate = (sjtype == "1") ? $("#emonth").val() : $("#edate").combobox("getValue");

        if (sjtype == 1) {                      //按月
            var smonth = sdate.replace(/-/g, "/");
            var emonth = edate.replace(/-/g, "/");
            var _smonth = window.top._startDate.replace(/^(\d{4}\/\d{2})\/\d{2}$/, "$1");
            var _emonth = window.top._endDate.replace(/^(\d{4}\/\d{2})\/\d{2}$/, "$1");
        }

        var jsonStr = '{"sjtype":"' + sjtype + '","sdate":"' + sdate + '","edate":"' + edate + '","khdm":"' + khdm + '","spdm":"' + spdm + '","zydm":"' + zydm + '","bhth":"' + bhth + '","flag":"' + cxtype + '"}';

        var s = null;
        if (lxtype == "1") {
            s = ParseData(window.external.DoOptions("Tp0216", "GetList", jsonStr));
        } else if (lxtype == "2") {
            s = ParseData(window.external.DoOptions("Tp021601", "GetList", jsonStr));
        } else {
            s = ParseData(window.external.DoOptions("Tp021602", "GetList", jsonStr));
        }

        if (s && s.ReturnCode == 0 && s.Records instanceof Array && s.Records.length > 0) {
            var records = s.Records;
            var title, subtitle, xAxis = [], yAxisTitle, data = [], unit = cxtype == 1 ? "元" : "", cols = [];
            switch (sjtype) {
                case "1":
                    xAxis = getMonths(sdate, edate, 1);
                    cols = getMonths(sdate, edate, 2);
                    break;
                case "2":
                    xAxis = getSeasons(sdate, edate, 1);
                    cols = getSeasons(sdate, edate, 2);
                    break;
                case "3":
                    xAxis = getYears(sdate, edate, 1);
                    cols = getYears(sdate, edate, 2);
                    break;
            }

            //过滤返回的信息
            if (lxtype == "1") {
                title = "客户销售趋势分析";
                for (var i = 0; i < records.length; i++) {
                    if (records[i].khmc != "环比→") {
                        var item = { name: records[i].khmc, data: [] };
                        for (var j = 0; j < cols.length; j++) {
                            var m = cols[j].name;
                            item.data[j] = isNaN(parseFloat(records[i][m])) ? 0 : (records[i][m] * 1).toFixed(place) * 1;
                        }
                        data.push(item);
                    }
                }
            } else if (lxtype == "2") {
                title = "药品销售趋势分析";
                for (var i = 0; i < records.length; i++) {
                    if (records[i].spmc != "环比→") {
                        var item = { name: records[i].spmc, data: [] };
                        for (var j = 0; j < cols.length; j++) {
                            var m = cols[j].name;
                            item.data[j] = isNaN(parseFloat(records[i][m])) ? 0 : (records[i][m] * 1).toFixed(place) * 1;
                        }
                        data.push(item);
                    }
                }
            } else {
                title = "销售员销售趋势分析";
                for (var i = 0; i < records.length; i++) {
                    if (records[i].zymc != "环比→") {
                        var item = { name: records[i].zymc, data: [] };
                        for (var j = 0; j < cols.length; j++) {
                            var m = cols[j].name;
                            item.data[j] = isNaN(parseFloat(records[i][m])) ? 0 : (records[i][m] * 1).toFixed(place) * 1;
                        }
                        data.push(item);
                    }
                }
            }
            yAxisTitle = cxtype == 1 ? "销售金额（" + unit + "）" : "销售数量";
            subtitle = xAxis.length > 0 ? xAxis[0] + "~" + xAxis[xAxis.length - 1] : "";
            if (xAxis.length > 36) { window.parent.cihoAlert(msg.bb.xsqs, msgBox.dlgBtn.Ok); return; }
            createLineChart("ChartPosition", title, subtitle, xAxis, yAxisTitle, data, unit, place);
            s = records = data = xAxis = cols = null;
        } else {
            $("#ChartPosition").html("<center></center>");
            return;
        }
    } catch (e) { }
}

//根据条件查询报表
function search() {
    try {
        var lxtype = $("#lxtype").combobox("getValue");
        var sjtype = $("#sjtype").combobox("getValue");
        var cxtype = $("#cxtype").combobox("getValue");

        var khdm = $("#khdm").combobox("getValue");
        var spdm = $("#spdm").combobox("getValue");
        var zydm = $("#zydm").combobox("getValue");

        if (khdm == undefined) { khdm = ""; $("#khdm").combobox("setValue", ""); }
        if (spdm == undefined) { spdm = ""; $("#spdm").combobox("setValue", ""); }
        if (zydm == undefined) { zydm = ""; $("#zydm").combobox("setValue", "") }

        var bhth = $("#includeTH").is(":checked");
        var sdate = (sjtype == "1") ? $("#smonth").val() : $("#sdate").combobox("getValue");
        var edate = (sjtype == "1") ? $("#emonth").val() : $("#edate").combobox("getValue");

        if (sjtype == 1) {                      //按月
            var smonth = sdate.replace(/-/g, "/");
            var emonth = edate.replace(/-/g, "/");
        }

        var colModel = [{ sortable: false, editable: false, hidden: true, name: "xh", index: "xh", width: 70, align: "left" }, { sortable: true, editable: false, hidden: true, name: "glxh", index: "glxh", width: 70, align: "left"}];
        var colNames = ["编号", "关联序号"];

        if (lxtype == "1") {
            colNames.push("客户名称");
            colModel.push({ sortable: false, editable: false, name: "khmc", index: "khmc", width: 70, align: "left", formatter: nameFormatter });
            switch (sjtype) {
                case "1":
                    colNames = colNames.concat(getMonths(sdate, edate, 1));
                    colModel = colModel.concat(getMonths(sdate, edate, 2));
                    break;
                case "2":
                    colNames = colNames.concat(getSeasons(sdate, edate, 1));
                    colModel = colModel.concat(getSeasons(sdate, edate, 2));
                    break;
                case "3":
                    colNames = colNames.concat(getYears(sdate, edate, 1));
                    colModel = colModel.concat(getYears(sdate, edate, 2));
                    break;
            }
        } else if (lxtype == "2") {
            colNames.push("药品名称");
            colModel.push({ sortable: false, editable: false, name: "spmc", index: "spmc", width: 70, align: "left", formatter: nameFormatter });
            switch (sjtype) {
                case "1":
                    colNames = colNames.concat(getMonths(sdate, edate, 1));
                    colModel = colModel.concat(getMonths(sdate, edate, 2));
                    break;
                case "2":
                    colNames = colNames.concat(getSeasons(sdate, edate, 1));
                    colModel = colModel.concat(getSeasons(sdate, edate, 2));
                    break;
                case "3":
                    colNames = colNames.concat(getYears(sdate, edate, 1));
                    colModel = colModel.concat(getYears(sdate, edate, 2));
                    break;
            }
        } else if (lxtype == "3") {
            colNames.push("销售员名称");
            colModel.push({ sortable: false, editable: false, name: "zymc", index: "zymc", width: 70, align: "left", formatter: nameFormatter });
            switch (sjtype) {
                case "1":
                    colNames = colNames.concat(getMonths(sdate, edate, 1));
                    colModel = colModel.concat(getMonths(sdate, edate, 2));
                    break;
                case "2":
                    colNames = colNames.concat(getSeasons(sdate, edate, 1));
                    colModel = colModel.concat(getSeasons(sdate, edate, 2));
                    break;
                case "3":
                    colNames = colNames.concat(getYears(sdate, edate, 1));
                    colModel = colModel.concat(getYears(sdate, edate, 2));
                    break;
            }
        }
        if (colModel.length > 39) { window.parent.cihoAlert(msg.bb.xsqs, msgBox.dlgBtn.Ok); return; }
        var jsonStr = '{"sjtype":"' + sjtype + '","sdate":"' + sdate + '","edate":"' + edate + '","khdm":"' + khdm + '","spdm":"' + spdm + '","zydm":"' + zydm + '","bhth":"' + bhth + '","flag":"' + cxtype + '"}';
        var s = null;

        if (lxtype == "1") {                                                            //客户
            s = ParseData(window.external.DoOptions("Tp0216", "GetList", jsonStr));
        } else if (lxtype == "2") {                                                     // 药品
            s = ParseData(window.external.DoOptions("Tp021601", "GetList", jsonStr));
        } else if (lxtype == "3") {                                                     //销售员
            s = ParseData(window.external.DoOptions("Tp021602", "GetList", jsonStr));
        }
        if (s && s.ReturnCode == 0 && s.Records instanceof Array) {
            $("#qsfx").GridUnload();
            if ($("#hb").data("hb")) {                      //显示环比
                createGrid("qsfx", colNames, colModel, s.Records);
            } else {                                        //将环比过滤掉
                var items = [];
                for (var i = 0; i < s.Records.length; i++) {
                    if (s.Records[i].khmc != "环比→" && s.Records[i].spmc != "环比→" && s.Records[i].zymc != "环比→") {                    //records[i].spmc != "环比→"
                        items.push(s.Records[i]);
                    }
                }
                createGrid("qsfx", colNames, colModel, items);
            }
            window.onresize();
        }
    } catch (e) { }
}

//格式化环比
function nameFormatter(cellvalue, options, rowObject) {
    try {
        if (cellvalue == "环比→") {
            return "<font color='#996600'>环比→</font>";
        } else if (cellvalue) {
            return cellvalue;
        } else {
            return "&nbsp;";
        }
    } catch (e) { }
}

//格式化数字
function numFormatter(cellvalue, options, rowObject) {
    try {
        if (cellvalue) {
            var cxtype = $("#cxtype").combobox("getValue");
            if (rowObject.spmc == "环比→" || rowObject.zymc == "环比→" || rowObject.khmc == "环比→") {
                if (cellvalue * 1 < 0) {
                    return "<font color='#996600'>" + (cellvalue * 100).toFixed(window.parent.strPercentPlace) + "%↓</font>";
                } else if (cellvalue * 1 > 0) {
                    return "<font color='green'>" + (cellvalue * 100).toFixed(window.parent.strPercentPlace) + "%↑</font>";
                } else {
                    return "<center>—</center>";
                }
            } else {
                return (cellvalue * 1).toFixed(cxtype == 1 ? window.parent.strMoneyPlace : window.parent.strCountPlace);
            }
        } else {
            return "&nbsp;";
        }
    } 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: "right", formatter: numFormatter });
                    break;
                case 3:
                    years.push({ val: sYear, txt: sYear + "年" });
                    break;
            }
            sYear++;
        }
        return years;
    } catch (e) { }
}

//返回按季度的一级列配置信息（2011年季度）
//startDate 起始时间
//endDate 结束时间
//type：1.列名数组
//          2.列配置
//          3.生成下拉框数据
//          4.药品列配置
function getSeasons(startDate, endDate, type) {
    try {
        var jd = ["一季度", "二季度", "三季度", "四季度"];
        var start, end, sMonth, eMonth, sSeason, eSeason;
        if (type == 3) {
            start = startDate.split('-');
            end = endDate.split('-');
            eMonth = parseInt(end[1], 10);
            sMonth = parseInt(start[1], 10);
            sSeason = Math.ceil(sMonth / 3);
            eSeason = Math.ceil(eMonth / 3);
        } else {
            start = startDate.split('~');
            end = endDate.split('~');
            sSeason = parseInt(start[1], 10);
            eSeason = parseInt(end[1], 10);
        }
        var sYear = parseInt(start[0], 10);
        var eYear = parseInt(end[0], 10);
        var seasons = [];
        while (sYear <= eYear) {
            if (sYear == eYear && sSeason == (eSeason + 1)) {
                break;
            }
            if (sSeason == 5) {
                sYear++;
                sSeason = 1;
            }
            switch (type) {
                case 1:
                    seasons.push(sYear + "年" + jd[sSeason - 1]);
                    break;
                case 2:
                    seasons.push({ sortable: false, editable: false, name: sYear + "~" + sSeason, index: sYear + "~" + sSeason, width: 70, align: "right", formatter: numFormatter });
                    break;
                case 3:
                    seasons.push({ val: sYear + "~" + sSeason, txt: sYear + jd[sSeason - 1] });
                    break;
            }
            sSeason++;
        }
        return seasons;
    } catch (e) { }
}

//求年份和月份，返回格式2011-02
//startDate 起始时间
//endDate 结束时间
//type：1.列名数组
//          2.列配置
//          3.生成下拉框数据
function getMonths(startDate, endDate, type) {
    try {
        var sYear = parseInt(startDate.split('-')[0], 10);
        var sMonth = parseInt(startDate.split('-')[1], 10);
        var eYear = parseInt(endDate.split('-')[0], 10);
        var eMonth = parseInt(endDate.split('-')[1], 10);
        startDate = new Date(sYear, sMonth);
        endDate = new Date(eYear, eMonth);
        if (startDate > endDate) return [];
        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: "right", formatter: numFormatter });
                    } else {
                        months.push({ sortable: false, editable: false, name: sYear + "-" + sMonth, index: sYear + "-" + sMonth, width: 70, align: "right", 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;
            }
            sMonth++;
        }
        return months;
    } catch (e) { }
}

//-----------------------创建线性图表-----------------------
//----bindId---要绑定到的层的Id
//----title------显示的主标题
//----subtitle--显示的副标题
//----xAxis-----x轴显示的数据【用数组格式】
//----yAxisTitle-y轴显示的标题
//----data------显示的json数据【用json格式】格式【[{name:"",data:[]},{name:"",data:[]}]】data数组必须与x轴数组个数相同
//----unit-------计量单位
function createLineChart(bindId, title, subtitle, xAxis, yAxisTitle, data, unit, place) {
    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.toFixed(place) + unit } },
            "legend": { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -10, y: 100, borderWidth: 0 },
            "series": data,
            "plotOptions": { series: { animation: { duration: 3000}} }
        });
    } catch (e) { }
}

//刷新combobox下拉框
function refreshMyCombobox(strModels) {
    try {
        var data;
        for (var i = 0; i < strModels.length; i++) {
            //这里是当前页面有的comgbobox
            if (strModels[i] == "Tspxx") {
                data = getComboboxData(strModels[i] + "2");
                data.unshift({ dm: "", mc: "全部药品" });
                reLoadCombobox("spdm", data);
            }
            if (strModels[i] == "Tkhxx") {
                data = getComboboxData(strModels[i] + "2");
                data.unshift({ dm: "", mc: "全部客户" });
                reLoadCombobox("khdm", data);
            }
            if (strModels[i] == "TZyxx") {
                data = getComboboxData(strModels[i] + "2");
                data.unshift({ dm: "", mc: "全部销售员" });
                data.push({ "dm": "-1", "mc": "其他销售员" });
                reLoadCombobox("zydm", data);
            }
        }
        data = null;
    } catch (e) { }
}

//根据type类型返回日期格式
//type  1:返回年份，格式：2011
//type  2:返回月份，格式：2011-02
//type  3:返回季度，格式：2011~2
function format(date, type) {
    var dateArr = date.match(/^(\d{4})-(\d{2})-(\d{2})$/);
    switch (type) {
        case 1:
            return dateArr[1];
        case 2:
            return dateArr[1] + "-" + dateArr[2];
        case 3:
            var season = Math.ceil(dateArr[2] * 1 / 3);
            return dateArr[1] + "~" + season;
    }
}