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);

        var yplist = getComboboxData("Tspxx2");
        var gyslist = getComboboxData("Tgysxx2");

        $("#lxtype,#sjtype,#gysdm,#spdm").combobox();
        addArrowClass();

        $("#lxtype").combobox({ width: 90, listWidth: 90, panelHeight: 42, editable: false, editable: false, enterDown: function () { showChartOrTable(); }, onSelect: function () { showChartOrTable(); } });
        $("#sjtype").combobox({
            width: 70,
            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;
                }
            }
        });
        $("#gysdm").combobox({
            valueField: "dm",
            textField: "mc",
            width: 110,
            onblur: function () {
                if ($(this).combobox("getText") == "") {
                    $(this).combobox("setValue", "");
                }
            },
            onfocus: function () {
                if ($(this).combobox("getText") == "全部供应商") {
                    $(this).combobox("setText", "");
                }
            }
        });
        $("#spdm").combobox({
            valueField: "dm",
            textField: "mc",
            width: 120,
            onblur: function () {
                if ($(this).combobox("getText") == "") {
                    $(this).combobox("setValue", "");
                }
            },
            onfocus: function () {
                if ($(this).combobox("getText") == "全部药品") {
                    $(this).combobox("setText", "");
                }
            }
        });
        $("#sdate,#edate").combobox({
            valueField: "val",
            textField: "txt",
            width: 90,
            editable: false
        });

        gyslist.unshift({ "dm": "", "mc": "全部供应商" });
        yplist.unshift({ "dm": "", "mc": "全部药品" });

        $("#gysdm").combobox("loadData", gyslist);
        $("#spdm").combobox("loadData", yplist);
        $("#gysdm,#spdm").combobox("setValue", "");

        $("#smonth").val(startMonth);
        $("#emonth").val(endMonth);
        $("#smonth,#emonth").monthpicker();
        addArrowClass();
        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");
        });
    } catch (e) { }
}

//显示表格或曲线图
function showChartOrTable() {
    try {
        if (showState == 1) {
            $("#divTable").hide();
            $("#divChart").show();
            showChart();
        } else {
            $("#divChart").hide();
            $("#divTable").show();
            search();
        }
    } 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;
                case 4:
                    years.push({ sortable: false, editable: false, name: sYear + "_je", index: sYear + "_je", width: 70, align: "right", formatter: numFormatter });
                    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, align: "right", name: sYear + "~" + sSeason, index: sYear + "~" + sSeason, width: 70, formatter: numFormatter });
                    break;
                case 3:
                    seasons.push({ val: sYear + "~" + sSeason, txt: sYear + jd[sSeason - 1] });
                    break;
                case 4:
                    seasons.push({ sortable: false, editable: false, align: "right", name: sYear + "~" + sSeason + "_je", index: sYear + "~" + sSeason + "_je", width: 70, formatter: numFormatter });
                    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, align: "right", name: sYear + "-0" + sMonth, index: sYear + "-0" + sMonth, width: 70, formatter: numFormatter });
                    } else {
                        months.push({ sortable: false, editable: false, align: "right", name: sYear + "-" + sMonth, index: sYear + "-" + sMonth, width: 70, 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, align: "right", name: sYear + "-0" + sMonth + "_je", index: sYear + "-0" + sMonth + "_je", width: 70, formatter: numFormatter });
                    } else {
                        months.push({ sortable: false, editable: false, align: "right", name: sYear + "-" + sMonth + "_je", index: sYear + "-" + sMonth + "_je", width: 70, formatter: numFormatter });
                    }
                    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) {
    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(window.top.strMoneyPlace) + unit } },
            "legend": { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -10, y: 100, borderWidth: 0 },
            "series": data,
            "plotOptions": { series: { animation: { duration: 3000}} }
        });
    } catch (e) { }
}

