'use strict';

//葡萄城表格样式
var STYLE_OBJECT = {};
var spread;
var spreadNS;
var sheet;
var tsJyFlag;
var SheetArea;
var data_back; // 用于备份页面初始化参数,用于重置功能
var data_extend_back; // 用于备份页面初始化参数,用于重置功能
var hideIndex = []; //  存放隐藏行列索引
var addIndex = []; // 存放动态行的索引
var IS_DATE_ARR = []; // 日期类型单元格
var fzObj = {}; // 动态行分组用的全局变量   
var copy_fzObj; // fzObj的原始值备份 重置报表时用
var doubleClick = []; // 防止两次点击
// 表内公式
var GLOBAL_FORMULA = {
  // 表内公式
  TABLE_FORMULA: {},
  // 表间公式
  SHEETS_FORMULA: {}
};
var leftMenu = []; // 左侧菜单

var GLOBAL_STATIC_INFO;

var NB_pzzlDm = ['10414', '10420']; // 年报的pzzldm

var GLOBAL_COPY_DATA; // spread合并后原始样式数据的备份

var GLOBAL_SHEET_ERROR = {}; // 校验不通过信息收集结果

var isInProduction = true;

var NB_cache_data; // 年报表单点击保存，存储之前填写的数据
var NB_Init_sheets;
var swjgdmCell005 = [6]; //存放10420_005表中新增行的行数
var sd_back;

var jnList = [];
var jwList = [];

window.onload = function () {
  getIEVersion();
  var url = window.location.host;
    if(config.spreadUrl == url){
        GC.Spread.Sheets.LicenseKey = "sbjs.tjsat.gov.cn,736922629637688#B0LBLdFREewVjRiZFNIdmWjtUWldkRhVWa9oFMLNlTwg4UUVTNjtUW0RXcwR5R6EnTIZTRNpXUBB7L0RWciRmaUlnUwQlTLFlYiNkMSFWaxI7bBBzc0VHOFF5M9pXSoRkQPhmZlRUewMncNBXSXZVTV36dSJVS0tEb5lnWI5mNxNzMwYEU7cnMRRUc6xmYF3GakpWYwckVF3mSsJWYlRlb6U6cZpFTGVzYhN7cjx6LphTQOFVSPxUdZVTU5pEeNhDZutmQPZFT6FEdONmc926YCl4drAlNx3Ud8o5LOhGOjJzaPJ4YUtmbx8maiJiOiMlIsIyMDdTRwYER4IiOigkIsEjN6ETO8EzM0IicfJye35XX3JSSGljQiojIDJCLiITMuYHITpEIkFWZyB7UiojIOJyebpjIkJHUiwiIxQDO4gDMggTMyEDOxAjMiojI4J7QiwiIuNmL636ZuQXYzpGduMnaiNnI0IyctRkIsICnCeOqZa+r+SuI0ISYONkIsICO8YzNzYTOyYjMykjNzcjI0ICZJJCL3V6csFmZ0IiczRmI1pjIs9WQisnOiQkIsISP3cXdOBVZwEVZ9V5V7dnTllFSVpHVYd5UZl6a6tUQ6hUQX36NTFVNKhHNC5USDlVOJBVWlJWRq3ERqJDWth7TyMmVnV7QjZWWzNXcxokewYTeBhXOFZnVBhWStt6SsB7TTJkUV3UTGlHSNRWR";
    }else{
        GC.Spread.Sheets.LicenseKey = "etax.tianjin.chinatax.gov.cn,498254719314719#B0WY39GZUNVZFpUQtZXVxFTRzYkQFtEbvVHRvgDb03yNXljc6R4KqtiTrFUYCF6RhdFTPhTOzpmeCRne7ZXRWVWV9MlUo34NlFDTVp6dyt4TVV7c8pERk94Uml4Y0JDcrsyYyFWbNVzcwsGRslndxw6Yy54SiJDVVZnajZVRXpmTnVVMGJGZ42GRolTSPpkea9mNxITT5YmapRHSN3iZrYWYDhXav3GOnd5LLBXYrd4badlcxwWbElFWzgmZsdWU4JVaYV6bmdWYudDVhR7KhJEOhJnQw4EbKxEdvk4NiZTWmpnN7cVY9tmd9VGZEdzSZZTai9UO8BTYqVkbppWSiojITJCLiYDOEZ4MDJzMiojIIJCL8YzN7MzN8kjM0IicfJye35XX3JSSGljQiojIDJCLiITMuYHITpEIkFWZyB7UiojIOJyebpjIkJHUiwiI5MDM4kDMgMjM7ATOxAjMiojI4J7QiwiIuNmL636ZugXY4Fmbph6Yu8Waq9WYpRnL8FGdlJiOiMXbEJCLig1jlzahlDZmpnInmDoimH9pnnKplnatm19tl1ZpnXKtmnKplLiOiEmTDJCLikTM7QTMzkTM7QTNygTO4IiOiQWSiwSflNHbhZmOiI7ckJye0ICbuFkI1pjIEJCLi4TPBJGc9IFVrJFNwQDZ0tWUKpmS9kHUmZmN6YzZwcFeahEaNNWWmRmMTdVRFxWNRZTcwQzSpt4dthTNHhUbxATNj9Gdp3kNs3mcXZUZDFVQTt6aJJUO6diSM9";
    }
  //设置全局变量
  spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));
  //将接口返回的数据  解析为全局基础信息
  toBaseInfo(GLOBAL_JSON);
  NB_Init_sheets = copyJSON(data.sheets)
  // 注册全部公式
  registAllFormula();
  // 获取左侧菜单
  getLeftMenu();
  //初始化报表并绘制页面
  initSpread(spread); // *****整体入口*****
  
  // 处理隐藏行列
  !isInProduction && _hideRowHanler();
  // 处理按钮
  _btnsEventHandler();
  // 处理显示部分列表
  isInProduction && getGlobalBaseInfo();
  !isInProduction && addLeftItem();
  // 阻止双击事件
  isInProduction && unBindDoubleClickEvent();
  // 编辑单元格事件
  isInProduction && bindEditEvent();
  isInProduction && isSqwsb(); // 上期未申报
  reBindEvent();
  setGLBhide();
  getJmxz_026();
  //10420_019  增加货币任务
  getJmxz_019();
  //增加“Currencyused”
  getJmxz_020();

  //增加新需求请求方法
  // getGuanLianBiao()
};
/**
 * 初始化葡萄城控件
 *
 * @param {*} spread
 */
