'use strict';

/**
 * 切换 sheet 页
 *
 * @param {*} index
 */

function toggleSheet(index) {
    spread.setActiveSheetIndex(index);
}
/**
 *  控制隐藏行列
 *
 * @param {*} sheetIndex   sheet 索引
 * @param {*} type      col 或者 row
 * @param {*} index     行列的索引 （从0开始）
 * @param {boolean} [isShow=false]  是否显示
 */
function hideRowCol(sheetIndex, type, index) {
    var isShow = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;

    if (type === 'row') {
        spread.sheets[sheetIndex].setRowVisible(index, isShow);
    } else if (type === 'col') {
        spread.sheets[sheetIndex].setColumnVisible(index, isShow);
    } else {
        throw new Error('type 参数错误');
    }
}

/**
 * 动态添加左侧菜单
 *
 */
function addLeftItem(flag, NBindex) {
    var activeIndex = [];
    var html = '';
    for (var i = 0; i < leftMenu.length; i++) {
        var name = 'table_' + leftMenu[i];
        var bbdm = leftMenu[i];
        var bbmc = GLOBAL_TABLE_NAMES[bbdm];
        //是否必填标志
        var isSheetRequired = (GLOBAL_SHEET_REQUIRED[bbdm] && GLOBAL_SHEET_REQUIRED[bbdm].isRequired == "Y");
        spread.getSheetIndex(name);
        var index = data.sheets[name].index;
        if (bbmc !== undefined) {
            if (isSheetRequired) {
                //年报特殊处理
                bbmc = ((bbdm != "10414_001" && bbdm != "10414_002") ?
                    ' <span style="color:red">【必填表】</span>' : '') +bbmc
            }
            //TODO

            html += "<div class='left-item' data-table='" + name + "' data-index='" + index + "'>" + bbmc + "</div>";
            activeIndex.push(index);
        }
    }
    toggleSheet(0);
    $('.left').empty();
    $('.left').html(html);
    $('.left-item').eq(0).addClass('left-item-active');
    $('.left-item').click(function () {
        //NOTE 此处添加年报特殊校验处理
        if ($(this).hasClass('table_fixed')) {
            return;
        }

        $('.left-item').removeClass('left-item-active');
        $(this).addClass('left-item-active');
        var index = Number($(this).attr('data-index'));
        // 2019年1月8日09:26:37 新增逻辑
        // 此处根据切换sheet时,sheet的修改状态控制是否显示红圈勾选错误
        var tableName = $(this).attr("data-table");
        if (tableName == 'table_10414_026') {
            getVal_026(index);
        }
        //table_10414_020 取019的日期值
        if (tableName == 'table_10420_020'){
            var tableName_19 = 'table_10420_019';
            var sheetIndex_19 = spread.getSheetIndex(tableName_19);
            if (sheetIndex_19 && getCellValue(sheetIndex_19,4,7) && getCellValue(sheetIndex_19,4,7).length > 4) {
                var data_019 = getCellValue(sheetIndex_19,4,7).substring(0,4);
                setCellValue(index, 5, 8, data_019);
            }else {
                setCellValue(index, 5, 8, "");
            }
        }
        if (tableName == 'table_10420_016') {
            var tablename = "table_10420_006";
            var sheetIndex = data.sheets[tablename] ? data.sheets[tablename].index : -1;
            var arr = [];
            if(sheetIndex != -1){
                for(var i=7; i<=11; i++){
                    var v = getCellValue(sheetIndex, i, 3);
                    if(v && v.trim() != ""){
                        arr.push(v);
                    }
                }
                for(var i=22; i<=26; i++){
                    var v = getCellValue(sheetIndex, i, 3);
                    if(v && v.trim() != ""){
                        arr.push(v);
                    }
                }
            }

            var arrs = [];
            //遍历当前数组
            for(var i = 0; i < arr.length; i++){
                //如果临时数组里没有当前数组的当前值，则把当前值push到新数组里面
                if (arrs.indexOf(arr[i]) == -1){
                    arrs.push(arr[i])
                };
            }

            newCellType(index, 7, 3, 'select', arrs.length>0 ? arrs : []);
            setCellLoked(index, 7, 3, false);
        }
        if (tableName == 'table_10420_001' || tableName == 'table_10420_002') {
            var NbBtnHtml = '<button class="htbutton import" id="saveNb"> 保存 </button>';
            $(".button-group").html(NbBtnHtml);
            $("#saveNb").on('click', function (e) {
                e.preventDefault();
                selectNb();
            });
        } else if (tableName == 'table_10420_005') {
            if (GLOBAL_JSON.operateType == "6") {
                var topBtnHtml = '<button class="htbutton import" id="cancellationBtn"> 清册注销 </button> <button class="htbutton" id="saveGlf"> 保存关联方 </button> ';
            }else if (GLOBAL_JSON.operateType == "5") {
                var topBtnHtml = '<button class="htbutton import" id="overdueBtn"> 逾期申报 </button> <button class="htbutton" id="saveGlf"> 保存关联方 </button> ';
            }else {
                var topBtnHtml = ' <button class="htbutton" id="importInBtn"> 导入 </button><button class="htbutton" id="saveGlf"> 保存关联方 </button> <button class="htbutton" id="storageBtn"> 暂存 </button> <button class="htbutton" id="saveBtn"> 保存 </button> <button class="htbutton import" id="uploadDataBtn"> 申报 </button> <button class="htbutton" id="exportOutBtn"> 导出 </button> <button class="htbutton" id="resetCurrentBtn" title="重置当前报表数据"> 重置当前报表 </button>  <button class="htbutton resetAll" id="resetBtn" title="重置所有报表数据"> 全部重置 </button>';
            }
            if(isGZflag){
                topBtnHtml = '<button class="htbutton import" id="uploadDataBtn"> 更正 </button> <button class="htbutton" id="resetCurrentBtn" title="重置当前报表数据"> 重置当前报表 </button> <button class="htbutton resetAll" id="resetBtn" title="重置所有报表数据"> 全部重置 </button> ';
            }
            $(".button-group").html(topBtnHtml);
            _bindTopButtonEvent();
            $("#saveGlf").on('click', function (e) {
                e.preventDefault();
                myConfirm("提示", "保存关联方将会清空相关表已选择的数据，点击确定继续", "确定", "取消", function () {
                    getSelectList('all');
                })
            });
        } else {
            if (GLOBAL_JSON.operateType == "6") {
                var topBtnHtml = '<button class="htbutton import" id="cancellationBtn"> 清册注销 </button>';
            }else if (GLOBAL_JSON.operateType == "5") {
                var topBtnHtml = '<button class="htbutton import" id="overdueBtn"> 逾期申报 </button>';
            }else {
                var topBtnHtml = ' <button class="htbutton" id="importInBtn"> 导入 </button><button class="htbutton" id="storageBtn"> 暂存 </button> <button class="htbutton" id="saveBtn"> 保存 </button> <button class="htbutton import" id="uploadDataBtn"> 申报 </button> <button class="htbutton" id="exportOutBtn"> 导出 </button> <button class="htbutton" id="resetCurrentBtn" title="重置当前报表数据"> 重置当前报表 </button>  <button class="htbutton resetAll" id="resetBtn" title="重置所有报表数据"> 全部重置 </button>';
            }
            if(isGZflag){
               topBtnHtml = '<button class="htbutton import" id="uploadDataBtn"> 更正 </button> <button class="htbutton" id="resetCurrentBtn" title="重置当前报表数据"> 重置当前报表 </button> <button class="htbutton resetAll" id="resetBtn" title="重置所有报表数据"> 全部重置 </button> ';
            }
            $(".button-group").html(topBtnHtml);
            _bindTopButtonEvent();
        }
        var sheetId = tableName.substring(6);
        // 如果当前报表为非必填且没有修改过  没有必要显示红圈
        if (GLOBAL_SHEET_REQUIRED[sheetId] && (GLOBAL_SHEET_REQUIRED[sheetId].isRequired != "Y" && !GLOBAL_SHEET_REQUIRED[sheetId].isChanged)) {
            spread.options.highlightInvalidData = false;
        } else {
            if (GLOBAL_SHEET_ERROR[tableName] && $(this).hasClass('has-error')) {
                spread.options.highlightInvalidData = true;
            }
        }

        toggleSheet(index);
    });
}