//生成图表
function showChart() {
    try {
        var sjtype = $("#sjtype").combobox("getValue");
        var lxtype = $("#lxtype").combobox("getValue");

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

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

        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 = '{"lxtype":"' + lxtype + '","sjtype":"' + sjtype + '","sdate":"' + sdate + '","edate":"' + edate + '","gysdm":"' + gysdm + '","spdm":"' + spdm + '"}';
        var s = ParseData(window.external.DoOptions("Tp0115", "GetList", jsonStr));
        if (s.ReturnCode == 0 && s.Records instanceof Array) {
            if (s.Records.length == 0) {
                $("#ChartPosition").html("<center></center>");
                return;
            }
        }

        var records = s.Records;
        var title, subtitle, xAxis = [], yAxisTitle, data = [], unit = "元", 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].gysmc != "环比→") {
                    var item = { name: records[i].gysmc, 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(window.parent.strMoneyPlace) * 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 + "_je";
                        item.data[j] = isNaN(parseFloat(records[i][m])) ? 0 : (records[i][m] * 1).toFixed(window.parent.strMoneyPlace) * 1;
                    }
                    data.push(item);
                }
            }
        }
        yAxisTitle = "采购金额（" + unit + "）";
        subtitle = xAxis.length > 0 ? xAxis[0] + "~" + xAxis[xAxis.length - 1] : "";
        if (xAxis.length > 36) { window.parent.cihoAlert(msg.bb.cgqs, msgBox.dlgBtn.Ok); return; }
        createLineChart("ChartPosition", title, subtitle, xAxis, yAxisTitle, data, unit);
    } catch (e) { }
}

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

        var gysdm = $("#gysdm").combobox("getValue");
        var spdm = $("#spdm").combobox("getValue");
        if (gysdm == undefined) { $("#gysdm").combobox("setValue", ""); gysdm = ""; }
        if (spdm == undefined) { $("#spdm").combobox("setValue", ""); spdm = ""; }

        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, align: "left", name: "xh", index: "xh", width: 70 }, { sortable: false, editable: false, align: "left", hidden: true, name: "glxh", index: "glxh", width: 70, align: "center"}];
        var colNames = ["编号", "关联序号"];

        if (lxtype == "1") {
            colNames.push("供应商名称");
            colModel.push({ sortable: false, editable: false, align: "left", name: "gysmc", index: "gysmc", width: 70, 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, align: "left", name: "spmc", index: "spmc", width: 70, formatter: nameFormatter });
            switch (sjtype) {
                case "1":
                    colNames = colNames.concat(getMonths(sdate, edate, 1));
                    colModel = colModel.concat(getMonths(sdate, edate, 4));
                    break;
                case "2":
                    colNames = colNames.concat(getSeasons(sdate, edate, 1));
                    colModel = colModel.concat(getSeasons(sdate, edate, 4));
                    break;
                case "3":
                    colNames = colNames.concat(getYears(sdate, edate, 1));
                    colModel = colModel.concat(getYears(sdate, edate, 4));
                    break;
            }
        }
        if (colModel.length > 39) { window.parent.cihoAlert(msg.bb.cgqs, msgBox.dlgBtn.Ok); return; }
        var jsonStr = '{"lxtype":"' + lxtype + '","sjtype":"' + sjtype + '","sdate":"' + sdate + '","edate":"' + edate + '","gysdm":"' + gysdm + '","spdm":"' + spdm + '"}';
        var s = ParseData(window.external.DoOptions("Tp0115", "GetList", jsonStr));

        if (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].spmc != "环比→" && s.Records[i].gysmc != "环比→") {                    //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) {
            if (rowObject.spmc == "环比→" || rowObject.gysmc == "环比→") {
                if (cellvalue * 1 > 0) {
                    return "<font color='green'>" + (cellvalue * 100).toFixed(window.parent.strPercentPlace) + "%↑</font>";
                } else if (cellvalue * 1 < 0) {
                    return "<font color='#996600'>" + (cellvalue * 100).toFixed(window.parent.strPercentPlace) + "%↓</font>";
                } else {
                    return "<center>—</center>";
                }
            } else {
                return (cellvalue * 1).toFixed(window.parent.strMoneyPlace);
            }
        } else {
            return "&nbsp;";
        }
    } catch (e) { }
}


//刷新管理界面的combobox
function refreshMyCombobox(strModels) {
    try {
        for (var i = 0; i < strModels.length; i++) {
            var data;
            //这里是当前页面有的comgbobox
            if (strModels[i] == "Tspxx") {
                data = getComboboxData(strModels[i] + "2");
                data.unshift({ dm: "", mc: "全部药品" });
                reLoadCombobox("spdm", data);
            }
            if (strModels[i] == "Tgysxx") {
                data = getComboboxData(strModels[i] + "2");
                data.unshift({ dm: "", mc: "全部供应商" });
                reLoadCombobox("gysdm", data);
            }
        }
    } 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;
    }
}