/**
 * @Title: amend_grid.js
 * @Description: 申报更正控制脚本
 * @author ygy
 * @date 2018/12/16 20:08
 */

/**
 * @Description: 入口
 * @param  companyInfo
 * @return
 * @throws
 * @author ygy
 * @date 2018/12/16 20:09
 */
function initPage(companyInfo) {
    getIEVersion();
    localStorage.setItem("cancellation", null);
    var companyInfo = companyInfo;
    console.log(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", "sbrq", "skssqq", "skssqz", "ybtse", "do"];
            var headerList = [{
                name: "序号",
                width: "5%"
            }, {
                name: "申报表名称",
                width: "45%"
            }, {
                name: "原申报日期",
                width: "10%"
            }, {
                name: "税款所属期起",
                width: "10%"
            }, {
                name: "税款所属期止",
                width: "10%"
            }, {
                name: "更正前应补退税额",
                width: "10%"
            }, {
                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,
            // buttonControlArr:[{html:"办理",classA:"doCollectArr"},{html:"删除",classA:"deletCollectArr"}],
            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) {
                console.log("一条数据信息", data)
                console.log(data.sourceFlag, data.sourceFlag.indexOf("sbzj") != -1)
                if (data && data.sourceFlag.indexOf("sbzj") != -1) {
                    window.mlistener = {
                        selectRowData: {},
                    };
                    // data.fillingFlag = "normal" // 填报标记
                    data.saveUserId = "201" + "15232119930731392X";// 用户id
                    window.mlistener.selectRowData = data;
                    window.open("http://192.168.105.153:8088/taxservicedesk/#/taxTableList");
                    // window.open("http://192.168.101.146:81/#/taxTableList");
                    return
                }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 form = $("#changeForm_amend");
                    // form.find("#changeForm_data").val(JSON.stringify(data));
                    // form.submit();

                    var requestData = JSON.stringify(data);
                    var falg = "amend";
                    $.ajax({
                        type: "POST",
                        // url: url + "/online_report/amend/toGzPzzl",
                        url: url + "/ssfwpt/amend/toGzPzzl",
                        dataType: "json",  // 请求方式为jsonp
                        data: {
                            data: requestData
                        },
                        success: function (data) {
                            localStorage.setItem("data", requestData);
                            if (data.url == "../declare/edit.jsp") {
                                window.open("/jsp/declare/edit.html?falg="+falg);
                            }else if (data.url == "../declare/yearReport.jsp") {
                                window.open("/jsp/declare/yearReport.html?falg="+falg);
                            }else if (data.url == "../declare/yearReportGLB.jsp") {
                                window.open("/jsp/declare/yearReportGLB.html?falg="+falg);
                            }else {
                                window.open("/jsp/error/index.html?falg="+falg);
                            }
                        },
                        error: function(xhr){
                            //jsonp 方式此方法不被触发
                            console.log("=======error======================")
                        }
                    })
                }
            } //点击按钮后的回调函数
        };
        var object = tool.tableCreate(tableObj);
        //  object.jsonReadyTo(ddt, { page: "1", pageSize: ddt.length });
    }

    /**
     * @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 , //登记序号
        }
        // if (tool.bijiaodata(durationOfTaxStart, durationOfTaxEnd)) {
        //     alertInfo("税款所属期起必须小于等于税款所属期止！");
        //     return false;
        // }
        // if (temporaryDate == declareDate) { // 本次和上次一样，本地处理
        //     handleSourceData(temporaryDate, durationOfTaxStart, durationOfTaxEnd) //初始数据处理
        // } else {
        //     $("#durationOfTaxStart").val(""); // 每次去查询后台请求数据，将税款所属期起止清空
        //     $("#durationOfTaxEnd").val("");
        //     getTaxAmendData(param); // 如果税款所属期起止：没数据 去查
        // }
        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 
         */
    //地址
    //http://sbjs.tjsat.gov.cn:18090
    //http://localhost:7070
    var url = localStorage.getItem("url");
    var getTaxAmendData = function(param) {
        // TODO 开始加载等待动画
        showLoading();
        $.ajax({
            // url: url + "/online_report/amend/getPzzlList", // 查询接口
            url: url + "/ssfwpt/amend/getPzzlList",
            data: param,
            type: "POST",
            dataType: "JSON"
        }).done(function(data) {
            if (data.success) {
                sourceData = data.bean.gzTaxInfos;
                newData = sourceData;
                if(newData.length==0){
                    alertInfo("选择区间暂无数据");
                }
                sourceData.map(function (item) {
                    item.ybtse = Number(item.ybtse)
                })
                companyInfo = data.bean;
//                console.log("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■");
//                console.log(companyInfo);
//                console.log("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■");
                pagingDataFun(sourceData, 1, initPagingNum);
                taxAmendGrid(sourceData);
            } else {
                alertWarning(data.errmsg);
            }
        }).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 * num)));
                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));
    pagingDataFun(companyInfo.gzTaxInfos,1,initPagingNum);
    return {}
}