function initSpread(spread) {
  //备份数据 用于重置等功能
  data_back = copyJSON(data);
  data_extend_back = copyJSON(extend_data);
  var sd = data;
  if (sd) {
    // 样式对象拆出来供后期调用
    styleArraytoObject(sd);
    // 合并导出的样式与配置
    sd = mergeOptions(sd, extend_data);
    // 备份 fzObj 初始值
    copy_fzObj = copyJSON(fzObj);
    // 挂起进程
    spread.suspendPaint();
    // 绘制报表
    spread.fromJSON(sd);
    changeExtend_back();
    // 配置页面参数
    spreadConfig(spread);
    spread.resumePaint();
  }
}

/**
 * 配置报表对象
 *
 * @param {*} spread
 */
function spreadConfig(spread) {
  spread.options.tabStripVisible = false;
  spread.options.newTabVisible = false;
  spread.options.tabNavigationVisible = false; // false: hide, true: show
  spread.options.setTabStripRatio = 0.7;
  spread.options.allowUserDragDrop = false; // 禁止用户拖动
  spread.options.allowUserDragMerge = false; // 禁止拖动合并
  spread.options.allowUserDragFill = false; // 禁止拖动填充
  spread.options.allowCopyPasteExcelStyle = false; // 禁止复制粘贴 Excel
  spread.options.allowUserZoom = false; // 禁止用户缩放表单
  spread.options.allowContextMenu = false;
  spread.options.showDragDropTip = false;
  spread.options.scrollbarShowMax = false;
  spread.options.scrollbarMaxAlign = true;
  spread.options.grayAreaBackColor = "#FFFFFF";
  spread.options.highlightInvalidData = false;
  spreadNS = GC.Spread.Sheets;
  // 遍历sheet
  for (var i = 0; i < spread.sheets.length; i++) {
    sheet = spread.getSheet(i);
    GLOBAL_SHEET_ERROR[sheet.name()] = {}; // 全局错误对象
    SheetArea = spreadNS.SheetArea;
    sheet.options.isProtected = isInProduction;
    sheet.options.protectionOptions.allowSelectLockedCells = false; // 禁止保护单元格被选中
    sheet.options.selectionBorderColor = "#FF0000";
    sheet.clearSelection();
    validationErrorHandler(sheet);
  }
}