/**
 * 给动态行左侧增加按钮
 *
 * @param {*} sheetIndex
 * @param {*} rowIndex
 */
function newAddBtn(sheetIndex, rowIndex) {
    setCellSize(sheetIndex, 'col', 'width', 0, 40);
    var options = {
        marginLeft: 5,
        marginTop: 2,
        marginRight: 5,
        marginBottom: 2,
        text: '+',
        buttonBackColor: '#42b983'
    };
    newCellType(sheetIndex, rowIndex, 0, 'button', options);
}
/**
 * 给动态行左侧删除按钮
 *
 * @param {*} sheetIndex
 * @param {*} rowIndex
 */
function newDelBtn(sheetIndex, rowIndex) {
    setCellSize(sheetIndex, 'col', 'width', 0, 40);
    var options = {
        marginLeft: 5,
        marginTop: 2,
        marginRight: 5,
        marginBottom: 2,
        text: '-',
        buttonBackColor: '#ff0000'
    };
    newCellType(sheetIndex, rowIndex, 0, 'button', options);
}
/**
 * 给按钮添加事件
 *
 */
function bindBtnEvent() {
    spread.bind(GC.Spread.Sheets.Events.ButtonClicked, function (e, info) {
        var sheet = spread.getActiveSheet();
        var sheetIndex = spread.getActiveSheetIndex();
        sheet.clearSelection();
        var row = info.row;
        var col = info.col;
        var sheetName = sheet.name();
        // 处理年报表单的选择
        var val = getCellValue(sheetIndex,row,col);
        if (sheetIndex == 1 && row == 37 && col == 3 && val == true) {
            setCellValue(sheetIndex, 38, 3, true)
            setCellValue(sheetIndex, 39, 3, true)
            setCellValue(sheetIndex, 40, 3, true)
          }
        // 防止双击
        if (doubleClick.indexOf(row) !== -1) {
            return;
        }
        doubleClick.push(row);

        var isFixedRow = fzObj[sheetIndex].isFixedRow;
        // 如果点击的是增加按钮
        if (isFixedRow.indexOf(row) !== -1 && col === 0) {
            if(sheetName == "table_10414_003") {
                if(fzObj[sheetIndex].isAddRow.length == 8) {
                    sheet.getCell(35, 5).locked(false);
                    var style1 = getCellStyle(sheetIndex, 35, 5)
                    style1.backColor = "#D9F3D9";
                    setCellStyle(sheetIndex, 35, 5, style1)
                    sheet.getCell(35, 6).locked(false);
                    var style2 = getCellStyle(sheetIndex, 35, 6)
                    style2.backColor = "#D9F3D9";
                    setCellStyle(sheetIndex, 35, 6, style2)
                }
                if(fzObj[sheetIndex].isAddRow.length == 9) {
                        myAlert("提示", "股东信息不能超过10条，请在其余股东合计填写！", "确定", function () {
                    });
                    var doubleIndex = doubleClick.indexOf(row);
                    doubleClick.splice(doubleIndex, 1);
                    return
                }
            }
            toAddRow(sheetIndex, row, isFixedRow);
        }
        // 如果点击的是删除按钮
        fzObj[sheetIndex].isAddRow.map(function (item, index) {
            if (item.index === row && col === 0) {
                var sheet = spread.getActiveSheet();
                var avtiveSheet = data.sheets[sheetName];
                var extendSheet = extend_data[sheetName];

                if(sheetName == "table_10414_003") {
                    var hjRow = 27 + fzObj[sheetIndex].isAddRow.length;
                    sheet.getCell(hjRow, 5).locked(true);
                    var style1 = getCellStyle(sheetIndex, hjRow, 5)
                    style1.backColor = "#FFFFFF";
                    setCellStyle(sheetIndex, hjRow, 5, style1)
                    sheet.getCell(hjRow, 6).locked(true);
                    var style2 = getCellStyle(sheetIndex, hjRow, 6)
                    style2.backColor = "#FFFFFF";
                    setCellStyle(sheetIndex, hjRow, 6, style2)
                    setCellValue(sheetIndex, hjRow, 5, 0)
                    setCellValue(sheetIndex, hjRow, 6, 0)
                }

                var isAddRow = fzObj[sheetIndex].isAddRow;
                var oldTable1 = avtiveSheet.data.dataTable;
                var rowData1 = copyJSON(avtiveSheet.data.dataTable[row]);
                var oldTable2 = extendSheet.data.datatable;
                var rowData2 = copyJSON(extendSheet.data.datatable[row]);
                deleteRowIndex(oldTable1, row, rowData1);
                deleteRowIndex(oldTable2, row, rowData2);
                var columnCount = sheet.getColumnCount();
                // 去除校验错误信息，去除左侧高亮
                for (var i = 1; i < columnCount; i++) {
                    var pos = row + '-' + i;
                    if (GLOBAL_SHEET_ERROR[sheetName][pos]) {
                        delete GLOBAL_SHEET_ERROR[sheetName][pos]
                        var $errorDom = $('[data-table="' + sheetName + '"]');
                        // debugger
                        if (JSON.stringify(GLOBAL_SHEET_ERROR[sheetName]) == "{}") {
                            if ($errorDom.hasClass('has-error')) {
                                $errorDom.removeClass('has-error');
                                var text = $errorDom.text();
                                $errorDom.text(text.substring(0, text.length - 6));
                            }
                        }
                    }
                }
                sheet.deleteRows(row, 1);
                setTimeout(function () {
                    fzObj[sheetIndex].isAddRow.splice(index, 1);

                    var newIndex = [];
                    for (var i = 0; i < isFixedRow.length; i++) {
                        if (row < isFixedRow[i]) {
                            var newFixedIndex = isFixedRow[i] - 1;
                            isAddRow.map(function (item) {
                                if (item.parent === isFixedRow[i]) {
                                    item.parent = newFixedIndex;
                                }
                            });
                        } else {
                            var newFixedIndex = isFixedRow[i];
                        }
                        newIndex.push(newFixedIndex);
                    }
                    isAddRow.map(function (item) {
                        if (item.index > row) {
                            item.index = item.index - 1;
                        }
                    });
                    fzObj[sheetIndex].isFixedRow = copyJSON(newIndex);
                }, 0);
            }
        });
        // 执行完毕，删除防双击堆栈里的索引
        setTimeout(function () {
            setLocked(sheetIndex)
            var doubleIndex = doubleClick.indexOf(row);
            doubleClick.splice(doubleIndex, 1);
        }, 0);
    });
}

