var zjhm = '';
var initpage;
var yearBblxDm = ['10414', '10420'];
var ccxwsBblxDm = ['12101']
var Author;
var prefix = "";
$(function() {
    if (config.environmental == 'test' || config.environmental == 'preProduce') {
        prefix = "/web";
    } else if (config.environmental == 'production') {
        prefix = "/web/online";
    }
    showLoading();
    getInitTable();
})

function getInitTable() {
    $.ajax({
        type: "POST",
        url: config.url + "/online/liquidation/tax_info",
        dataType: "json", // 请求方式为jsonp
        // async: false,
        data: {
            djxh: getUrlParam("djxh"),
            token: getUrlParam("token"),
            sbsq: '',
            pzzlDm: getUrlParam("pzzlDm")
        },
        success: function(data, status, xhr) { //客户端jquery预先定义好的callback函数，成功获取跨域服务器上的json数据后，会动态执行这个callback函数
            hideLoading();
            //el表达式变jq
            // $("#token").attr("value","");
            var authorization_sbzj2 = xhr.getResponseHeader("Encryption")
            sessionStorage.setItem("authorization_sbzj2", authorization_sbzj2);
            var companyInfo = data;
            $("#djxh").attr("value", companyInfo.djxh);
            if (companyInfo.returnCode == "00") {
                zjhm = companyInfo.content.zjhm
                Author = companyInfo.content.value
                    // var sbsq = companyInfo.content.sbsq.replace('-','');
                    // if (companyInfo.content.sfyhzctsBz == 'Y'&&sbsq<='202104') {
                    //     myAlert("提示", "尊敬的纳税人、缴费人，为进一步巩固拓展减税降费成效，助力市场主体纾困解难，对部分2020年底到期税费优惠政策（不包括社会保险费），您可暂按原政策文件规定申报享受优惠（原减免性质代码可继续使用）。详细情况可咨询主管税务分局、税务所或12366纳税服务热线。感谢您的理解与支持！！", "确定");
                    // }
                    // tool.hjDialog(companyInfo.content.djxh)出口退税暂不上线
                config.value = companyInfo.content.value // 不一定对
                companyInfo.content.config = config
                initpage = initPage(companyInfo.content);

            } else {
                hideLoading();
                // initpage = initPage("");
                alertWarning(companyInfo.returnMessage);
                if (!companyInfo.bean) {
                    companyInfo.bean = {};
                    Author = companyInfo.content.value
                    companyInfo.bean.djxh = getUrlParam("djxh");
                    companyInfo.bean.return = false;
                }
                companyInfo.bean.config = config
                initpage = initPage(companyInfo.bean);
                return false;
                // 弹出错误对话框
            }
            $("#getInputValue").on("focus", function() {
                WdatePicker({
                    isShowClear: false,
                    dateFmt: 'yyyy-MM',
                    onpicking: function(dp) {
                        initpage.changeDate(this, dp);
                    }
                });
            });
        },
        error: function(xhr) {
            //jsonp 方式此方法不被触发
            console.log("=======error======================")
        }
    })
}
/**
 * 按期申报填报列表页控制脚本
 * 
 * @author 于广洋
 * @modify 王雷
 */
// -------------------------------

/**
 * 绘制税种填报页面
 * 
 * @param {*} companyInfo 
 */