/**
 * 判断单元格是否检验通过
 *
 * @param {*} sheet
 * @param {*} row
 * @param {*} col
 * @param {*} value
 */
function getIsValid(sheet, row, col, value) {
  var isValid = sheet.isValid(Number(row), Number(col), value);
  var table_name = sheet.name();
  var pos = row + '-' + col;
  if (isValid) { // 如果通过并且全局对象里有值，则删除
    if (GLOBAL_SHEET_ERROR[table_name][pos]) {
      delete GLOBAL_SHEET_ERROR[table_name][pos]
      var $errorDom = $('[data-table="' + table_name + '"]');
      if (JSON.stringify(GLOBAL_SHEET_ERROR[table_name]) == "{}") {
        if ($errorDom.hasClass('has-error')) {
          $errorDom.removeClass('has-error');
          var text = $errorDom.text();
          $errorDom.text(text.substring(0, text.length - 6));
        }
      }
    }
  } else {
    console.log("GLOBAL_SHEET_ERROR", GLOBAL_SHEET_ERROR);
    GLOBAL_SHEET_ERROR[table_name][pos] = true
  }
}

/**
 *校验失败收集信息
 *
 * @param {*} sheet
 */
function validationErrorHandler(sheet) {
  sheet.bind(GC.Spread.Sheets.Events.ValidationError, function (sender, args) {
    var pos = args.row + '-' + args.col;
    GLOBAL_SHEET_ERROR[args.sheetName][pos] = true
  })
}

/**
 * 获取合并后的单元格配置并重新绘制
 *
 * @param {*} spreadObj  spreadjs对象
 * @param {*} options  表格配置
 */
function mergeOptions(spreadObj, options) {
  var sheetKeys = [];
  $.each(spreadObj.sheets, function (key) {
    sheetKeys.push(key);
  });
  sheetKeys.forEach(function (sheetName, sheetIndex) {
    // 此对象用于收集当前报表单元格校验规则
    data.sheets[sheetName].index = sheetIndex;
    var sheetValidateCells = {
      type1: [], // 字符串非空
      type2: [], // 数值 != 0
      type3: [], // 数值 >  0
      type4: [], // 数值 >= 0
    };
    // 生成分组的全局对象
    fzObj[sheetIndex] = {
      isFixedRow: [],
      isAddRow: [],
      isSumRow: []
    };
    var tableSheet = spreadObj.sheets[sheetName];
    if (tableSheet) {
      //获取葡萄城单元格配置
      var dataTable = tableSheet.data.dataTable;
      //获取cell工具导出单元格配置
      var optionDataTable = options && options[sheetName] && options[sheetName].data.datatable;
      if (!optionDataTable) {
        return;
      }
      $.each(dataTable, function (rowIndex, row) {
        $.each(row, function (colIndex, col) {
          if (optionDataTable) {
            if (optionDataTable[rowIndex] && optionDataTable[rowIndex][colIndex]) {
              var tdOption = optionDataTable[rowIndex][colIndex];
              if (tdOption) {
                if(tdOption.defaultValue) {
                  col.value = tdOption.defaultValue
                }
                // 验证数据处理
                _validateControl(tdOption, colIndex, rowIndex, sheetValidateCells);
                //表内公式处理
                _formulaControl(tdOption, rowIndex, col, colIndex, sheetName);
                // 特殊行列标记处理逻辑
                _rankMarkerControl(tdOption, sheetIndex, rowIndex, colIndex, optionDataTable, row);
                //特殊类型数据处理
                _sltDataControl(tdOption, col, sheetName);
                //将其他属性添加到葡萄城单元格的tag属性当中,只有tag属性是可配置属性
                _mergeToTag(tdOption, col);
              }
            }
          }
        });
      });
      // 添加到spread的标准验证规则中
      addToSpreadValidate(sheetValidateCells, tableSheet);
    }
  });
  GLOBAL_COPY_DATA = copyJSON(spreadObj)
  return spreadObj;
}

/**
 * 添加到spread的标准验证规则中
 *
 * @param {*} sheetValidateCells
 * @param {*} tableSheet
 */
