/**
 * @Title: amend_grid.js
 * @Description: 申报更正控制脚本
 * @author ygy
 * @date 2018/12/16 20:08
 */
var zjhm = '';
var initpage;
var nbbd10414 = "";
var nbbd10420 = "";
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/amend/index",
        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();
            var authorization_sbzj2 = xhr.getResponseHeader("Encryption")
            sessionStorage.setItem("authorization_sbzj2", authorization_sbzj2);
            var companyInfo = data;
            $("#djxh").attr("value", companyInfo.djxh);
            if (companyInfo.success) {
                zjhm = companyInfo.bean.zjhm
                sfyhzctsBz = companyInfo.bean.sfyhzctsBz
                    // var skssqz = companyInfo.bean.sbqz.replace('-','')
                    // if (companyInfo.bean.sfyhzctsBz == 'Y'&&skssqz<='20210331') {
                    //     myAlert("提示", "尊敬的纳税人、缴费人，为进一步巩固拓展减税降费成效，助力市场主体纾困解难，对部分2020年底到期税费优惠政策（不包括社会保险费），您可暂按原政策文件规定申报享受优惠（原减免性质代码可继续使用）。详细情况可咨询主管税务分局、税务所或12366纳税服务热线。感谢您的理解与支持！！", "确定");
                    // }
                    // tool.hjDialog(companyInfo.bean.djxh)出口退税暂不上线
                config.value = companyInfo.bean.value
                companyInfo.bean.config = config
                nbbd10414 = companyInfo.bean.nbbd10414;
                nbbd10420 = companyInfo.bean.nbbd10420;
                initpage = initPage(companyInfo.bean);
            } else {
                hideLoading();
                if (companyInfo.errmsg != undefined) {
                    alertWarning(companyInfo.errmsg);
                } else {
                    alertWarning(companyInfo.returnMessage);
                }
                if (!companyInfo.bean) {
                    companyInfo.bean = {};
                    companyInfo.bean.djxh = getUrlParam("djxh");
                    companyInfo.bean.return = false;
                }
                companyInfo.bean.config = config
                initpage = initPage(companyInfo.bean);
                // 弹出错误对话框
            }
        },
        error: function(xhr) {
            //jsonp 方式此方法不被触发
            console.log("=======error======================")
        }
    })
}
/**
 * @Description: 入口
 * @param  companyInfo
 * @return
 * @throws
 * @author ygy
 * @date 2018/12/16 20:09
 */
var yearBblxDm = ['10414', '10420'];