/**
 *  改变行索引
 *
 * @param {*} row
 * @param {*} newIndex
 * @param {*} rowIndex
 * @param {*} table
 * @param {*} rowData
 */
function changeRowIndex(table, newIndex, rowData, rowIndex, row) {
    var newArr = [];
    $.each(table, function (key) {
        newArr.push(key);
    });
    var arr = newArr.filter(function (x) {
        return isNumber(x);
    });
    arr.sort(function (a, b) {
        return b - a;
    });
    arr.unshift(Number(arr[0]) + 1);
    arr.forEach(function (value, index) {
        if (Number(value) > newIndex) {
            table[value] = copyJSON(table[(Number(value) - 1).toString()]);
        }
        if (Number(value) == newIndex) {
            table[newIndex.toString()] = copyJSON(rowData);
        }
    });
}
/**
 * 改变行索引
 *
 * @param {*} table
 * @param {*} newIndex
 * @param {*} rowData
 * @param {*} rowIndex
 * @param {*} row
 */
function deleteRowIndex(table, newIndex, rowData, rowIndex, row) {
    var newArr = [];
    $.each(table, function (key) {
        newArr.push(key);
    });
    var arr = newArr.filter(function (x) {
        return isNumber(x);
    });
    arr.sort(function (a, b) {
        return a - b;
    });

    for (var newRowIndex = newIndex; newRowIndex < arr.length; newRowIndex++) {
        if (newRowIndex < arr.length - 1) {
            table[arr[newRowIndex]] = copyJSON(table[arr[newRowIndex + 1]]);
        }
        if (newRowIndex == arr.length - 1) {
            delete table[arr[newRowIndex]];
        }
    }
}

/**
 * 数组去重
 * 
 * @param {any} arr 去重前数组
 * @returns 去重后数组
 */
function uniqueArr(arr) {
    var result = [],
        json = {};
    for (var i = 0, len = arr.length; i < len; i++) {
        if (!json[arr[i]]) {
            json[arr[i]] = 1;
            result.push(arr[i]);
        }
    }
    return result;
};

/**
 * 获取单元格样式
 *
 * @param {*} sheetIndex
 * @param {*} row
 * @param {*} col
 * @returns
 */
function getCellStyle(sheetIndex, row, col) {
    var sheet = spread.sheets[sheetIndex];
    var style = sheet.getStyle(row, col, GC.Spread.Sheets.SheetArea.viewport);
    return style;
}