function addToSpreadValidate(sheetValidateCells, tableSheet) {
  SHEET_VALIDATE_RULES.validations[0].ranges = sheetValidateCells["type2"].join(',');
  SHEET_VALIDATE_RULES.validations[1].ranges = sheetValidateCells["type3"].join(',');
  SHEET_VALIDATE_RULES.validations[2].ranges = sheetValidateCells["type4"].join(',');
  SHEET_VALIDATE_RULES.validations[3].ranges = sheetValidateCells["type1"].join(',');
  tableSheet.validations = copyJSON(SHEET_VALIDATE_RULES.validations);
}

/**
 * 收集当前sheet中的验证规则
 *
 * @param {*} tdOption
 * @param {*} colIndex
 * @param {*} rowIndex
 * @param {*} sheetValidateCells
 */
function _validateControl(tdOption, colIndex, rowIndex, sheetValidateCells) {
  if (tdOption.require && tdOption.require != "N") {
    // debugger
    var excelPoint = createCellPos(parseInt(colIndex) + 1) + (parseInt(rowIndex) + 1).toString();
    //判断如果存在校验
    var validateType = tdOption.require;
    sheetValidateCells["type" + validateType].push(excelPoint);
  }
}

/**
 * 解析表内和表间公式
 *
 * @param {*} tdOption
 * @param {*} rowIndex
 * @param {*} col
 * @param {*} colIndex
 * @param {*} sheetName
 */
function _formulaControl(tdOption, rowIndex, col, colIndex, sheetName) {
  // 1.表内公式处理
  if (tdOption.formula_1) {
    var formula = tdOption.formula_1;
    if (formula.substring(0, 6) === 'string' && formula.indexOf(".0f") != -1) {
      formula = formula.slice(7, -10);
    }
    if (formula.indexOf('string') != -1) {
      formula = formula.allReplace('string', '')
    }
    if (formula.indexOf('STRING') != -1) {
      formula = formula.allReplace('STRING', '')
    }
    if (formula.indexOf('FIND') != -1) {
      formula = formula.allReplace('FIND', 'TOFIND')
    }
    if (formula.indexOf('TRIMLEFT') != -1) {
      formula = formula.allReplace('TRIMLEFT', '')
    }
    formula = formula.toUpperCase().replace(/COL\(\)/gi, 'COLUMN()');
    if (formula.indexOf("CF_GET_BBHJ") > -1) {
      formula = formulaToSheetPoint2(formula)
    }
    if (formula.indexOf("CF_GET_BBSJ") > -1) {
      //特殊函数将相关参数转为Excel点坐标
      formula = formulaToSheetPoint(formula);
    }
    if (formula.indexOf("SUM") > -1) {
      var reg = /\((.+?)\)/g;
      if (reg.test(formula)) {
        //如果匹配上直接获取括号里的内容
        var innerFormula = RegExp.$1;
        if (innerFormula.indexOf(':') > -1 && innerFormula.split(':').length == 2) {
          var innerArr = innerFormula.split(':');
          var a0 = splitExcelPoint($.trim(innerArr[0]));
          var a1 = splitExcelPoint($.trim(innerArr[1]));
          if (a0[0] == a1[0]) {
            var prevRowIndex = Number(a1[1]);
            if (Number(rowIndex) == prevRowIndex) {
              formula = formula.substring(0, formula.indexOf('(')) + '(' + a0.join('') + ":" + 'INDIRECT("' + a1[0] + '"&ROW()-1))';
            } else {
              var cha = Number(rowIndex) > prevRowIndex && Number(rowIndex) - prevRowIndex || -1;
              if (cha >= 0) {
                formula = formula.substring(0, formula.indexOf('(')) + '(' + a0.join('') + ":" + 'INDIRECT("' + a1[0] + '"&ROW()-' + (cha + 1) + '))';
              }
            }
          }
        }
      }
    }
    col.formula = formula;
  }

  // 2.表间公式处理
  if (tdOption.tableFormula && tdOption.tableFormula.formula) {
    var item = tdOption.tableFormula;
    var arr = item.formula.split(';');
    var obj = {
      rowIndex: rowIndex,
      colIndex: colIndex,
      formula: {}
    };
    arr.map(function (item) {
      var _name = item.split('=')[0];
      var equalIndex = item.indexOf('=');
      if (equalIndex) {
        var _val = item.slice(equalIndex + 1);
        var fixIndex = _val.indexOf('FORMULA=');
        if (fixIndex != -1) {
          _val = _val.split("FORMULA")[1];
        }
      }
      if (_name === 'ZC' || _name === 'TJ' || _name === 'ES') {
        _val && (obj.formula[_name] = _val);
      }
    });

    //判断是否相同
    if (JSON.stringify(obj.formula) != "{}") {
      //此处针对TJ做特殊处理
      if (obj.formula.TJ) {
        obj.formula.TJ = obj.formula.TJ.replace(new RegExp('\\] \\* 1', 'g'), ']');
        obj.formula.TJ = obj.formula.TJ.replace(new RegExp('\\] \\+ 1', 'g'), ']');
      }
      obj.formula.ZC = obj.formula.ZC.toUpperCase().replace(/COL\(\)/gi, 'COLUMN()');
      //如果表格没有公式 或者公式与当前的条件不同的
      if (!col.formula || obj.formula.ZC != "=" + col.formula) {
        //如果存在条件的
        var tableformula = obj.formula;
        //如果有条件
        var newformula = "";
        if (tableformula.TJ) {
          newformula = setTjFormula(obj, col, sheetName, rowIndex, colIndex);
        } else {
          //没有条件且表间公式和表内公式不相同的情况
          if (obj.formula.ZC != "=" + col.formula) {
            //此处将报表相关的参数转化为一整行和一整列的参数,有点难以描述的逻辑ε=(´ο｀*)))
            newformula = setNormalFormula(obj.formula.ZC, 'ZC', sheetName, rowIndex, colIndex);
          }
        }
        if (newformula.indexOf("CF_GET_BJ_ZC") > -1) {
          if (newformula.indexOf("SUM") > -1) {
            newformula = replaceAll(newformula, "CF_GET_BJ_ZC", "CF_GET_BJ_ZC_SUM");
          }
        }
        newformula = replaceAll(newformula, "'", '"');
        col.formula = newformula;
      }
    }
  }
}