function initPage(companyInfo) {
    getIEVersion();
    localStorage.setItem("cancellation", null);
    var companyInfo = companyInfo;
    // 以下是初始化数据，用来缓存
    var initPagingNum = 20;
    var pagingData = []; //存放分页数据
    // 缓存后台查询数据
    var sourceData = [];
    var newData = []; //新数据
    var declareDate = " "; // 缓存申报日期
    var durationOfTaxStart = ""; //缓存查询时间
    var durationOfTaxEnd = ""; //缓存查询时间
    var param = {};
    /**
     * @Description: 渲染更正table列表
     * @param
     * @return
     * @author ygy
     * @date 2018/12/16 20:30
     */
    var taxAmendGrid = function(ddt) {
            var declarationDateStart = $("#declarationDateStart").val();
            var declarationDateEnd = $("#declarationDateEnd").val();
            declareDate = declarationDateStart + " " + declarationDateEnd; // 临时存储date 可能用于时间比对，赋值给时间全局变量
            var id = "#taxAmendGrid";
            var buttonHtml = "更正申报";
            var order = ["bblxMc", "djxh", "zgswskfjMc", "sbrq", "skssqq", "skssqz", "ybtse", "do"];
            var headerList = [{
                    name: "序号",
                    width: "3%"
                }, {
                    name: "申报表名称",
                    width: "22%"
                }, {
                    name: "登记序号",
                    width: "13%"
                },
                {
                    name: "主管税务所（科、分局）",
                    width: "24%"
                },
                {
                    name: "原申报日期",
                    width: "7%"
                }, {
                    name: "税款所属期起",
                    width: "7%"
                }, {
                    name: "税款所属期止",
                    width: "7%"
                }, {
                    name: "更正前应补退税额",
                    width: "7%"
                }, {
                    name: "操作",
                    width: "10%"
                }
            ];
            //渲染表
            getTableDeclaration(id, order, headerList, ddt, buttonHtml);
        }
        /**
         * @Description: 初始化table
         * @param
         * @return
         * @author ygy
         * @date 2018/12/16 20:31
         */
    var getTableDeclaration = function(id, order, headerList, ddt, buttonHtml) {
        var tableObj = {
            id: id, //tabel父元素的id
            autoHeight: 10,
            containerWidth: "99%", //table占父元素的百分比
            order: order, //数据按照什么顺序排序  1.do为是否保函操作 2.序号列会自动添加不需要写
            onlyId: "sbuuid", //数据的唯一标识
            height: "320", //表格的高度
            buttonHeight: "70", //表格的高度
            buttonHtml: buttonHtml, //按钮里的字
            headerList: headerList, //表头名字及占比，顺序与order对应
            data: {
                page: "1",
                pageSize: "20"
            },

            jsonReady: ddt,
            callback: function(data, node) {
                    data.operateType = '4';
                    data.sbbz = '4';
                    data.value = config.value;
                    if (data.sourceFlag == "ssfwpt_sbzj") {
                        window.mlistener = {
                            selectRowData: {},
                        };
                        data.fillingFlag = "corrections" // 填报标记
                        data.saveUserId = "zxtb"; // 用户id
                        data.zjhm = zjhm //证件号码
                        window.mlistener.selectRowData = data;
                        if (yearBblxDm.indexOf(data.bblxDm) == -1) {
                            window.open(prefix + config.ssfwptPage, '_blank');
                        } else {
                            if (data.bblxDm == '10414' && nbbd10414 != 'Y') {
                                myAlert("提示", "尊敬的纳税人：为了保证更正数据的准确性，只有在本系统申报的企业才可以进行更正操作。您未在本系统申报，不能在本系统更正。", "确定");
                            } else if (data.bblxDm == '10420' && nbbd10420 != 'Y') {
                                myAlert("提示", "尊敬的纳税人：为了保证更正数据的准确性，只有在本系统申报的企业才可以进行更正操作。您未在本系统申报，不能在本系统更正。", "确定");
                            } 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() {
                                    param = { //根据后台接收方式进行修改
                                        djxh: companyInfo.djxh, //登记序号
                                        sbrqq: durationOfTaxStart, // 申报日期起
                                        sbrqz: durationOfTaxEnd, // 申报日期止
                                        gzCacheKey: companyInfo.gzCacheKey, //登记序号
                                        zjhm: zjhm //证件号码
                                    }
                                    getTaxAmendData(param);
                                }, 1000);
                            }
                        })
                    } else if (data.sourceFlag == "ssfwpt_sbzj_version_2") { //税表组件2.0
                        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", //下载申报文件接口
                                correctTax: "/tax_service/get_gz_tax_and_declare", //更正接口
                                modalSave: "/tax_service/save_pop", //弹窗保存状态
                                modalInquire: "/tax_service/sel_pop", //弹窗查询状态
                                modalRemove: "/tax_service/del_pop", //删除弹窗
                            }
                        };
                        data.sfyhzctsBz = sfyhzctsBz //首次进表标志
                        data.fillingFlag = "corrections" // 填报标记
                        data.flag = '' //清算标志 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 {
                        //TODO 跳转页面
                        data.djxh = companyInfo.djxh;
                        data.nssbqq2 = durationOfTaxStart;
                        data.nssbqz2 = durationOfTaxEnd;
                        data.gzCacheKey = companyInfo.gzCacheKey;
                        data.checkTime = false;
                        if (data.bblxDm === '11602') {
                            var List = companyInfo.gzTaxInfos.filter(function(item) {
                                return item.bblxDm == '10101' || item.bblxDm == '10102'
                            })
                            if (List.length === 0) {
                                data.checkTime = true;
                            }
                            for (var i = 0; i < List.length; i++) {
                                if (List[i].skssqq !== data.skssqq || List[i].skssqz !== data.skssqz) {
                                    data.checkTime = true;
                                    break;
                                }
                            }
                        }
                        var requestData = data;
                        var falg = "amend";
                        requestData.flag = true;
                        requestData.encryptKey = config.value;
                        localStorage.setItem("data", requestData);
                        var url = config.spreadUrl + "/online_report/amend/toGzPzzl?falg=" + falg
                        var form = $("#changeForm_amend");
                        form.attr('action', url); //通过jquery为action属性赋值
                        form.find("#changeForm_data").val(JSON.stringify(requestData));
                        form.submit();
                        return false;
                    }
                } //点击按钮后的回调函数
        };
        var object = tool.tableCreate(tableObj);
    }

    /**
     * @Description: // 查询点击事件 // 根据申报日期起、止来判断是否需要查询后台
     * @author ygy
     * @date 2018/12/16 20:56 
     */

    $("#getAmendData").click(function() {
        var declarationDateStart = $("#declarationDateStart").val();
        var declarationDateEnd = $("#declarationDateEnd").val();
        var declarationDate = " ";
        declarationDate = declarationDateStart + " " + declarationDateEnd;
        durationOfTaxStart = $("#durationOfTaxStart").val();
        durationOfTaxEnd = $("#durationOfTaxEnd").val();
        //var temporaryDate = declarationDateStart + " " + declarationDateEnd; // 临时存储date 可能用于时间比对，赋值给时间全局变量
        // 用于查询后台的参数，提前整理好
        param = { //根据后台接收方式进行修改
            djxh: companyInfo.djxh, //登记序号
            sbrqq: durationOfTaxStart, // 申报日期起
            sbrqz: durationOfTaxEnd, // 申报日期止
            gzCacheKey: companyInfo.gzCacheKey, //登记序号
        }
        getTaxAmendData(param); // 如果税款所属期起止：没数据 去查
    });

    /**
     * 获取的源数据进行数据处理
     */
    var handleSourceData = function(temporaryDate, durationOfTaxStart, durationOfTaxEnd) {
            // 遍历缓存数据，将符合条件的存储到新数组中（时间，申报表名称）
            newData = [];
            if (!durationOfTaxStart && !durationOfTaxEnd) {
                newData = sourceData;
            } else {
                for (var i = 0; i < sourceData.length; i++) {
                    // 比对名称，时间起止
                    if ((!tool.bijiaodata(durationOfTaxStart, sourceData[i].skssqq) && tool.bijiaodata(durationOfTaxEnd, sourceData[i].skssqq) &&
                            (!tool.bijiaodata(durationOfTaxStart, sourceData[i].skssqz) && tool.bijiaodata(durationOfTaxEnd, sourceData[i].skssqz)))) {
                        newData.push(sourceData[i]); // 放新数组中
                    } else
                    if (temporaryDate == " " && declarationDate == " ") {
                        newData.push(sourceData[i]); // 放新数组中
                    }
                }
            }
            declareDate = temporaryDate;
            pagingDataFun(newData, 1, initPagingNum);
            taxAmendPaging("#taxAmendPaging", newData); //调用分页
        }
        /**
         * @Description:查询列表数据
         * @param
         * @return 
         * @author ygy
         * @date 2018/12/16 21:10 
         */
    var url = companyInfo.config.url;
    var getTaxAmendData = function(param) {
        param.value = config.value;
        // TODO 开始加载等待动画
        showLoading();
        $.ajax({
            url: url + "/online/amend/getPzzlList",
            data: param,
            type: "POST",
            dataType: "JSON",
            headers: {
                'Encryption': sessionStorage.getItem("authorization_sbzj2")
            },
        }).done(function(data) {
            if (data.success) {
                zjhm = data.bean.zjhm
                sourceData = data.bean.gzTaxInfos;
                nbbd10414 = data.bean.nbbd10414;
                nbbd10420 = data.bean.nbbd10420;
                newData = sourceData;
                if (newData.length == 0) {
                    alertInfo("选择区间暂无数据");
                }
                sourceData.map(function(item) {
                    item.ybtse = Number(item.ybtse)
                })
                companyInfo = data.bean;
                config.value = companyInfo.value;
                pagingDataFun(sourceData, 1, initPagingNum);
                taxAmendGrid(sourceData);

            } else {
                if (data.errmsg != undefined) {
                    alertWarning(data.errmsg);
                } else {
                    alertWarning(data.returnMessage);
                }
            }
        }).always(function(data) {
            hideLoading();
        });

    }

    /**
     * @Description: 更正列表的分页
     * @author ygy
     * @date 2018/12/17 13:58 
     */
    var taxAmendPaging = function(id, data) {
            $("#taxAmendPaging").remove();
            var html = '<div style="float:right;margin-right: 15px;" id="taxAmendPaging" class="page_divContainer">' +
                '<div class="div-float"></div>';
            $("#father-paging").append(html);
            $(id).pagingTable({
                pageNo: 1, //开始时选中的页数
                pageSize: initPagingNum, //每页条数
                totalSize: newData.length, //总条数
                callback: function(num, num2) {
                    num = parseInt(num);
                    num2 = parseInt(num2);
                    if (parseInt(num2) != initPagingNum) {
                        initPagingNum = parseInt(num2);
                        pagingDataFun(newData, parseInt(num), parseInt(num2));
                        return false;
                    } else {
                        taxAmendGrid(pagingData[num - 1]);
                        return false;
                    }

                }
            })
        }
        /**
         * 分页拆分数组
         * @param {分页数据} data 
         * @param {默认第一页码} page 
         * @param {每页默认多少条} num 
         */
    var pagingDataFun = function(data, page, num) {
        pagingData = []; // 调用该方法，就清空原数组的数据
        if (num >= data.length) {
            pagingData = data;
            taxAmendPaging("#taxAmendPaging", pagingData); // 分页停留在第一页
            taxAmendGrid(pagingData);
        } else {
            for (var i = 0; i < data.length / num; i++) {
                pagingData.push(data.slice(i * num, num * (i + 1)));
            }
            taxAmendPaging("#taxAmendPaging", pagingData[0]); // 分页停留在第一页
            taxAmendGrid(pagingData[page - 1]);
        }
    }
    durationOfTaxStart = tool.formatDate(companyInfo.sbqq);
    durationOfTaxEnd = tool.formatDate(companyInfo.sbqz);
    $("#durationOfTaxStart").attr("value", tool.formatDate(companyInfo.sbqq));
    $("#durationOfTaxEnd").attr("value", tool.formatDate(companyInfo.sbqz));
    newData = companyInfo.gzTaxInfos
    if (newData && newData.length > 0) {
        pagingDataFun(newData, 1, initPagingNum);
    }
    return {}
}