function initPage(companyInfo) {
    getIEVersion();
    var companyInfo = companyInfo;
    var djxh = companyInfo.djxh;
    var nowdate = ""; // 存储当前选择的时间框;
    var submitData
        /**
         * 展示税种申报信息
         */
    var showTax = function(taxInfo) {
        //时间格式化
        $.each(taxInfo, function(i, item) {
            if (item.sssqQ) {
                item.sssqQ = tool.formatDate(item.sssqQ);
            }
            if (item.sssqZ) {
                item.sssqZ = tool.formatDate(item.sssqZ);
            }
            if (item.sbrq) {
                item.sbrq = tool.formatDate(item.sbrq);
            }
            if (item.bblxDm == '30101') {
                item.sssqQ = "-";
                item.sssqZ = "-";
            }
        })
        var id = "#taxGrid";
        var buttonHtml = "填写申报表";
        var order = ["pzzlMc", "djxh", "zgswskfjMc", "sssqQ", "sssqZ", "sbrq", "do"];
        var promptStatement = "";
        var headerList = [{
                name: "序号",
                width: "2%"
            }, {
                name: "申报表",
                width: "30%"
            },
            {
                name: "登记序号",
                width: "12%"
            },
            {
                name: "主管税务所（科、分局）",
                width: "25%"
            },
            {
                name: "税款所属期起",
                width: "7%"
            }, {
                name: "税款所属期止",
                width: "7%"
            }, {
                name: "申报日期",
                width: "7%"
            }, {
                name: "操作",
                width: "10%"
            }
        ];
        //渲染表
        getTableDeclaration(id, order, headerList, taxInfo, buttonHtml, promptStatement)
    };
    /**
     * 展示财务报表申报信息
     */
    var showFinancial = function(financialInfo, type) {
        //时间格式化
        $.each(financialInfo, function(i, item) {
            if (item.sssqQ) {
                item.sssqQ = tool.formatDate(item.sssqQ);
            }
            if (item.sssqZ) {
                item.sssqZ = tool.formatDate(item.sssqZ);
            }
            if (item.sbrq) {
                item.sbrq = tool.formatDate(item.sbrq);
            }
        })
        var id = "#financialGrid";
        var buttonHtml = "填写申报表";
        var order = ["kjzd", "pzzlMc", "djxh", "zgswskfjMc", "sssqQ", "sssqZ", "sbrq", "do"];
        var promptStatement = "";
        if (financialInfo.length < 1 && type == 1) {
            promptStatement = "您尚未进行财务报表类型备案，请先备案后再进行申报";
        }
        var headerList = [{
                name: "序号",
                width: "2%"
            }, {
                name: "财务、会计制度",
                width: "10%"
            }, {
                name: "财务报表报送小类",
                width: "19%"
            }, {
                name: "登记序号",
                width: "11%"
            },
            {
                name: "主管税务所（科、分局）",
                width: "25%"
            },
            {
                name: "报送所属期起",
                width: "7%"
            }, {
                name: "报送所属期止",
                width: "7%"
            }, {
                name: "申报日期",
                width: "7%"
            }, {
                name: "操作",
                width: "10%"
            }
        ];
        //渲染表
        getTableDeclaration(id, order, headerList, financialInfo, buttonHtml, promptStatement)
    };


    /**
     * 税务申报table渲染
     * @param {*} id 
     * @param {*} order 
     * @param {*} headerList 
     * @param {*} ddt 
     * @param {*} buttonHtml 
     */
    var getTableDeclaration = function(id, order, headerList, ddt, buttonHtml, promptStatement) {
        var tableObj = {
            id: id, //tabel父元素的id
            autoHeight: ddt.length > 0 ? 10 : "",
            containerWidth: "99%", //table占父元素的百分比
            autoHeight: ddt.length > 0 ? 10 : "", // 默认10行
            order: order, //数据按照什么顺序排序  1.do为是否保函操作 2.序号列会自动添加不需要写
            onlyId: "uuId", //数据的唯一标识
            height: "320", //表格的高度
            buttonHeight: "", //表格的高度
            buttonHtml: buttonHtml, //按钮里的字
            headerList: headerList, //表头名字及占比，顺序与order对应
            promptStatement: promptStatement, // 没有数据时默认提示
            data: {
                page: "1",
                pageSize: ddt.length
            },
            jsonReady: ddt,
            callback: function(data, node) {
                    data.operateType = '6';
                    data.sbbz = '6';
                    if (data.sbzt == "Y") {
                        myAlert("提示", "当前申报表已经申报", "确定")
                        return false;
                    }
                    data.value = config.value;
                    // 财产行为税
                    if (ccxwsBblxDm.indexOf(data.bblxDm) != -1) {
                        // 测试环境start
                        var openUrl = config.ccxwsTaxTable + '?djxh=' + data.djxh + '&zsDjxh=' + data.zsDjxh + '&nsrsbh=' + data.nsrsbh + '&nsrmc=' + data.nsrmc + '&operateType=cancellation' + '&lybz=online' + '&Authorization=' + Author; //测试环境
                        // var openUrl = config.ccxwsTaxTable +'?lybz=online' +'&operateType=cancellation'+'&sblx=js' + '&token=' + data.token //正式环境
                        window.open(openUrl, '_blank');
                    } else if (data.sourceFlag == "ssfwpt_sbzj") {
                        window.mlistener = {
                            selectRowData: {},
                        };
                        data.fillingFlag = "cancellation" // 填报标记
                        data.saveUserId = "zxtb"; // 用户id
                        data.zjhm = zjhm
                        window.mlistener.selectRowData = data;
                        if (yearBblxDm.indexOf(data.bblxDm) != -1) {
                            data.saveUserId = "zxtb_singleReport"; // 用户id
                            data.userId = "zxtb"; // userId
                            window.open(prefix + config.yearTaxTable, '_blank');
                        } else {
                            window.open(prefix + config.ssfwptPage, '_blank');
                        }
                        Object.defineProperty(mlistener, 'returnSelectRowData', {
                            set: function(val) {
                                setTimeout(function() {
                                    getInitTable()
                                }, 1000);
                            }
                        })
                    } else if (data.sourceFlag == "ssfwpt_sbzj_version_2") {
                        window.mlistener = {
                            selectRowData: {},
                            urlList: {
                                getMenu: '/tax_service/getBbLb', //菜单接口
                                openTable: "/tax_service/open_table", //开表接口
                                getData: "/tax_service/get_data", //提取数据接口  
                                saveTable: "/tax_service/save_single_sbb_info", //保存
                                deleteTable: "/tax_service/delete_single_sbb_info", //删除
                                checkTaxTable: "/tax_service/report_data_validate", //表间校验
                                declareTable: "/tax_service/declare", //申报
                                downloadFile: "/tax_service/load_declare_file", //下载申报文件接口
                                modalSave: "/tax_service/save_pop", //弹窗保存状态
                                modalInquire: "/tax_service/sel_pop", //弹窗查询状态
                                modalRemove: "/tax_service/del_pop", //删除弹窗
                            }
                        };
                        data.fillingFlag = "cancellation" // 填报标记
                        data.flag = '1' //清算标志 1是清算,空是正常开表
                        window.mlistener.selectRowData = data;
                        var openUrl = prefix + config.tableBridge; //测试环境
                        window.open(openUrl, '_blank');
                        Object.defineProperty(mlistener, 'returnSelectRowData', {
                            set: function(val) {
                                setTimeout(function() {
                                    getTaxDeclaration(sbqDate, "N", '2');
                                }, 1000);
                            }
                        })
                    } else {
                        data.djxh = companyInfo.djxh;
                        data.iszzsybjc = companyInfo.iszzsybjc; // 一表申报代码
                        data.nsrsbh = companyInfo.nsrsbh; // 那随人识别号
                        // data.nssbq = nowdate;
                        data.checkTime = false;
                        if (data.pzzlDm === '11602') {
                            var List = companyInfo.taxInfos.filter(function(item) {
                                return item.pzzlDm == '10101' || item.pzzlDm == '10102'
                            })
                            if (List.length === 0) {
                                data.checkTime = true;
                            }
                            for (var i = 0; i < List.length; i++) {
                                if (List[i].sssqQ !== data.sssqQ || List[i].sssqZ !== data.sssqZ) {
                                    data.checkTime = true;
                                    break;
                                }
                            }
                        }

                        var str = location.href;
                        str = str.split("/")[4];
                        if (str && "cancellation" == str.substring(0, 12)) {
                            localStorage.setItem("cancellation", str.substring(0, 12));
                        }
                        submitData = data;
                        declarationMethod("N")
                    }
                } //点击按钮后的回调函数
        };
        var object = tool.tableCreate(tableObj);
    };

    /**
     * 税务申报 初始化数据获取
     * @param {*} mydate
     */
    var url;
    if (companyInfo) {
        url = config.url;
    }
    var getTaxDeclaration = function(date, type) {
        // TODO 开始加载等待动画
        showLoading();
        var param = {
            djxh: djxh,
            operateType: companyInfo.operateType,
            sbsq: date,
            isFresh: type.toUpperCase() == "Y",
            value: config.value
        }
        $.ajax({
            url: url + "/online/declare/getPzzlList",
            data: param,
            type: "POST",
            dataType: "JSON",
            headers: { 'Encryption': sessionStorage.getItem("authorization_sbzj2") },
        }).done(function(data) {
            if (data.success) {
                companyInfo = data.content;
                zjhm = companyInfo.zjhm
                config.value = companyInfo.value;
                if (data.bean) {
                    drawGrid(data.bean);
                }
                if (type == 'Y') {
                    myAlert("提示", "重置清册成功", "确定")
                }
            } else {
                if (data.errmsg != undefined) {
                    alertWarning(data.errmsg);
                } else {
                    alertWarning(data.returnMessage);
                }
            }
        }).always(function(data) {
            hideLoading();
        });
    };
    /**
     * 隐藏modal
     */
    var closeModal = function() {
        $('#ybName #dName').html("");
        $('#myMask #myModal').hide();
    }
    var drawGrid = function(bean) {
        if (bean.taxInfos.length == 0) {
            alertInfo("税费申报暂无数据");
        }
        showTax(bean.taxInfos);
        if (bean.financialInfos.length == 0) {
            showFinancial(bean.financialInfos, 0);
            alertInfo("财务报表报送暂无数据");
        } else {
            if (bean.cwbbbabz == "N") {
                showFinancial([], 1);
            } else if (bean.cwbbbabz != "N") {
                showFinancial(bean.financialInfos, 0);
            }
        }

    };

    /**
     * 日期改变时触发
     * N 非强制刷新
     * @param {*} obj
     * @param {*} dp
     */
    var changeDate = function(obj, dp) {
        date = dp.cal.getNewDateStr();
        nowdate = date; // 给缓存时间赋值
        // 加了一个延时，时间改变后时间框没有收起隐藏就加载数据，没有找到好的解决办法，暂时用延时处理
        setTimeout(function() {
            getTaxDeclaration(date, "N");
        }, 50);

    };

    var refresh = function() {
        myConfirm("消息", "您确定需要重置申报清册吗？点击确定继续", "确定", "取消", function() {
            getTaxDeclaration(nowdate, "Y");
        });
    };
    //申报方式 当iszzsybjc=01同时pzzlDm=010101时，调用改方法
    var declarationMethod = function(statu) {
        submitData.ybjcState = statu;
        submitData.value = config.value;
        if (submitData.sourceFlag == "ssfwpt_sbzj") {
            window.mlistener = {
                selectRowData: {},
            };
            submitData.fillingFlag = "inventory" // 填报标记
            data.saveUserId = "zxtb"; // 用户id
            window.mlistener.selectRowData = submitData;
            if (yearBblxDm.indexOf(data.bblxDm) == -1) {
                window.open(prefix + config.ssfwptPage, '_blank');
            } else {
                data.saveUserId = "zxtb_singleReport"; // 用户id
                data.userId = "zxtb"; // userId
                window.open(prefix + config.yearTaxTable, '_blank');
            }
            Object.defineProperty(mlistener, 'returnSelectRowData', {
                set: function(val) {
                    setTimeout(function() {
                        getTaxDeclaration(nowdate, "N");
                    }, 1000);
                }
            })
        } else if (submitData.sourceFlag == "ssfwpt_sbzj_version_2") {
            window.mlistener = {
                selectRowData: {},
                urlList: {
                    getMenu: '/tax_service/getBbLb', //菜单接口
                    openTable: "/tax_service/open_table", //开表接口
                    getData: "/tax_service/get_data", //提取数据接口  
                    saveTable: "/tax_service/save_single_sbb_info", //保存
                    deleteTable: "/tax_service/delete_single_sbb_info", //删除
                    checkTaxTable: "/tax_service/report_data_validate", //表间校验
                    declareTable: "/tax_service/declare", //申报
                    downloadFile: "/tax_service/load_declare_file", //下载申报文件接口
                    modalSave: "/tax_service/save_pop", //弹窗保存状态
                    modalInquire: "/tax_service/sel_pop", //弹窗查询状态
                    modalRemove: "/tax_service/del_pop", //删除弹窗
                }
            };
            data.fillingFlag = "cancellation" // 填报标记
            data.flag = '1' //清算标志 1是清算,空是正常开表
            window.mlistener.selectRowData = data;
            var openUrl = prefix + config.tableBridge; //测试环境
            window.open(openUrl, '_blank');
            Object.defineProperty(mlistener, 'returnSelectRowData', {
                set: function(val) {
                    setTimeout(function() {
                        getTaxDeclaration(sbqDate, "N", '2');
                    }, 1000);
                }
            })
        } else {
            var falg = "declare";
            localStorage.setItem("data", JSON.stringify(submitData));
            submitData.flag = true;
            submitData.encryptKey = config.value;
            var url = config.spreadUrl + "/online_report/declare/toPzzl?falg=" + falg
            var form = $("#changeForm");
            form.attr('action', url); //通过jquery为action属性赋值
            form.find("#changeForm_data").val(JSON.stringify(submitData));
            form.submit();
            return false;
        }
    }
    if (companyInfo) {
        nowdate = companyInfo.sbsq;
        //var aaa =  {taxInfos:[],financialInfos:[]};
        drawGrid(companyInfo);
    }
    //页面出现滚动条，监听滚动条变化将高赋值给模态框
    window.onscroll = function() {
        $("#myModal").css("top", $(document).scrollTop() + 235);
    }
    return {
        //  declarationMethod: declarationMethod,
        //  closeModal:closeModal
    }
}