/**
 * 转换表间公式 带条件
 *
 * @param {*} obj
 * @param {*} col
 * @param {*} tableName
 * @param {*} rowIndex
 * @param {*} colIndex
 * @returns
 */
function setTjFormula(obj, col, tableName, rowIndex, colIndex) {
  var ZC = setNormalFormula(obj.formula.ZC, 'TJ', tableName, rowIndex, colIndex);
  var TJ = setNormalFormula(obj.formula.TJ, 'TJ', tableName, rowIndex, colIndex);
  var ES = (obj.formula.ES && setNormalFormula(obj.formula.ES, 'TJ', tableName, rowIndex, colIndex)) || 0;
  return 'if(' + TJ + ',' + ZC + ',' + ES + ')'; // 拼接 IF 公式

}

/**
 * 转换表间公式  不带条件的
 *
 * @param {*} formula
 * @param {*} type
 * @param {*} tableName
 * @param {*} rowIndex
 * @param {*} colIndex
 * @returns
 */
function setNormalFormula(formula, type, tableName, rowIndex, colIndex) {
  if (type === 'ZC') {
    var formulaName = 'CF_GET_BJ_ZC';
  } else {
    var formulaName = 'SELF_TJ_FORMULA';
  }
  var arr = [];
  for (var i = 0; i < formula.length; i++) {
    var obj = {};
    var indexStr = formula.substring(i, i + 1);
    if (indexStr === '[' || indexStr === ']') {
      arr.push(i);
    }
  }
  var newFormulaStr = formula;
  for (var j = 0; j < arr.length; j++) {
    // 根据奇偶来组合成一对
    if (j % 2 == 0) {
      // 偶数
      var old = formula.substring(arr[j], arr[j + 1] + 1); // 匹配出带‘[]’的内容 用来最后替换
      var item = formula.substring(arr[j] + 1, arr[j + 1]); // 匹配出[]里的内容 用来分隔出参数
      var arr2 = item.split(',');
      var arg1 = arr2[0]; //报表代码加版本号
      var arg2 = arr2[1];
      var arg3 = arr2[2];
      var arg4 = arr2[3];
      if (type === 'TJ') {
        if (splitExcelPoint(arg2).length == 2) {
          var tableId = arg1.substring(0, 9);
          if ($.inArray(tableId, leftMenu) > -1) {
            arg1 = 'table_' + arg1.substring(0, 9) + '!' + arg2;
            var newformula = formulaName + '(' + arg1 + ',"' + arg3 + '","' + arg4 + '")'; // 拼接新的公式
          } else {
            //进入极端情况判断 返回4个参数的新公式
            var newformula = formulaName + '(0,"' + arg2 + '","' + arg3 + '","' + arg4 + '")';
          }
        } else {
          //带条件的有五个参数
          var newformula = formulaName + '(' + 'table_' + arg1.substring(0, 9) + '!A1:Z100' + ',"table_' + arg1.substring(0, 9) + '","' + arg2 + '","' + arg3 + '","' + arg4 + '")'; // 拼接新的公式
        }
      } else {
        var tableId = arg1.substring(0, 9);
        if (splitExcelPoint(arg2).length == 2) {
          //证明第二个参数是坐标,那么可以直接根据报表name!point形式当做参数传入其中
          if (tableName == "table_" + tableId) {
            var newformula = formulaName + '(table_' + tableId + '!' + arg2 + ',"' + arg3 + '","' + arg4 + '")';
          } else {
            if ($.inArray(tableId, leftMenu) > -1) {
              //五个参数
              var newformula = formulaName + '_DIFF' + '(table_' + tableId + '!' + arg2 + ',"' + arg3 + '","' + arg4 + '")';
            } else {
              //进入极端情况判断
              var newformula = formulaName + '_DIFF' + '(0,"' + arg2 + '","' + arg3 + '","' + arg4 + '")';
            }
          }
        } else {
          //证明不是坐标 而是参数NodeName的情况
          if (tableName == "table_" + tableId) {
            //获取到报表代码
            var excelCol = convertNum2Eng(Number(colIndex) + 1) + ":" + convertNum2Eng(Number(colIndex) + 1);
            var excelRow = "" + (Number(rowIndex) + 1).toString() + ":" + (Number(rowIndex) + 1).toString();
            //此处将当前单元格所在行和列当做条件塞进函数 到时候计算
            var newformula = formulaName + '(' + excelCol + ',' + excelRow + ',"' + arg2 + '","' + arg3 + '","' + arg4 + '")';
          } else {
            if ($.inArray(tableId, leftMenu) > -1) {
              var newformula = formulaName + "_DIFF" + '(table_' + tableId + '!A1:Z100,"table_' + tableId + '","' + arg2 + '","' + arg3 + '","' + arg4 + '")';
            } else {
              var newformula = formulaName + "_DIFF" + '(0,"table_' + tableId + '","' + arg2 + '","' + arg3 + '","' + arg4 + '")';
            }
          }
        }
      }
      newFormulaStr = newFormulaStr.replace(old, newformula);
    }
  }
  return newFormulaStr;
}


