/**
 * 供应商绩效考核计划明细页面JS
 *
 */

var page = {
    tmpNameMap: {},
    submitFlag: 0,
    title: '',
    filePath: '',
    el: {
        planTitle: '#planTitle',
        evaluationCycle: '#evaluationCycle',
        evaluationDate: '#evaluationDate',
        remark: '#remark'
    },
    initForm: function () {
        //日期选择对象
        var p = $(page.el.evaluationDate).datebox('panel'),
            //日期选择对象中月份
            tds = false,
            //显示月份层的触发控件
            span = p.find('span.calendar-text');
        $(page.el.evaluationDate).datebox({
            //显示日趋选择对象后再触发弹出月份层的事件，初始化时没有生成月份层
            onShowPanel: function () {
                //触发click事件弹出月份层
                span.trigger('click');
                if (!tds)
                    //延时触发获取月份对象，因为上面的事件触发和对象生成有时间间隔
                    setTimeout(function () {
                        tds = p.find('div.calendar-menu-month-inner td');
                        tds.click(function (e) {
                            //禁止冒泡执行easyui给月份绑定的事件
                            e.stopPropagation();
                            //得到年份
                            var year = /\d{4}/.exec(span.html())[0],
                                //月份
                                //之前是这样的month = parseInt($(this).attr('abbr'), 10) + 1;
                                month = parseInt($(this).attr('abbr'), 10);

                            //隐藏日期对象
                            $(page.el.evaluationDate).datebox('hidePanel')
                                //设置日期的值
                                .datebox('setValue', year + '-' + month);
                        });
                    }, 0);
            },
            //配置parser，返回选择的日期
            parser: function (s) {
                if (!s) return new Date();
                var arr = s.split('-');
                return new Date(parseInt(arr[0], 10), parseInt(arr[1], 10) - 1, 1);
            },
            //配置formatter，只返回年月 之前是这样的d.getFullYear() + '-' +(d.getMonth());
            formatter: function (d) {
                var currentMonth = (d.getMonth() + 1);
                var currentMonthStr = currentMonth < 10 ? ('0' + currentMonth) : (currentMonth + '');
                return d.getFullYear() + '-' + currentMonthStr;
            }
        });
    },
    fileUpload: function () {
        var filebox = $("#file_box").filebox("files");
        if (filebox.length == 1) {
            var formData = new FormData();
            formData.append("file", filebox[0]);
            fileUploadAjaxWithCall(formData, function (d) {
                page.filePath = d.id;
                $("#fileName").html(d.fileName);
                $("#fileName").attr('href', g.ctx + 'pc/sys/file/rest/download/' + d.id);
                $("#file_box").filebox("clear")
            }, false);
        }
    },
    loadData: function () {
        if (id !== 0) {
            $.ajax({
                url: g.ctx + 'pc/spe/supAppraisePlan/rest/detail?id=' + id,
                type: "GET",
                success: function (data) {
                    page.filePath = data.importFile;
                    $("#fileName").html(data.fileName);
                    $("#fileName").attr('href', g.ctx + 'pc/sys/file/rest/download/' + data.importFile);
                    for (var prop in data) {
                        var val = data[prop];
                        switch (prop) {
                            case 'planCode':
                            case 'planTitle':
                            case 'remark':
                                $("#" + prop).textbox("setValue", val);
                                break;
                            case 'templateId':
                            case 'evaluationCycle':
                            case 'companyCode':
                                $("#" + prop).combobox("setValue", val);
                                break;
                            case 'evaluationDate':
                                $("#" + prop).datebox("setValue", val);
                                break;
                            default:
                                $("#" + prop).val(val);
                                break;
                        }
                    }
                }
            });
        }
    },
    getPlanTitle: function () {
        var dateVal = $("#evaluationDate").datebox('getValue') + '';
        if (dateVal === '') {
            return;
        }
        var year = dateVal.split('-')[0];
        var month = dateVal.split('-')[1];
        var cycle = $("#evaluationCycle").combobox("getValue");
        var tmpName = '';
        if ($("#templateId").combobox("getValue")) {
            tmpName = page.tmpNameMap[$("#templateId").combobox("getValue")];
        }
        switch (cycle) {
            case '1':
                $("#planTitle").textbox('setValue', year + "年度考核计划(" + tmpName + ")");
                break;
            case '2':
                if (1 <= parseInt(month) && parseInt(month) <= 3) {
                    $("#planTitle").textbox('setValue', year + "年度第1季度考核计划(" + tmpName + ")");
                } else if (4 <= parseInt(month) && parseInt(month) <= 6) {
                    $("#planTitle").textbox('setValue', year + "年度第2季度考核计划(" + tmpName + ")");
                } else if (7 <= parseInt(month) && parseInt(month) <= 9) {
                    $("#planTitle").textbox('setValue', year + "年度第3季度考核计划(" + tmpName + ")");
                } else {
                    $("#planTitle").textbox('setValue', year + "年度第4季度考核计划(" + tmpName + ")");
                }
                break;
            case '3':
                $("#planTitle").textbox('setValue', year + "年度第" + month + "月度考核计划(" + tmpName + ")");
                break
        }
    },
    evaluationDateChange: function (v1, v2) {
        page.getPlanTitle();
    },
    cycleChange: function (val, val2) {
        var url = g.ctx + 'pc/spe/supAppraiseTemplate/rest/listAll' + '?types=' + val + ",-1";
        $('#templateId').combobox("clear");
        $('#templateId').combobox("reload", url);
        page.getPlanTitle();
    },
    tmplLoadSuccess: function (data) {
        page.tmpNameMap = {}
        $.each(data, (idx, itm) => {
            page.tmpNameMap[itm.id] = itm.templateName
        })
    },
    tmplChange: function (val, val2) {
        page.getPlanTitle();
    },
    dateFormatter: function () {
        //获取年份
        var y = date.getFullYear();
        //获取月份
        var m = date.getMonth() + 1;
        return y + '-' + m;
    },
    fileClick: function () {
        $("#filePick .filebox-label").click();
    },
    download: function () {
        var tmplId = $('#templateId').combobox("getValue");
        if (tmplId === undefined || tmplId === '') {
            topWin.layer.alert('请先选择模板!', {icon: 2});
            return;
        }
        var dateVal = $("#evaluationDate").datebox('getValue') + '';
        if (dateVal === '') {
            topWin.layer.alert('请先选择考核时间', {icon: 2});
            return;
        }
        var year = dateVal.split('-')[0];
        var month = dateVal.split('-')[1];
        window.open(g.ctx + 'pc/spe/supAppraiseTemplate/rest/exportTemplate?templateId=' + tmplId
            + '&date=' + year + "-" + month);
    },
    bindEvent: function () {
        $("#file_upload").bind("click", page.fileClick);
        $("#download").bind('click', page.download);
    },
    saveData: function (call) {
        if (page.submitFlag == 1) {
            return;
        }
        page.submitFlag = 1;
        var passFlag = $("#dataForm").form("validate");
        if (!passFlag) {
            return;
        }
        var array = $('#dataForm').serializeArray();
        var postData = {};
        $.each(array, function (index, item) {
            postData[item.name] = item.value;
        });
        postData.importFile = page.filePath;
        postData.id = id;
        postData.templateId = $('#templateId').combobox("getValue");
        var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/spe/supAppraisePlan/rest/saveOrUpdate',
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(postData),
            complete: function () {
                page.submitFlag = 0;
                topWin.layer.close(loading);
            },
            success: function (data) {
                call();
            }, error: function (d) {
                topWin.layer.alert(d.responseJSON.message, {icon: 2});
            }
        });
    }
};
$(function () {
    page.initForm();
    page.bindEvent();
    page.loadData();
});