/**
 * 设置单元格样式
 *
 * @param {*} sheetIndex
 * @param {*} row
 * @param {*} col
 * @param {*} style
 */
function setCellStyle(sheetIndex, row, col, style) {
    var sheet = spread.sheets[sheetIndex];
    sheet.setStyle(row, col, style);
}

/**
 *设置单元格边框
 *
 * @param {*} sheetIndex
 * @param {*} row
 * @param {*} col
 * @param {*} color
 */
function setCellBorder(sheetIndex, row, col, color) {
    var sheet = spread.sheets[sheetIndex];
    var lineStyle = GC.Spread.Sheets.LineStyle.thin;
    var lineBorder = new GC.Spread.Sheets.LineBorder(color, lineStyle);
    sheet.getRange(row, col, 1, 1).setBorder(lineBorder, {
        all: true
    });
}

/**
 * 给单元格赋值
 *
 * @param {*} sheetIndex
 * @param {*} row
 * @param {*} col
 * @param {*} value
 */
function setCellValue(sheetIndex, row, col, value) {
    var sheet = spread.sheets[sheetIndex];
    sheet.setValue(row, col, value);
}
/**
 * 获取单元格的值
 *
 * @param {*} sheetIndex
 * @param {*} row
 * @param {*} col
 * @returns
 */
function getCellValue(sheetIndex, row, col) {
    var sheet = spread.sheets[sheetIndex];
    var value = sheet.getValue(row, col);
    return value;
}

/**
 * 获取单元格显示的值
 *
 * @param {*} sheetIndex
 * @param {*} row
 * @param {*} col
 * @returns
 */
function getCellText(sheetIndex, row, col) {
    var sheet = spread.sheets[sheetIndex];
    if (sheet) {
        var value = sheet.getText(row, col, GC.Spread.Sheets.SheetArea.viewport);
    } else {
        var value = 0;
    }
    return value;
}

/**
 * 新建单元格类型
 *
 * @param {*} sheetIndex
 * @param {*} row
 * @param {*} col
 * @param {*} type checkbox;select;button
 * @param {*} options checkbox、select:[{name:'',value:''}]
 * @param {*} options button: 

{marginLeft:'',marginTop:'',marginRight:'',marginBottom:'',text:'',buttonBackColor:''}
 * 
 */
function newCellType(sheetIndex, row, col, type, options) {
    var sheet = spread.sheets[sheetIndex];
    switch (type) {
        case "checkbox":
            //5
            var c = new GC.Spread.Sheets.CellTypes.CheckBox();
            sheet.setCellType(row, col, c, GC.Spread.Sheets.SheetArea.viewport);
            c.textAlign(3);
            var textTrue, textFalse;
            textTrue = textFalse = options && options.length > 0 && options[0].name || "";
            c.textTrue(textTrue);
            c.textFalse(textFalse);
            break;
        case "select":
            //7
            var combo = new spreadNS.CellTypes.ComboBox();
            combo.items(options).editorValueType(spreadNS.CellTypes.EditorValueType.text);
            sheet.getCell(row, col, spreadNS.SheetArea.viewport).cellType(combo).value('');
            combo.editable(false);
            break;
        case "button":
            //7
            var btn = new GC.Spread.Sheets.CellTypes.Button();
            btn.marginLeft(options.marginLeft);
            btn.marginTop(options.marginTop);
            btn.marginRight(options.marginRight);
            btn.marginBottom(options.marginBottom);
            btn.text(options.text);
            btn.buttonBackColor(options.buttonBackColor);
            sheet.setCellType(row, col, btn, GC.Spread.Sheets.SheetArea.viewport);
            sheet.getCell(row, col).hAlign(GC.Spread.Sheets.HorizontalAlign.center); // 按钮居中对齐
            setLocked(sheetIndex)
            sheet.getCell(row, col).locked(false);
            break;
    }
}

function setLocked(sheetIndex) {
    var sheet = spread.sheets[sheetIndex];
    var rowCount = sheet.getRowCount();
    var sheetName = sheet.name();
    if (sheetName.substring(0, 5) !== 'table') {
        return
    }
    var isFixedRow = fzObj[sheetIndex].isFixedRow;
    var isAddRow = fzObj[sheetIndex].isAddRow;
    var singleAddRow = []
    isAddRow.map(function (item) {
        singleAddRow.push(item.index)
    })
    for (var j = 1; j < rowCount; j++) {
        if (isFixedRow.indexOf(j) == -1 && singleAddRow.indexOf(j) == -1) {
            sheet.getCell(j, 0).locked(true);
        }
    }
}
/**
 * 设置行列尺寸
 *
 * @param {*} sheetIndex
 * @param {*} type1  row 或 col
 * @param {*} type2  width 或 height
 * @param {*} index  索引
 * @param {*} size  尺寸
 */
function setCellSize(sheetIndex, type1, type2, index, size) {
    var sheet = spread.sheets[sheetIndex];
    if (type1 === 'row') {
        if (type2 === 'width') {
            sheet.setRowWidth(index, size);
        } else {
            sheet.setRowHeight(index, size);
        }
    } else if (type1 === 'col') {
        if (type2 === 'width') {
            sheet.setColumnWidth(index, size);
        } else if (type2 === 'height') {
            sheet.setColumnHeight(index, size);
        }
    }
}

/**
 *获取单元格tag
 *
 * @param {*} sheetIndex
 * @param {*} row
 * @param {*} col
 * @returns
 */
function getTag(sheetIndex, row, col) {
    var sheet = spread.sheets[sheetIndex];
    var tag = sheet.getTag(row, col, spreadNS.SheetArea.viewport);
    return tag;
}
/**
 *设置单元格tag
 *
 * @param {*} sheetIndex
 * @param {*} row
 * @param {*} col
 * @param {*} tag
 * @returns
 */