/**
 * 将相关公式CF_GET_BBHJ正则替换参数
 *
 * @param {*} base
 * @returns
 */
function formulaToSheetPoint2(base) {
  var reg = /"\w{9}"/gi;
  return base.replace(reg, function () {
    var r = arguments[0];
    return "table_" + r.replace(/"/gi, "") + "!A1:Z100," + r;
  });
}

/**
 * 将自定义公式参数转为Excel表参数
 */
function formulaToSheetPoint(base) {
  var reg = /"\w{9}",\s?\d{1,10},\s?\d{1,10}/gi;
  base = base.replace(reg, function () {
    var r = arguments[0].split(",");
    var tableId = r[0].replace(/"/gi, '');
    if ($.inArray(tableId, leftMenu) > -1) {
      return 'table_' + r[0].replace(/"/gi, '') + "!" + createCellPos(parseInt(r[1], 10)) + (parseInt(r[2], 10));
    } else {
      return r;
    }
  });
  return base;
}

/**
 * 输入数字 转化为对应的字母
 *
 * @param {*} n
 * @returns
 */
function createCellPos(n) {
  n = n - 1;
  var ordA = 'A'.charCodeAt(0);
  var ordZ = 'Z'.charCodeAt(0);
  var len = ordZ - ordA + 1;
  var s = "";
  while (n >= 0) {
    s = String.fromCharCode(n % len + ordA) + s;
    n = Math.floor(n / len) - 1;
  }
  return s;
}

/**
 * 收集公式
 *
 * @param {*} tdOption
 * @param {*} tableFormula
 * @param {*} rowIndex
 * @param {*} colIndex
 * @param {*} sheetsFormula
 */
function _collectFormula(tdOption, tableFormula, rowIndex, colIndex, sheetsFormula) {
  if (tdOption.formula_1) {
    tableFormula.push({
      rowIndex: rowIndex,
      colIndex: colIndex,
      colName: '' + convertNum2Eng(Number(colIndex) + 1) + (Number(rowIndex) + 1),
      formula: tdOption.formula_1
    });
  }
  if (tdOption.tableFormula) {
    sheetsFormula.push({
      rowIndex: rowIndex,
      colIndex: colIndex,
      colName: '' + convertNum2Eng(Number(colIndex) + 1) + (Number(rowIndex) + 1),
      table: tdOption.tableFormula.name,
      formula: tdOption.tableFormula.formula
    });
  }
}

/**
 * 特殊行列标记-处理逻辑
 *
 * @param {*} tdOption
 * @param {*} sheetIndex
 * @param {*} rowIndex
 * @param {*} colIndex
 * @param {*} optionDataTable
 * @param {*} row
 */
function _rankMarkerControl(tdOption, sheetIndex, rowIndex, colIndex, optionDataTable, row) {
  // 隐藏行列属性-处理逻辑
  var index = _rankMarker_hideControl(tdOption, sheetIndex, rowIndex, colIndex, row);
  // 动态行和合计行-处理逻辑
  var index = _rankMarker_multiAndSumControl(tdOption, optionDataTable, rowIndex, index, sheetIndex, row);
}

/**
 * 下拉菜单或选择框处理逻辑
 *
 * @param {*} tdOption
 * @param {*} col
 */
function _sltDataControl(tdOption, col, sheetName) {
  if ((tdOption.dataSltType && tdOption.dataSltType != '') || (tdOption.specialType && (tdOption.specialType == 7 || tdOption.specialType == 8))) {
    var type = tdOption.dataSltType;
    var cellType = {};

    if (type == "checkbox") {
      //checkBox情况
      cellType.typeName = "5";
      cellType.textAlign = 3;
      cellType.textTrue = cellType.textFalse = tdOption.options && tdOption.options.length > 0 && tdOption.options[0].name || "";
    } else if (type == "select" || type == "radio") {
      if (type == "radio" && col.value != undefined) {
        var temp = tdOption.options.filter(function (item) {
          return item.value == col.value;
        });
        if (temp.length > 0) {
          col.value = temp[0].name;
        } else {
          col.value = "";
        }
      }
      cellType.typeName = "7";
      if (tdOption.options && tdOption.options.length > 0) {
        if (type == "radio") {
          cellType.items = tdOption.options.reduce(function (a, b) {
            return a.concat({
              text: $.trim(b.name),
              value: b.value
            });
          }, []);
        } else {
          cellType.items = tdOption.options.reduce(function (a, b) {
            if ((GLOBAL_JSON.pzzlDm === '10101' && sheetName === 'table_10101_025')) {
              var text = b.value + ' ' + b.name
            } else {
              var text = b.name
            }
            return a.concat({
              text: text,
              value: b.value
            });
          }, []);
        }
      }
      cellType.maxDropDownItems = 5;
    }
    // 特殊类型处理
    specialSelectCell(sheetName, tdOption, cellType);

    if (typeof col.style === "string") {
      col.style = copyJSON(STYLE_OBJECT[col.style]);
    }
    col.style.cellType = copyJSON(cellType);
    delete tdOption.options;
  }


}

/**
 * 将其他属性添加到葡萄城单元格的tag属性当中, 只有tag属性是可配置属性
 *
 * @param {*} tdOption
 * @param {*} col
 */
function _mergeToTag(tdOption, col) {
  if (tdOption.style && tdOption.style.locked === false) {
    if (typeof col.style === "string") {
      col.style = copyJSON(STYLE_OBJECT[col.style]);
      col.style.locked = false;
    } else {
      col.style.locked = false;
    }
    //locked属性  添加到葡萄城单元格属性后就 没用了
    delete tdOption.style;
  }
  col.tag = JSON.parse(JSON.stringify(tdOption));
}

/**
 * 处理动态行和合计行
 *
 * @param {*} tdOption
 * @param {*} optionDataTable
 * @param {*} rowIndex
 * @param {*} index
 * @param {*} sheetIndex
 * @param {*} row
 * @returns
 */

function _rankMarker_multiAndSumControl(tdOption, optionDataTable, rowIndex, index, sheetIndex, row) {
  // 是否合计行
  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;
    }

    fzObj[sheetIndex].isSumRow.push(Number(rowIndex));
    fzObj[sheetIndex].isSumRow = uniqueArr(fzObj[sheetIndex].isSumRow);
  } 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 index = sheetIndex + '-' + rowIndex;
      addIndex.push(index);
      addIndex = uniqueArr(addIndex);
      fzObj[sheetIndex].isFixedRow.push(Number(rowIndex));
      fzObj[sheetIndex].isFixedRow = uniqueArr(fzObj[sheetIndex].isFixedRow);
    }
  }
  return index;
}

/**
 * 处理隐藏行列
 *
 * @param {*} tdOption
 * @param {*} sheetIndex
 * @param {*} rowIndex
 * @param {*} colIndex
 * @returns
 */
function _rankMarker_hideControl(tdOption, sheetIndex, rowIndex, colIndex) {
  if (tdOption.isHide === 'Y') {
    var index = sheetIndex + '-' + rowIndex + '-' + colIndex;
    hideIndex.push(index);
  } else { }
  return index;
}

/**
 * 配置由数组转为对象
 *
 */
function styleArraytoObject(spreadObj) {
  var styleArr = spreadObj.namedStyles;
  styleArr.forEach(function (x, index) {
    STYLE_OBJECT[x.name] = x;
  });
}



/**
 * 隐藏行列处理
 *
 */
function _hideRowHanler() {
  hideIndex.map(function (item) {
    if (item.split('-')[2] == 0) {
      hideRowCol(item.split('-')[0], 'row', item.split('-')[1], false);
    } else {
      hideRowCol(item.split('-')[0], 'col', item.split('-')[2], false);
    }
  });
}

function setGLBhide() {
  if (GLOBAL_JSON.pzzlDm === '10420') {
    // console.log('关联表');
    for (var i = 5; i < 14; i++) {
      hideRowCol(1, 'row', i, false);
    }
  }
  }