function setTag(sheetIndex, row, col, tag) {
    var sheet = spread.sheets[sheetIndex];
    sheet.setTag(row, col, tag);
}
/**
 *设置单元格公式
 *
 * @param {*} sheetIndex
 * @param {*} row
 * @param {*} col
 * @returns
 */
function getFormula(sheetIndex, row, col) {
    var sheet = spread.sheets[sheetIndex];
    var formula = sheet.getFormula(row, col);
    return formula;
}

function getAllFormula() {
    var sheet = spread.getActiveSheet();
    var sheetIndex = spread.getActiveSheetIndex();
    var rowCount = sheet.getRowCount();
    var colCount = sheet.getColumnCount();
    for (var i = 0; i < rowCount; i++) {
        for (var j = 0; j < colCount; j++) {
            var formula = sheet.getFormula(i, j);
            if (formula) {
                console.log("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■");
                console.log("formula:", i, '-', j, ':', formula);
                console.log("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■");
            }
        }
    }
}

function setFormula(sheetIndex, row, col, value) {
    var sheet = spread.sheets[sheetIndex];
    sheet.setFormula(row, col, value);
}

function getVlaueByName(str, name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    var result = str.match(reg);
    return result ? decodeURIComponent(result[2]) : null;
}

/**
 * 字母转数字
 *
 * @param {*} Eng
 * @returns
 */
function convertEng2Num(Eng) {
    var num = Eng.charCodeAt() - 64;
    return num;
}

/**
 *移除sheet
 *
 * @param {*} arr
 */
function removeSheets(arr) {
    arr.map(function (item) {
        var tableName = 'table_' + item;
        var sheetIndex = spread.getSheetIndex(tableName);
        spread.removeSheet(sheetIndex);
    });
}

function toAddRow(sheetIndex, row, isFixedRow) {
    var sheet = spread.sheets[sheetIndex];
    var sheetName = sheet.name();
    // 根据全局变量 isAddRow 来判断是否是增的行
    var isAddRow = fzObj[sheetIndex].isAddRow;
    var singleAddRow = isAddRow.filter(function (item) {
        return item.parent == row;
    });
    var newRowIndex = Number(row) + singleAddRow.length + 1;
    sheet.addRows(newRowIndex, 1); // 增加行
    // 存放进全局数组变量
    var newRowObj = {
        parent: row,
        index: newRowIndex
    };
    isAddRow.push(newRowObj);
    // fzObj[sheetIndex].isAddRow = uniqueArr(fzObj[sheetIndex].isAddRow);
    // 新增行之后修改全局变量isFixedRow 里原始行的索引
    var newIndex = [];
    for (var i = 0; i < isFixedRow.length; i++) {
        if (row < isFixedRow[i]) {
            var newFixedIndex = isFixedRow[i] + 1;
            isAddRow.map(function (item) {
                if (item.parent === isFixedRow[i]) {
                    item.parent = newFixedIndex;
                    item.index = item.index + 1;
                }
            });
        } else {
            var newFixedIndex = isFixedRow[i];
        }
        newIndex.push(newFixedIndex);
    }
    fzObj[sheetIndex].isFixedRow = copyJSON(newIndex);

    var rowCount = sheet.getRowCount();
    var columnCount = sheet.getColumnCount();
    var arr = [];
    $.each(data.sheets, function (key) {
        arr.push(key);
    });
    var avtiveSheet = data.sheets[sheetName];
    var extendSheet = extend_data[sheetName]
    // 修改索引
    var oldTable1 = avtiveSheet.data.dataTable;
    var rowData1 = copyJSON(avtiveSheet.data.dataTable[row]);
    var oldTable2 = extendSheet.data.datatable;
    var rowData2 = copyJSON(extendSheet.data.datatable[row]);
    changeRowIndex(oldTable1, newRowIndex, rowData1);
    changeRowIndex(oldTable2, newRowIndex, rowData2);
    newDelBtn(sheetIndex, newRowIndex);
    // 给新增的单元格设置样式和赋值
    sheet.suspendPaint();
    var posArr = []
    for (var i = 1; i < columnCount; i++) {
        var pos = convertNum2Eng(i) + (Number(row) + 1)
        posArr.push(pos)
        posArr = uniqueArr(posArr)
    }

    for (var i = 1; i < columnCount; i++) {
        var style1 = getCellStyle(sheetIndex, row, i);
        var tag = getTag(sheetIndex, row, i);
        // 如果有公式复制公式
        var formula = getFormula(sheetIndex, row, i);
        if (formula) {
            posArr.map(function (item) {
                // 多行公式处理 单元格公式 + 1
                if (formula.indexOf(item) != -1) {
                    var pos = splitExcelPoint(item)
                    var newPos = pos[0] + (Number(pos[1]) + singleAddRow.length + 1)
                    formula = formula.allReplace(item, newPos)
                }
            })
            if (formula.indexOf('CF_GET_BJ_ZC') != -1 || formula.indexOf('SPECIAL_VAL') != -1) {
                var arr1 = formula.split(',');

                if (formula.indexOf('SPECIAL_VAL') != -1) {
                    arr1 = formula.split('(')[1].split(',');
                }
                var arr2 = [];
                arr1.map(function (item) {
                    var arr = item.split(':');
                    arr2.push(arr);
                });
                arr2.map(function (item) {
                    if (isNumber(item[0]) && isNumber(item[1])) {
                        var oldValue = item[0] + ':' + item[1];
                        var len = singleAddRow.length;
                        var newValue = Number(item[0]) + len + 1 + ':' + (Number(item[1]) + len + 1);
                        formula = formula.allReplace(oldValue, newValue); // 替换
                    }
                });
            }
            setFormula(sheetIndex, newRowIndex, i, formula);
        }
        // 如果是合并列
        var name = spread.sheets[sheetIndex].name();
        var spans = sheet.getSpans();
        spans.map(function (item) {
            if (item.row == row && item.col == i) {
                if (item.colCount > 1) {
                    var sheet = spread.sheets[sheetIndex];
                    sheet.addSpan(newRowIndex, i, item.rowCount, item.colCount);
                }
            }
        });
        // 复制校验
        var validList = sheet.getDataValidator(row, i);
        sheet.setDataValidator(newRowIndex, i, validList);
        // 设置样式和 tag
        setCellStyle(sheetIndex, newRowIndex, i, style1);
        setTag(sheetIndex, newRowIndex, i, tag);
        if (tag.defaultValue) {
            var defalutValue = tag.defaultValue;
            setCellValue(sheetIndex, newRowIndex, i, defalutValue);
        } else {
            if (rowData1[i]) {
                if (rowData1[i].value == '0.00') {
                    setCellValue(sheetIndex, newRowIndex, i, 0);
                }
            }
        }
    }
    var height = getRowHeight(sheetIndex, row);
    setRowHeight(sheetIndex, newRowIndex, height);
    // 重新绑定日期控件

    if (sheetName == 'table_10420_005') {
        swjgdmCell005.push( newRowIndex)
    }
   

    sheet.resumePaint();
}