/**
 * 按钮事件处理
 *
 */
function _btnsEventHandler() {
  if (addIndex.length !== 0) {
    addIndex.map(function (item) {
      newAddBtn(item.split('-')[0], item.split('-')[1]);
    });
  }
}

/**
 * 将接口返回的数据  解析为全局基础信息
 *
 * @param {*} info
 */
function toBaseInfo(info) {
  GLOBAL_STATIC_INFO = copyJSON(info.param);
}

/**
 *提示上期未申报
 *
 */
function isSqwsb() {
  if (GLOBAL_JSON.isSqwsb == "Y") {
    myAlert("提示", "该申报种类上期未申报！", "确定", function () { });
  }
}

/**
 *选择会计制度弹框，用于10414_002表格的默认勾选对应表格
 */
function chooseKjzu() {
  $("#chooseHjzdModal,#kjzdBlackModal").show();
  var index = spread.getSheetIndex("table_10414_002");
  var kjzdDm = GLOBAL_STATIC_INFO.KJZDDM[1],
    dm = kjzdDm ? kjzdDm.split("|") : '',
    thtml = "";
  var dmList = { "01": "一般企业", "02": "金融企业", "03": "事业单位" };
  for (var i = 0; i < dm.length; i++) {
    var temp = dm[i];
    thtml += '<li>';
    thtml += '<input type="radio" name="kjzdxz" id="kjzdxz' + temp + '" value="' + temp + '"/>';
    thtml += '<label for="kjzdxz' + temp + '">' + dmList[temp] + '</label>';
    thtml += '</li>';
  }
  $("#chooseHjzdModal ul").html(thtml);
  $("#chooseHjzdModal #czSwjgConfirm").click(function () {
    var chooseVal = $("#chooseHjzdModal input:radio:checked").val();
    if (!chooseVal) return;
    setCellValue(index, 5, 4, chooseVal);
    switch (chooseVal) {
      case "01":
        setCellValue(index, 8, 3, true);
        setCellValue(index, 9, 3, false);
        setCellValue(index, 10, 3, true);
        setCellValue(index, 11, 3, false);
        setCellValue(index, 12, 3, false);
        break;
      case "02":
        setCellValue(index, 8, 3, false);
        setCellValue(index, 9, 3, true);
        setCellValue(index, 10, 3, false);
        setCellValue(index, 11, 3, true);
        setCellValue(index, 12, 3, false);
        break;
      case "03":
        setCellValue(index, 8, 3, false);
        setCellValue(index, 9, 3, false);
        setCellValue(index, 10, 3, false);
        setCellValue(index, 11, 3, false);
        setCellValue(index, 12, 3, true);
        break;
      default:
        break;
    }
    $("#chooseHjzdModal,#kjzdBlackModal").hide();
  });
}