/**
 *获取行高
 *
 * @param {*} sheetIndex
 * @param {*} row
 * @returns
 */
function getRowHeight(sheetIndex, row) {
    var sheet = spread.sheets[sheetIndex];
    var height = sheet.getRowHeight(row, spreadNS.SheetArea.viewport);
    return height;
}

/**
 *设置行高
 *
 * @param {*} sheetIndex
 * @param {*} row
 * @param {*} value
 */
function setRowHeight(sheetIndex, row, value) {
    var sheet = spread.sheets[sheetIndex];
    sheet.setRowHeight(row, value, spreadNS.SheetArea.viewport);
}

/**
 * 正则全局替换
 *
 */
String.prototype.allReplace = function (oldValue, newValue) {
    var reg = new RegExp(oldValue, "g"); //创建正则RegExp对象   
    return this.replace(reg, newValue);
}
/**
 *阻止双击事件
 *
 */
function unBindDoubleClickEvent() {
    spread.bind(GC.Spread.Sheets.Events.CellDoubleClick, function (e, info) {
        var sheet = spread.getActiveSheet();
        var sheetIndex = spread.getActiveSheetIndex();
        var row = info.row;
        var col = info.col;
        var tag = getTag(sheetIndex, row, col)
        var fomula = getFormula(sheetIndex, row, col)
        // console.log('fomula:',fomula)   
        if (!!fomula) {
            sheet.clearSelection();
        }
    });
}

/**
 *编辑后检验
 *
 */
function bindEditEvent() {
    spread.bind(GC.Spread.Sheets.Events.EditEnded, function (sender, info) {
        var sheet = spread.getActiveSheet();
        var sheetIndex = spread.getActiveSheetIndex();
        var editingText = Number(info.editingText);
        var row = info.row;
        var col = info.col;
        var tag = getTag(sheetIndex, row, col)
        // console.log('tag:', tag)
        if (tag.dataType == 'N') {
            if (!isNumber(editingText)) {
                setCellValue(sheetIndex, row, col, 0)
                // console.log(value);
            } else if (editingText.length > Number(tag.formatLenth)) {
                setCellValue(sheetIndex, row, col, 0)
            }
            var value = getCellValue(sheetIndex, row, col)
        }
    });
}

/**
 * 判断是否为数字
 *
 * @param {*} value
 * @returns
 */
function isNumber(value) {
    var patrn = /^(-)?\d+(\.\d+)?$/;
    if (patrn.exec(value) == null || value == "") {
        return false
    } else {
        return true
    }
}

/**
 * 单元格单击事件(测试时使用)
 *
 */
function bindCellClickEvent() {
    spread.bind(GC.Spread.Sheets.Events.CellClick, function (e, info) {
        var activeSheetIndex = spread.getActiveSheetIndex();
        var row = info.row;
        var col = info.col;
        var pos = convertNum2Eng(col + 1) + '' + (row + 1)
        var style = getCellStyle(activeSheetIndex, row, col);
        var tag = getTag(activeSheetIndex, row, col)
        console.log("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■");
        console.log('row', row)
        console.log('col', col)
        console.log('pos', pos)
        console.log('tag', tag)
        console.log('style', style)
        // console.log('row', row, 'col', col, 'pos',pos,'tag', tag,'style',style);
        console.log("■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■");
    });
}

function toReallyTime(stringtime) {
    var num;
    if (stringtime === '' || stringtime === null) {
        num = '';
    } else if (stringtime.length === 8) {
        var y = stringtime.substr(0, 4);
        var m = stringtime.substr(4, 2);
        var d = stringtime.substr(6, 2);
        return y + '-' + m + '-' + d;
    } else {
        var y = stringtime.substr(0, 4);
        var m = stringtime.substr(4, 2);
        return y + '-' + m;
    }
    return num;
}

// 对数字进行四舍五入
function fixedNumber(val, formatter) {
    if (typeof val == 'string') {
        return val;
    }
    var _formatter = Math.pow(10, Number(formatter))
    if (formatter === '0') {
        _formatter = 1
    }
    if (val > 0) {
        var _val = Math.round(_numberMul(val, _formatter)) / _formatter
    } else {
        var _val = _numberSub(0, val);
        _val = _numberSub(0, Math.round(_numberMul(_val, _formatter)) / _formatter)
    }
    return _val;
}
// 浮点数相乘
function _numberMul(a, b) {
    var c = 0,
        d = a.toString(),
        e = b.toString();
    try {
        c += d.split(".")[1].length;
    } catch (f) { }
    try {
        c += e.split(".")[1].length;
    } catch (f) { }
    return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
}

// 浮点数相加
function _numberAdd(a, b) {
    var c, d, e;
    try {
        c = a.toString().split(".")[1].length;
    } catch (f) {
        c = 0;
    }
    try {
        d = b.toString().split(".")[1].length;
    } catch (f) {
        d = 0;
    }
    return e = Math.pow(10, Math.max(c, d)), (_numberMul(a, e) + _numberMul(b, e)) / e;
}
// 浮点数相减
function _numberSub(a, b) {
    var c, d, e;
    try {
        c = a.toString().split(".")[1].length;
    } catch (f) {
        c = 0;
    }
    try {
        d = b.toString().split(".")[1].length;
    } catch (f) {
        d = 0;
    }
    return e = Math.pow(10, Math.max(c, d)), (_numberMul(a, e) - _numberMul(b, e)) / e;
}

// 浮点数相除
function _numberDiv(a, b) {
    var c, d, e = 0,
        f = 0;
    try {
        e = a.toString().split(".")[1].length;
    } catch (g) { }
    try {
        f = b.toString().split(".")[1].length;
    } catch (g) { }
    return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), _numberMul(c / d, Math.pow(10, f - e));
}

// ◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆   
// ◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆
// ◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆
// ◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆
// 2019年2月19日13:24:28 新增对年报的特殊处理/取值方法

/**
 * 获取分类历史信息中的数组数据
 *
 * @returns 数组
 */
function NB_getFllsxxBaseInfo(nd) {
    var fllsxxInfo;
    if (!nd) {
        if (JSON.stringify(GLOBAL_JSON.fllsxx["sbQysdsczzsndsb2018NsrjbxxVO"]) != "{}") {
            fllsxxInfo = GLOBAL_JSON.fllsxx["sbQysdsczzsndsb2018NsrjbxxVO"];
        } else {
            if (JSON.stringify(GLOBAL_JSON.fllsxx["sbQysdsczzsndsb2014NsrqtxxVO"]) != "{}") {
                fllsxxInfo = GLOBAL_JSON.fllsxx["sbQysdsczzsndsb2014NsrqtxxVO"];
            }
        }
    } else {
        if (nd == 2014) {
            var str = 'sbQysdsczzsndsb2014NsrqtxxVO'
        } else {
            var str = 'sbQysdsczzsndsb2018NsrjbxxVO'
        }
        fllsxxInfo = GLOBAL_JSON.fllsxx[str];
    }
    var keys = getObjectKeys(fllsxxInfo);
    // 获取到过滤的值
    var baseInfo = keys.length > 0 ? fllsxxInfo[keys[0]] : [];
    return baseInfo;
}

/**
 * 根据codeName获取对应的数据
 *
 * @returns
 */
function NB_getCellData(codeName, nd) {
    var baseInfo = NB_getFllsxxBaseInfo(nd);
    var cellObj = null;
    baseInfo.forEach(function (x) {
        if (x.code == codeName) {
            cellObj = copyJSON(x);
        }
    });
    return cellObj;
}

/**
 *排序年报
 *
 * @param {*} arr
 */
function NBsort(arr) {
    for (var i = 0; i < arr.length - 1; i++) {
        for (var j = 0; j < arr.length - i - 1; j++) {
            if (Number(arr[j].substring(6)) > Number(arr[j + 1].substring(6))) {
                var swap = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = swap;
            }
        }
    }
}
/**
 *重新绑定事件
 *
 */
function reBindEvent() {
    var CellClick = GC.Spread.Sheets.Events.CellClick;
    var ValueChanged = GC.Spread.Sheets.Events.ValueChanged;
    var ButtonClick = GC.Spread.Sheets.Events.ButtonClicked;
    spread.unbind(CellClick);
    spread.unbind(ValueChanged);
    spread.unbind(ButtonClick);
    bindValueChanged(); // 绑定 年报ValueChanged 方法
    bindNbCellClickEvent(); // 年报点击事件特殊处理
    bindBtnEvent();
}

/**
 *把备份信息data_extend_back重新特殊处理，留待备用
 *
 */
function changeExtend_back() {
    getObjectKeys(data_extend_back).forEach(function (tableName, sheetIndex) {
        var optionDataTable = data_extend_back && data_extend_back[tableName] && data_extend_back[tableName].data.datatable;
        if (!optionDataTable) {
            return;
        }
        $.each(optionDataTable, function (rowIndex, row) {
            $.each(row, function (colIndex, col) {
                var tdOption = optionDataTable[rowIndex][colIndex];
                if (tdOption) {
                    // 是否合计行
                    if (tdOption.isSum) {
                        tdOption.isSum = true;
                        tdOption.isMulti = true;
                        if (!optionDataTable[rowIndex].isSum) {
                            optionDataTable[rowIndex].isSum = true;
                            optionDataTable[rowIndex].isMulti = true;
                        }

                        //将当前行第一列的合并属性设置为true
                        if (!optionDataTable[rowIndex][0].isSum) {
                            optionDataTable[rowIndex][0].isSum = true;
                            optionDataTable[rowIndex][0].isMulti = true;
                        }

                    } else {
                        // 是否多行 并且确实是多行(isReallyNotDynamicRow: false或undefined的情况)
                        if (tdOption.dynamicRow && !optionDataTable[rowIndex].isReallyNotDynamicRow) {
                            tdOption.isMulti = true;
                            if (!optionDataTable[rowIndex].isMulti) {
                                optionDataTable[rowIndex].isMulti = true;
                            }
                            //将当前行第一列的多行属性设置为true
                            if (!optionDataTable[rowIndex][0].isMulti) {
                                optionDataTable[rowIndex][0].isMulti = true;
                            }

                        }
                    }
                }
            });
        });
    })
    var sheetKeys = [];
    $.each(data_back.sheets, function (key) {
        sheetKeys.push(key);
    });
    sheetKeys.forEach(function (sheetName, sheetIndex) {
        // 此对象用于收集当前报表单元格校验规则
        data_back.sheets[sheetName].index = sheetIndex;
    })
}
/**
 *控制单元格只读
 *
 * @param {*} sheetIndex
 * @param {*} row
 * @param {*} col
 * @param {*} flag
 */
function setCellLoked(sheetIndex,row,col,flag) {
    var sheet = spread.sheets[sheetIndex];
    sheet.getCell(row, col).locked(flag);
    var style = getCellStyle(sheetIndex, row, col)
    style.backColor = flag ? "#FFFFFF" : "#D9F3D9";
    setCellStyle(sheetIndex, row, col, style)
}
/**
 *从 10420_005获取关联方名称的下拉
 *
 * @param {*} tableName
 * @returns
 */
function getSelectList(tableName) {
    var tableNameList = ["table_10420_006", "table_10420_007", "table_10420_008", "table_10420_009", "table_10420_010", "table_10420_012", "table_10420_011"]
    if (tableNameList.indexOf(tableName) == -1 && tableName !== 'all') {
        return;
    }
    spread.isPaintSuspended(true);
    var index005 = spread.getSheetIndex('table_10420_005');
    var sheet = spread.sheets[index005];
    var rowCount = sheet.getRowCount();
    var startRow = 6;
    jnList = [];
    jwList = [];
    for (var i = 6; i < rowCount - 1; i++) {
        var glfMc = sheet.getValue(i, 2);
        var gj = sheet.getValue(i, 4);
        if (glfMc !== "" && glfMc !== null && gj !== "" && gj !== null) {
            if (gj.split(' ')[0] == '156') {
                var obj = {
                    text: glfMc,
                    value: glfMc
                }
                jnList.push(obj)
            } else {
                var obj = {
                    text: glfMc,
                    value: glfMc
                }
                jwList.push(obj)
            }
        }
    }
    if (tableName == 'all') {
        tableNameList.map(function (name) {
            setGlf(name,jwList,jnList);
        })
    } else {
        setGlf(tableName,jwList,jnList);
    }
    spread.isPaintSuspended(false);
}
/**
 * 设置下拉框的锁定
 * 
 * @param {*} index
 * @param {*} row
 * @param {*} list
 * @param {*} flag
 */
function setSelectLocked(index, row, list, flag) {
    !flag && newCellType(index, row, 3, 'select', list)
    setCellLoked(index, row, 3, flag);
    setCellLoked(index, row, 4, true);
    setCellLoked(index, row, 5, true);
    setCellValue(index, row, 3, "");
    setCellValue(index, row, 4, "");
    setCellValue(index, row, 5, 0);
}

/**
 *根据不同情况控制关联方的只读
 *
 * @param {*} name
 * @param {*} jwList
 * @param {*} jnList
 */
function setGlf(name,jwList,jnList) {
    switch (name) {
        case "table_10420_006":
        case "table_10420_007":
        case "table_10420_008":
        case "table_10420_009":
            var index = spread.getSheetIndex(name);
            if (index) {
                var jw_row = [7, 8, 9, 10, 11, 22, 23, 24, 25, 26];
                if (jwList.length !== 0) {
                    jw_row.map(function (row) {
                        setSelectLocked(index, row, jwList, false)
                    })
                } else {
                    jw_row.map(function (row) {
                        setSelectLocked(index, row, [], true)
                    })
                }

                var jn_row = [14, 15, 16, 17, 18, 29, 30, 31, 32, 33];
                if (jnList.length !== 0) {
                    jn_row.map(function (row) {
                        setSelectLocked(index, row, jnList, false)
                    })
                } else {
                    jn_row.map(function (row) {
                        setSelectLocked(index, row, [], true)
                    })
                }
            }
            break;
        case "table_10420_010":
        case "table_10420_012":
            var index = spread.getSheetIndex(name);
            if (index) {
                var jw_row = [8, 9, 10, 11, 12, 23, 24, 25, 26, 27];
                if (jwList.length !== 0) {
                    jw_row.map(function (row) {
                        setSelectLocked(index, row, jwList, false)
                    })
                } else {
                    jw_row.map(function (row) {
                        setSelectLocked(index, row, [], true)
                    })
                }
                var jn_row = [15, 16, 17, 18, 19, 30, 31, 32, 33, 34];
                if (jnList.length !== 0) {
                    jn_row.map(function (row) {
                        setSelectLocked(index, row, jnList, false)
                    })
                } else {
                    jn_row.map(function (row) {
                        setSelectLocked(index, row, [], true)
                    })
                }
            }
            break;
        case "table_10420_011":
            var index = spread.getSheetIndex(name);
            if (index) {
                var list = []
                jwList.map(function (item) {
                    var obj = {
                        text: item.text,
                        value: 2
                    }
                    list.push(obj)
                })
                jnList.map(function (item) {
                    var obj = {
                        text: item.text,
                        value: 1
                    }
                    list.push(obj)
                })
                if (list.length !== 0) {
                    newCellType(index, 8, 3, 'select', list)
                    var arr = [];
                    fzObj[index].isAddRow.map(function (item) {
                        newCellType(index, item.index, 3, 'select', list)
                        if (item.parent == 8) {
                            arr.push(item.index)
                        }
                    })
                    newCellType(index, (13 + arr.length), 3, 'select', list)
                }
            }
            break;

    }
}

//“是”和“否”只能选择一个。 yyx
/**
 *
 * @param flag 点击单元格的状态
 * @param index 非点击单元格的索引
 * @param row  非点击单元格的行
 * @param col  非点击单元格的列
 */
function chooseOne(flag, index, row, col) {
    if (flag) {
        setCellValue(index, row, col, false);
    }else {
        setCellValue(index, row, col, true);
    }
}