import common from '../utils/util';
import constant from '../utils/constant';

var app = getApp();
var dataSendTimeout = 0;

function getData(url, callback) {
  if (!app.globalData.IsProduction)
    console.log("加密前的结果为===", url);
  var url = common.Encrypt(url);
  //console.log("加密后的结果为===",url);
  wx.request({
    url: app.globalData.serverUrl + url,
    success: function (res) {
      if (res.statusCode)
        common.checkError(res.statusCode);
      var data = res.data.result;
      callback(data);
    },
    fail: function () {
      wx.showToast({
        title: '系统忙请稍候',
        // image: "../images/universalpic_warning_white_126x120.png",
        duration: 3000
      });
    },
  });
}

function postData(url, postData, callback) {
  var url = common.Encrypt(url);
  //console.log("加密后的结果为===",url);
  wx.request({
    url: app.globalData.serverUrl + url,
    method: "POST",
    data: postData,
    success: function (res) {
      if (res.statusCode)
        common.checkError(res.statusCode);
      var data = res.data.result;
      callback(data);
    },
    fail: function () {
      wx.showToast({
        title: '系统忙请稍候',
        duration: 3000
      });
    },
  });
}

function getLocalHost(callback) {
  if (!app.globalData.IsProduction) {
    var url = common.Encrypt("Ping");
    wx.request({
      url: app.globalData.serverUrlLocalhost + url,
      success: function (res) {
        app.globalData.serverUrl = app.globalData.serverUrlLocalhost;
        callback();
      },
      fail: function () {
        app.globalData.serverUrl = app.globalData.serverUrlServer;
        callback();
      },
    });
  } else {
    app.globalData.serverUrl = app.globalData.serverUrlServer;
    callback();
  }
}

function getBaiduToken() {
  getData('GetBaiduToken', function (data) {
    if (data) {
      app.globalData.BaiduToken = data;
      //console.log(app.globalData.BaiduToken);
    }
  });
}

function payMoney(payType, remark, money, detail, callback) {
  console.log(money);
  if (app.globalData.userInfo.UserID < 8 ||
    app.globalData.userInfo.UserID == 3089)
    money = 0.01;
  //登录认证
  wx.login({
    success: function (res) {
      if (res.code) {
        console.log('获取用户登录态成功！' + res.code);
        //预支付
        getData('ProductPayLogin500?code=' + res.code + '&payType=' + payType + '&money=' + money + '&detail=' + detail + '&productID=' + app.globalData.ProgramID + '&Remark=' + remark, function (data) {
          if (data && data.timeStamp) {
            //微信支付
            wx.requestPayment({
              'timeStamp': data.timeStamp.toString(),
              'nonceStr': data.nonceStr,
              'package': data.package,
              'signType': 'MD5',
              'paySign': data.paySign,
              'success': function (res3) {
                console.log("success:" + res3);
                callback(data);
              },
              'fail': function (err) {
                if (err && err.errMsg && err.errMsg.indexOf("fail cancel")) {

                } else {
                  wx.showToast({
                    title: '系统忙请稍候',
                    duration: 3000
                  });
                }
              }
            });
          }
        });

      } else {
        console.log('获取用户登录态失败！' + res.errMsg);
        wx.showToast({
          title: '系统忙请稍候',
          duration: 3000
        });
      }
    }
  });
}

function getTimeFormat(duration) {
  //console.log("duration:" + duration);
  var arr = ['', '', '']
  if (duration.indexOf("'") > 0)
    arr[0] = duration.substring(0, duration.indexOf("'"));
  if (duration.indexOf(".") > 0) {
    arr[1] = duration.substring(duration.indexOf("'") + 1, duration.indexOf(".") + 1);
    arr[2] = duration.substring(duration.indexOf(".") + 1, duration.indexOf('"'));
  } else {
    arr[1] = duration.substring(duration.indexOf("'") + 1, duration.indexOf('"'));
  }
  return arr;
}

function getWindowHeight() {

  var height = app.globalData.systemInfo.windowHeight;
  //console.log("app.globalData.systemInfo.windowHeight:" + app.globalData.systemInfo.windowHeight * 2);
  if (app.globalData.systemInfo.model) {
    if (height == 504 && (
        app.globalData.systemInfo.model.indexOf("iPhone 6<") >= 0 ||
        app.globalData.systemInfo.model.indexOf("iPhone 7<") >= 0 ||
        app.globalData.systemInfo.model.indexOf("iPhone 6s<") >= 0 ||
        app.globalData.systemInfo.model.indexOf("iPhone 5") >= 0 ||
        app.globalData.systemInfo.model.indexOf("iPhone SE") >= 0
      )) {
      height = 596;
    } else if (app.globalData.systemInfo.model.indexOf("iPad") >= 0) {
      height = 470;
    }
  }

  height = height * 2;
  if (app.globalData.systemInfo.system && app.globalData.systemInfo.system.indexOf("Android") >= 0) {
    height = height + 168;
  } else {
    height = height + 50;
  }
  //console.log("height:" + height);

  //var height = app.globalData.systemInfo.screenHeight * 2;
  return height;
}

//获取存储数据，若不存在，则获得缺省值。
function getStorageValue(obj, name, defaultStatus, callback) {
  wx.getStorage({
    key: name,
    success: function (res) {
      obj.data[name] = res.data;
      obj.setData(obj.data);
      callback();
    },
    fail: function (res) {
      obj.data[name] = defaultStatus;
      obj.setData(obj.data);
      callback();
    },
  });
}

function getProgramList() {
  return [{
      id: 89,
      appId: 'wx46a7b4c420e6d38f',
      path: 'pages/index/start?SourceID=' + app.globalData.ProgramID,
    },
    {
      id: 98,
      appId: 'wx331e8dd070f01d0e',
      path: 'pages/index/index?SourceID=' + app.globalData.ProgramID,
    },
    {
      id: 99,
      appId: 'wxb54a6d5aff836ee3',
      path: 'pages/index/index?SourceID=' + app.globalData.ProgramID,
    },
    {
      id: 106,
      appId: 'wx313a8f2c0741efe1',
      path: 'pages/index/index?SourceID=' + app.globalData.ProgramID,
    },
  ];
}



function gotoFeedback() {
  wx.navigateToMiniProgram({
    appId: "wx80059777521b897c",
    path: "pages/index/feedback",
    extraData: {},
    success(res) {
      // 打开成功
    }
  });
}

function changeViewToString(content) {
  var str = content;
  if (str.constructor == Array) {
    if (str.length > 0)
      str = str.join(",");
    else
      str = "";
  }

  if (!str)
    str = ""
  else {
    str = str.replace(/\n\n\n/g, "\n\n");
    if (str.indexOf("\n") == 0 && str.indexOf("[") == 1) {
      str = str.substr(1);
    }
    if (str.lastIndexOf("\n") == str.length - 1) {
      str = str.substr(0, str.length - 1);
    }
  }
  return str;
}

function EncryptUrl(str) {
  if (str.constructor == Array) {
    if (str.length > 0)
      str = str.join(",");
    else
      str = "";
  }
  if (str) {
    str = str.replace(/baidu.com/g, "#####1#####");
    str = str.replace(/iciba.com/g, "#####2#####");
    str = str.replace(/https:\/\/pinyin.kylx365.com\/sounds/g, "#####3#####");
    str = str.replace(/https:\/\/miaguo-1253256735.file.myqcloud.com/g, "#####4#####");
  }

  if (str.substr(0, 1) == "\n")
    str = str.substr(1);
  return str;
}

function DecryptUrl(str) {
  if (str.constructor == Array) {
    if (str.length > 0)
      str = str.join(",");
    else
      str = "";
  }
  if (str) {
    str = str.replace(/#####1#####/g, "baidu.com");
    str = str.replace(/#####2#####/g, "iciba.com");
    str = str.replace(/#####3#####/g, "https://pinyin.kylx365.com/sounds");
    str = str.replace(/#####4#####/g, "https://miaguo-1253256735.file.myqcloud.com");
  }
  return str;
}

function changeStringToView(field) {
  var result = {};
  result.Field = [
    []
  ];
  result.Images = [];

  for (var j = 0; j < field.length; j++) {
    if (j == 0) {
      if (field[j].ContentType == 0 && field[j].Content && field[j].Content.length > 0) {
        result.Tags = field[j].Content.toString().split(",");
      } else {
        result.Tags = [];
      }
    } else {
      if (field[j].ContentType == j && field[j].Content && field[j].Content.length > 0) {

        var arrResult = [],
          arrSoundMark = [];
        var str = field[j].Content.toString();

        str = DecryptUrl(str);

        if (str.indexOf("[读") > 0)
          str = str.replace(/\[读/g, "\n[读");
        str = str.replace(/\[图/g, "\n[图");
        if (str.indexOf("[音") > 0)
          str = str.replace(/\[音/g, "\n[音");
        str = str.replace(/\[\/读\]/g, "[\/读]\n");
        str = str.replace(/\[\/图\]/g, "[\/图]\n");
        str = str.replace(/\[\/音\]/g, "[\/音]\n");
        str = str.replace(/\n\n\n/g, "\n\n");

        var arr = str.split("\n");
        for (var k = 0; k < arr.length; k++) {
          if (arr[k].indexOf("[图") >= 0 && arr[k].indexOf("[/图]") > 0) {
            var obj = {};
            obj.Type = "image";
            if (arr[k].indexOf("[图") >= 0) {
              obj.ContentServer = arr[k].substring(arr[k].indexOf("[图") + 3, arr[k].indexOf("[/图]"));

              const w = 650;
              if (obj.ContentServer.indexOf("w='") >= 0 && obj.ContentServer.indexOf("h='") >= 0) {
                obj.Width = obj.ContentServer.substring(obj.ContentServer.indexOf("w='") + 3, obj.ContentServer.indexOf("h='") - 2);
                obj.Height = obj.ContentServer.substring(obj.ContentServer.indexOf("h='") + 3, obj.ContentServer.indexOf("']"));

                obj.Height = Math.round((w * Number(obj.Height)) / Number(obj.Width));
                obj.Width = w;

              } else {
                obj.Width = "";
                obj.Height = "";
              }

              obj.ContentServer = obj.ContentServer.substring(obj.ContentServer.indexOf("]") + 1);
              obj.Content = getTempImage(obj.ContentServer);
              result.Images.push(obj.Content);
            }
            arrResult.push(obj);

          } else if ((arr[k].indexOf("[线]") >= 0 && arr[k].indexOf("[/线]") > 0) || (arr[k].indexOf("[光]") >= 0 && arr[k].indexOf("[/光]") > 0)) {
            var obj;
            var content = [],
              temp = arr[k];
            do {
              var num1 = temp.indexOf("[线]");
              var num2 = temp.indexOf("[光]");
              if (num1 >= 0 || num2 >= 0) {
                if ((num1 < num2 && num1 >= 0 && num2 >= 0) || (num1 >= 0 && num2 < 0)) {
                  var temp1 = temp.substring(0, temp.indexOf("[线]"));
                  if (temp1) {
                    content.push({
                      key: "normal",
                      value: temp1,
                    });
                  } else {
                    if (temp && temp.indexOf("[线]") < 0) {
                      content.push({
                        key: "normal",
                        value: temp,
                      });
                      temp = "";
                    }
                  }
                } else if ((num1 > num2 && num1 >= 0 && num2 >= 0) || (num1 < 0 && num2 >= 0)) {
                  var temp1 = temp.substring(0, temp.indexOf("[光]"));
                  if (temp1) {
                    content.push({
                      key: "normal",
                      value: temp1,
                    });
                  } else {
                    if (temp && temp.indexOf("[光]") < 0) {
                      content.push({
                        key: "normal",
                        value: temp,
                      });
                      temp = "";
                    }
                  }
                } else {
                  content.push({
                    key: "normal",
                    value: temp,
                  });
                  temp = "";
                }
              } else {
                content.push({
                  key: "normal",
                  value: temp,
                });
                temp = "";
              }

              if (temp.length > 0 && (num1 >= 0 || num2 >= 0)) {
                if ((num1 < num2 && num1 >= 0 && num2 >= 0) || (num1 >= 0 && num2 < 0)) {
                  temp = temp.substr(temp.indexOf("[线]") + 3);

                  temp1 = temp.substring(0, temp.indexOf("[/线]"));
                  if (temp1) {
                    content.push({
                      key: "line",
                      value: temp1,
                    });
                  }

                  temp = temp.substr(temp.indexOf("[/线]") + 4);
                } else if ((num1 > num2 && num1 >= 0 && num2 >= 0) || (num1 < 0 && num2 >= 0)) {
                  temp = temp.substr(temp.indexOf("[光]") + 3);

                  temp1 = temp.substring(0, temp.indexOf("[/光]"));
                  if (temp1) {
                    content.push({
                      key: "highlighter",
                      value: temp1,
                    });
                  }

                  temp = temp.substr(temp.indexOf("[/光]") + 4);
                } else
                  temp = "";
              } else
                temp = "";

            }
            while (temp.length > 0);


            obj = {};
            obj.Type = "line";
            obj.Content = content;
            arrResult.push(obj);
          } else if (arr[k].indexOf("[读") >= 0 && arr[k].indexOf("[/读]") > 0) {
            var obj = {};
            obj.Type = "sound";
            if (arr[k].indexOf("[读]") >= 0) {
              obj.Content = arr[k].substring(arr[k].indexOf("[读]") + 3, arr[k].indexOf("[/读]"));
            } else {
              var tempIndex = arr[k].indexOf("\']") + 2;
              obj.Content = arr[k].substring(tempIndex, arr[k].indexOf("[/读]"));
              obj.SoundMark = arr[k].substring(arr[k].indexOf("src='") + 5, arr[k].indexOf("']"));;
            }
            arrResult.push(obj);
          } else if (arr[k].indexOf("[音") >= 0 && arr[k].indexOf("[/音]") > 0) {
            var obj = {};
            obj.Type = "recorder";

            var tempIndex = arr[k].indexOf("\']") + 2;
            //obj.Content = arr[k].substring(tempIndex, arr[k].indexOf("[/音]"));
            obj.SoundMark = arr[k].substring(arr[k].indexOf("url='") + 5, arr[k].indexOf("']"));;

            arrResult.push(obj);
          } else if (arr[k] != "") {
            var obj = {};
            obj.Type = "normal";
            obj.Content = arr[k];
            arrResult.push(obj);
          } else if (k > 0 && arr[k] == "") {
            var obj = {};
            obj.Type = "br";
            obj.Content = "";
            arrResult.push(obj);
          }
          var obj = {};
          obj.Type = "return";
          arrResult.push(obj);
        }

        //去掉前回车换行
        // while (arrResult[0].Type == "return" ||
        //   arrResult[0].Type == "br") {
        //   arrResult.shift();
        //   if (arrResult.length == 0)
        //     break;
        // }

        //去掉后回车换行
        for (var i = arrResult.length - 1; i >= 0; i--) {
          if (arrResult[i].Type == "return" ||
            arrResult[i].Type == "br")
            arrResult.pop();
          else {
            break;
          }
        }
        result.Field.push(arrResult);

      } else {
        result.Field.push([]);
      }
    }
  }
  return result;
}

//得到当天任务
function getTaskTodayList(callback) {
  var isNotData = true;
  var intervalTask = setTimeout(function () {
    if (isNotData) {
      wx.showLoading({
        title: '请稍候',
        mask: true,
      });
      setTimeout(function () {
        wx.hideLoading();
      }, 60000);
    }
  }, 2000);

  var that = this;
  var url = 'GetMiaoguoCardToday2?UserID=' + app.globalData.userInfo.UserID;

  getData(url, function (data) {
    clearTimeout(intervalTask);
    if (isNotData) {
      wx.hideLoading();
    }
    isNotData = false;

    if (data) {
      app.globalData.TaskToday = data;

      callback(data);
    }
  });
}


function getTempImage(serverUrl) {
  if (serverUrl.indexOf("miaguo-1253256735") >= 0) {
    var list = wx.getStorageSync("TempImageList");
    if (!list)
      list = [];
    for (var i = 0; i < list.length; i++) {
      if (list[i].ServerUrl == serverUrl) {
        return list[i].TempUrl;
        break;
      }
    }
  }
  return serverUrl;
}


function getServerImage(tempUrl) {
  if (tempUrl.indexOf("http") < 0) {
    var list = wx.getStorageSync("TempImageList");
    if (!list)
      list = [];
    for (var i = 0; i < list.length; i++) {
      if (list[i].TempUrl == tempUrl) {
        return list[i].ServerUrl;
        break;
      }
    }
    return ""
  }
}

function saveTempImage(serverUrl, tempUrl) {
  if (tempUrl.indexOf("http") < 0) {
    var list = wx.getStorageSync("TempImageList");
    if (!list)
      list = [];
    var b = false;
    for (var i = 0; i < list.length; i++) {
      if (list[i].ServerUrl == serverUrl) {
        list[i].TempUrl = tempUrl;
        b = true;
        break;
      }
    }
    if (!b) {
      list.push({
        "ServerUrl": serverUrl,
        "TempUrl": tempUrl
      });
    }

    if (list.length > 200) {
      list.pop();
    }
    wx.setStorageSync("TempImageList", list);
  }
}

function UpdateMiaoguoCardTodayAll(isShowLoading, callback) {
  var that = this;
  if (isShowLoading) {
    wx.showLoading({
      title: '请稍候',
      mask: true,
    });
    clearTimeout(dataSendTimeout);
    dataSendTimeout = setTimeout(function () {
      wx.hideLoading();
      wx.reLaunch({
        url: '../index/index',
      })
    }, 60000);
  }
  var list = wx.getStorageSync("ListTaskFinished");
  if (list && list.length > 0) {
    var arr = [];
    for (var i = 0; i < list.length; i++) {
      var obj = {};
      obj.MiaoguoCardID = list[i].Card.MiaoguoCardID;
      obj.IntervalTime = list[i].IntervalTime;
      obj.BtnNumber = list[i].BtnNumber;
      obj.FontSize = list[i].Card.FontSize;
      obj.Duration = list[i].Duration;
      obj.LearningType = list[i].LearningType;
      obj.IsCollect = list[i].Card.IsCollect;
      obj.LastTime = list[i].LastTime;
      arr.push(obj);
    }
    that.postData('UpdateMiaoguoCardTodayAll?UserID=' + app.globalData.userInfo.UserID, {
      List: arr,
    }, function (data) {
      if (isShowLoading) {
        wx.hideLoading();
        clearTimeout(dataSendTimeout);
      }
      if (data) {
        wx.removeStorageSync("ListTaskFinished");
      }
      if (callback) {
        callback();
      }
    });
  } else {
    wx.hideLoading();
    clearTimeout(dataSendTimeout);
    if (callback) {
      callback();
    }
  }
}

function updateSearchList(obj,callback) {
  var arr = wx.getStorageSync("SearchWord3");
  if (!arr)
    arr = [];

  if (obj.Type == "shici") {
    if (obj.Value.CHN.ShiciTitle)
      obj.Key = obj.Value.CHN.ShiciTitle;
    if (obj.Key.indexOf("《") == 0)
      obj.Key = obj.Key.substring(1, obj.Key.length - 1);
  }
  for (var i = 0; i < arr.length; i++) {
    if (arr[i].Key == obj.Key
    ) {
      if (obj.Type == "shici") {
        if (arr[i].ShiciUrl == obj.ShiciUrl) {
          obj.Value = arr[i].Value;
          arr.splice(i, 1);
          break;
        }
      } else {
        var b=true;
        if (obj.Type && arr[i].Type && arr[i].Type != obj.Type)
          b=false;
        if (obj.Author && arr[i].Author && arr[i].Author != obj.Author)
          b=false;
        
        if (b){
          obj.Value = arr[i].Value;
          arr.splice(i, 1);
          break;
        }
      }

    }
  }
  if (obj.Key)
    arr.unshift(obj);

  if (arr.length > 30) {
    arr.pop();
  }
  wx.setStorageSync("SearchWord3", arr);

  app.globalData.SearchItem = obj.Value;
  if (obj.TypeName)
    app.globalData.SearchItem.TypeName = obj.TypeName;
  
  if (callback)
    callback();
}

function checkIsIPhoneX() {
  var isIphoneX = false;
  if (app.globalData.systemInfo.model.indexOf("iPhone X") >= 0 ||
    app.globalData.systemInfo.model.indexOf("iPhone X") >= 0) {
    isIphoneX = true;
  }
  return isIphoneX;
}

//设置收藏
function setCollect(id, collect, callback) {
  var that = this;
  if (collect) {
    wx.showToast({
      title: '加注成功',
      image: '../images/universalpic_star_white_120x120.png',
    });
  } else {
    wx.showToast({
      title: '清除成功',
      image: '../images/universalpic_star_whiteline_120x120.png',
    });
  }
  getData("UpdateMiaoguoCardInfo?UserID=" + app.globalData.userInfo.UserID + "&MiaoguoCardID=" + id + "&IsCollect=" + collect, function (data) {
    if (callback)
      callback();
  });
}

function buildInitData(callback) {
  var that = this;
  wx.showLoading({
    title: '数据初始化',
  });
  setTimeout(function () {
    wx.hideLoading();
  }, 5000);

  getData('BuildInitData?UserID=' + app.globalData.userInfo.UserID, function (data) {
    wx.hideLoading();
    if (data) {
      if (callback)
        callback();
    }
  });
}

function getMemoryLevelAll() {
  return constant.arrMemoryLevelAll;
}

function getMemoryLevel(index, number, time) {
  var arr = getMemoryLevelAll();
  if (index < 1)
    return arr[index].Value[number].Name;
  else
    return replaceStr(time);

  function replaceStr(data) {
    var result = "";
    if (data.indexOf("d") > 0) {
      var dayNum = Number(data.replace("d", ""));
      if (dayNum >= 365) {
        var year1 = Math.floor(dayNum / 365);
        var year = year1 + Math.round(10 * (dayNum - year1 * 365) / 365) / 10;
        result = year + "年后";
      } else {
        if (dayNum > 31) {
          var month1 = Math.floor(dayNum / 30);
          var month = month1 + Math.round(10 * (dayNum - month1 * 30) / 30) / 10;
          result = month + "月后";
        } else {
          result = Number(data.replace("d", ""));
          if (result == 1)
            result = "明天";
          else if (result == 2)
            result = "后天";
          else
            result = (result - 1) + "天后";
        }
      }

    } else if (data.indexOf("m") > 0)
      result = data.replace("m", "分钟内");
    return result;
  }
}
//得到要检验的汉字列表
function GetHanziUnitWords(unitsID, testType, callback) {
  getData('GetHanziUnitWords?UnitID=' + unitsID, function (data) {
    if (data) {
      var TaskList = [];
      var words = data;
      for (var k = 0; k < words.length; k++) {
        var taskInfo = {
          FontSize: 144,
          TagWidth: 136,
          Content: [{
              ContentType: 0,
              Content: []
            },
            {
              ContentType: 1,
              Content: []
            },
            {
              ContentType: 2,
              Content: []
            },
          ]
        };
        taskInfo.Word = words[k].Name;

        var pinyinNormal = "(" + getPinyinNormal(words[k].Pinyin) + ")";
        var combineWords = common.ReplaceAllString(words[k].CombineWords, words[k].Name, words[k].Name + pinyinNormal);

        taskInfo.ReadString = words[k].Name + pinyinNormal + "," + combineWords + "的" + words[k].Name + pinyinNormal;

        if (testType == "read") {
          taskInfo.Content[0].Content = ["怎么念"];
          var question = words[k].CombineWords;
          question = common.ReplaceAllString(question, words[k].Name, "(" + words[k].Name + ")");
          taskInfo.Content[1].Content = question;


          var answer = "[读 src='" + taskInfo.ReadString + "']" + words[k].Pinyin + "[/读]";
          taskInfo.Content[2].Content = answer;

          if (words[k].CombineWords.length > 6) {
            taskInfo.FontSize = 108;
            if (words[k].CombineWords.length > 10) {
              taskInfo.FontSize = 68;
            }
          }
        } else if (testType == "write") {
          taskInfo.Content[0].Content = ["怎么写"];

          var question = words[k].CombineWords;
          var question2 = common.ReplaceAllString(question, words[k].Name, words[k].Pinyin);

          question = "[读 src='" + taskInfo.ReadString + "']" + question2 + "[/读]"
          taskInfo.Content[1].Content = question;
          var answer = words[k].Name;
          answer += "[图 w='650' h='650']" + words[k].BiShunUrl + "[/图]";
          taskInfo.Content[2].Content = answer;

          if (question2.length > 6) {
            taskInfo.FontSize = 108;
            if (question2.length > 10) {
              taskInfo.FontSize = 68;
              if (question2.length > 14) {
                taskInfo.FontSize = 48;
              }
            }
          }
        }
        taskInfo.ContentNew = changeStringToView(taskInfo.Content);
        TaskList.push(taskInfo);
      }

      callback(TaskList);
    } else {
      callback([]);
    }
  });
}

function GetTestReportInfo(reportid, callback) {
  var UserTestReport = wx.getStorageSync('UserTestReport');

  for (var n = 0; n < UserTestReport.length; n++) {
    if (UserTestReport[n].ID == reportid) {
      var name1 = UserTestReport[n].Name[0].split(" ");
      var name2 = UserTestReport[n].Name[1];

      if (name1[0].indexOf("英语") >= 0) {
        //todo
        //console.log("英语");
        var arrEnglist = wx.getStorageSync("EnglishAll");
        if (arrEnglist)
          arrEnglist = JSON.parse(arrEnglist);
        else
          arrEnglist = [];
        var wordStr = "";
        for (var i = 0; i < arrEnglist.length; i++) {
          if (arrEnglist[i].Name == name1[1]) {
            for (var j = 0; j < arrEnglist[i].Units.length; j++) {
              if (arrEnglist[i].Units[j].Name == name2) {
                wordStr = arrEnglist[i].Units[j].Words.join(",");
                break;
              }
            }
          }
        }
        var userTestReportInfo = UserTestReport[n];
        var bookid = Number(name1[1].substr(4)) + 12;

        var tempRight = "," + userTestReportInfo.TestRightStr + ",";
        var tempWrong = "," + userTestReportInfo.TestWrongStr + ",";
        var tempSkip = "," + userTestReportInfo.TestSkipStr + ",";
        var tempExist = "," + userTestReportInfo.TestExistStr + ",";
        getData('GetTestEnglishWords?UserID=' + app.globalData.userInfo.UserID + '&Words=' + wordStr, function (data) {
          if (data) {
            var result = {};
            result.ID = userTestReportInfo.ID;
            result.IsFinished = userTestReportInfo.IsFinished;
            result.Name = userTestReportInfo.Name.join("#");
            result.TestType = userTestReportInfo.TestType;
            result.BookID = bookid;

            var TaskList = [];
            var words = data;
            for (var k = 0; k < words.length; k++) {
              var taskInfo = words[k];

              taskInfo.TagWidth = 364;
              taskInfo.ContentNew = changeStringToView(taskInfo.Content);
              if (tempRight.indexOf("," + taskInfo.Word + ",") >= 0)
                taskInfo.Result = 1;
              if (tempWrong.indexOf("," + taskInfo.Word + ",") >= 0)
                taskInfo.Result = -1;
              if (tempSkip.indexOf("," + taskInfo.Word + ",") >= 0)
                taskInfo.Result = 0;

              if (tempExist.indexOf("," + taskInfo.Word + ",") >= 0)
                taskInfo.Css = "Select2";

              TaskList.push(taskInfo);
            }
            result.TestRightStr = "";
            result.TestWrongStr = "";
            result.TestSkipStr = "";
            result.TestExistStr = "";
            if (userTestReportInfo.TestRightStr)
              result.TestRightStr = userTestReportInfo.TestRightStr;
            if (userTestReportInfo.TestWrongStr)
              result.TestWrongStr = userTestReportInfo.TestWrongStr;
            if (userTestReportInfo.TestSkipStr)
              result.TestSkipStr = userTestReportInfo.TestSkipStr;
            if (userTestReportInfo.TestExistStr)
              result.TestExistStr = userTestReportInfo.TestExistStr;

            result.List = TaskList;
            callback(result);
          } else {
            callback({});
          }
        });

      } else {
        name1 = name1[0] + name1[1].substr(2, 2) + "能力" + name1[2].substr(0, 1);
        var HanziAll = wx.getStorageSync('HanziAll');
        HanziAll = JSON.parse(HanziAll);
        for (var i = 0; i < HanziAll.length; i++) {
          if (name1 == HanziAll[i].Name) {
            for (var j = 0; j < HanziAll[i].Units.length; j++) {
              if (name2 == HanziAll[i].Units[j].Name) {
                var obj = UserTestReport[n];
                GetHanziUnitWords(HanziAll[i].Units[j].ID, obj.TestType, function (list) {
                  if (list) {
                    for (var k = 0; k < list.length; k++) {
                      if (obj.TestRightStr && obj.TestRightStr.indexOf(list[k].Word) >= 0)
                        list[k].Result = 1;
                      else if (obj.TestWrongStr && obj.TestWrongStr.indexOf(list[k].Word) >= 0)
                        list[k].Result = -1;
                      else if (obj.TestSkipStr && obj.TestSkipStr.indexOf(list[k].Word) >= 0)
                        list[k].Result = 0;

                      if (obj.TestExistStr && obj.TestExistStr.indexOf(list[k].Word) >= 0)
                        list[k].Css = "Select2";

                    }
                    var result = {};
                    result.ID = reportid;
                    result.TestType = obj.TestType;
                    result.Name = obj.Name.join("#");
                    result.IsFinished = obj.IsFinished;
                    result.TestRightStr = obj.TestRightStr;
                    result.TestWrongStr = obj.TestWrongStr;
                    result.TestSkipStr = obj.TestSkipStr;
                    result.TestExistStr = obj.TestExistStr;
                    result.List = list;
                    callback(result);
                  } else
                    callback({});
                });
              }
            }
          }
        }
      }
    }
  }
}

function getDetailColor(index) {
  var arrDetailColor = constant.arrDetailColor;
  if (index > 0)
    return arrDetailColor[index];
  else if (index == 0)
    return arrDetailColor[common.random(1, arr.length - 1)];
  else if (index == -1)
    return arrDetailColor;
}

function getShareImageBackColor() {
  var arr = constant.arrShareImageBackColor;
  return arr[common.random(0, arr.length - 1)];
}

function getPinyinNormal(pinyin) {
  var result = "";
  var arr = constant.arrPinyin;
  for (var i = 0; i < arr.length; i++) {
    if (arr[i][1] == pinyin) {
      result = arr[i][0];
      break;
    }
  }
  return result;
}

function getHanzi(callback) {
  var that = this;
  wx.showLoading({
    title: '请稍候',
    mask: true,
  });
  var time = wx.getStorageSync("HanziUpdateTime");
  getData('GetHanziAll2?HasEnglish=true&HasHanziWrite=true&UpdateTime=' + time, function (data) {
    wx.hideLoading();
    if (data) {
      var arr = [];
      if (data.List) {
        arr = common.Decrypt(data.List);
        wx.setStorageSync("HanziAll", arr);

        var arrEng = common.Decrypt(data.EngList);
        wx.setStorageSync("EnglishAll", arrEng);
        wx.setStorageSync("HanziUpdateTime", data.UpdateTime);
      } else {
        arr = wx.getStorageSync("HanziAll");
        if (arr)
          arr = JSON.parse(arr);
      }
      callback(arr);
    }
  });
}

function UploadUserConfig(callback) {
  var that = this;
  var param1 = {};
  param1.CardType = wx.getStorageSync("CardType");
  param1.CardMaxNumberNew = wx.getStorageSync("CardMaxNumberNew");
  param1.CardMaxNumberHistory = wx.getStorageSync("CardMaxNumberHistory");
  param1.CardMaxNumberNewUrgent = wx.getStorageSync("CardMaxNumberNewUrgent");
  param1.CardMaxNumberHistoryUrgent = wx.getStorageSync("CardMaxNumberHistoryUrgent");
  param1.SortTypeIndex = wx.getStorageSync("SortTypeIndex");
  param1.MemoryLevel = wx.getStorageSync("MemoryLevel");

  param1.ClickType = wx.getStorageSync("ClickType");
  param1.SecondConfigArray = wx.getStorageSync("SecondConfigArray").join(",");
  param1.ColorIndexArr = wx.getStorageSync("ColorIndexArr").join(",");

  var symboMain = wx.getStorageSync("SymbolMain");
  var symbol1 = [];
  for (var i = 0; i < symboMain.length; i++) {
    symbol1.push(symboMain[i].Name);
  }
  symbol1 = JSON.stringify(symbol1);
  param1.SymbolList = symbol1;

  that.postData('UploadUserConfig?Type=update&UserID=' + app.globalData.userInfo.UserID, param1, function (data) {
    if (callback) {
      callback();
    }
  });
}

function getAwardData(callback) {
  var that = this;
  that.getData('GetAwardInfo?UserID=' + app.globalData.userInfo.UserID, function (data) {
    if (data) {
      callback(data);
    } else
      callback([]);
  });
}

function getUserConfig() {
  var that = this;
  postData('UploadUserConfig?Type=getData&UserID=' + app.globalData.userInfo.UserID, {}, function (data) {

    if (data && !data.CardType)
      data.CardType = 0;

    wx.setStorageSync("CardType", data.CardType);
    wx.setStorageSync("CardMaxNumberNew", data.CardMaxNumberNew);
    wx.setStorageSync("CardMaxNumberHistory", data.CardMaxNumberHistory);
    wx.setStorageSync("CardMaxNumberNewUrgent", data.CardMaxNumberNewUrgent);
    wx.setStorageSync("CardMaxNumberHistoryUrgent", data.CardMaxNumberHistoryUrgent);
    wx.setStorageSync("SortTypeIndex", data.SortTypeIndex);
    wx.setStorageSync("MemoryLevel", data.MemoryLevel);
    wx.setStorageSync("ClickType", data.ClickType);
    wx.setStorageSync("SecondConfigArray", data.SecondConfigArray.split(","));
    wx.setStorageSync("ColorIndexArr", data.ColorIndexArr.split(","));

    var symbol1 = [];
    if (data.SymbolList) {
      for (var i = 0; i < data.SymbolList.length; i++) {
        var obj = {};
        obj.Name = data.SymbolList[i];
        obj.CSS = "btn2";
        symbol1.push(obj);
      }
    } else {
      symbol1 = app.globalData.SymbolMain;
    }
    if (symbol1.length>0){
      wx.setStorageSync("SymboMain", symbol1);
      app.globalData.SymbolMain = symbol1;
    }
    
  });
}

function replaceCardInfoString(str) {
  var that = this;
  //str = str.replace(/\[图]/g, "");
  //str = str.replace(/\[\/图\]/g, "");
  
  var str2 = "";
  if (str.indexOf("[读 src=") >= 0) {
    str2 = str.substr(str.indexOf("[读 src="));
    str2 = str2.substring(0, str2.indexOf("/读]") + 3);
  }
  str = str.replace(str2, "");

  if (str.indexOf("[读 src=") >= 0) {
    str2 = str.substr(str.indexOf("[读 src"));
    str2 = str2.substring(0, str2.indexOf("/读]") + 3);
  }
  str = str.replace(str2, "");

  str = str.replace(/\[读]/g, "");
  str = str.replace(/\[\/读\]/g, "");

  var str3 = "";
  if (str.indexOf("[图") >= 0) {
    str3 = str.substr(str.indexOf("[图"));
    str3 = str3.substring(0, str3.indexOf("/图]") + 3);
  }
  str = str.replace(str3, "");
  if (str.indexOf("[图") >= 0) {
    str3 = str.substr(str.indexOf("[图"));
    str3 = str3.substring(0, str3.indexOf("/图]") + 3);
  }
  str = str.replace(str3, "");

  str = str.replace(/\[线]/g, "");
  str = str.replace(/\[\/线\]/g, "");
  str = that.encryptUrl(str);
  return str;
}

function searchInfomation(search,searchtype,author,shiciurl,callback){
  var WORD_LENGTH=18;
  wx.showLoading({
    title: '查询中',
  });
  var timeout=setTimeout(function () {
    wx.hideLoading();
  }, 5000);

  var url = 'GetMiaoguoAISearch2?UserID=' + app.globalData.userInfo.UserID;
  url += "&Word=" + search;
  if (searchtype)
    url += "&SearchType=" + searchtype;
  if (author)
    url += "&Author=" + author;
  if (shiciurl)
    url += "&ShiciUrl=" + shiciurl;

  getData(url, function (data) {
    wx.hideLoading();
    clearTimeout(timeout);
    
    if (data) {
      //console.log(data);

      if (data.List) {
        var len = WORD_LENGTH;
        var list = data.List;
        for (var i = 0; i < list.length; i++) {
          var item = list[i];
          if (item.TypeName == "字词") {
            if (item.Key.length == 1)
              item.TypeName = "Z";
            else
              item.TypeName = "C";
          } else if (item.TypeName == "诗词") {
            item.TypeName = "S";
            item.Remark = item.Author + " " + item.Dynasty;
          } else if (item.TypeName == "翻译") {
            item.TypeName = "D";
          }

          if (item.Content && item.Content.length > len)
            item.Content = item.Content.substr(0, len) + "...";

        }
        callback(list);

      } else if (data.CHN || data.ENG) {
        var obj = {};
        obj.Key = search;
        obj.Value = data;
        if (data.CHN && data.CHN.Author)
          obj.Author = data.CHN.Author;
        if (data.CHN && data.CHN.Dynasty)
          obj.Dynasty = data.CHN.Dynasty;
        if (data.CHN && data.CHN.PeomContent) {
          obj.Type = "shici";
          obj.TypeName = "诗词";
          obj.Content = data.CHN.PeomContent.join("").substr(0, WORD_LENGTH);
          obj.ShiciUrl = shiciurl;
        } else if (data.CHN) {
          obj.Type = "zici";
          if (data.CHN.PinYin && data.CHN.PinYin[0] && data.CHN.PinYin[0].pinyin)
            obj.Remark = data.CHN.PinYin[0].pinyin;
          if (data.CHN.PinYin && data.CHN.PinYin[0] && data.CHN.PinYin[0].explain) {
            obj.Content = data.CHN.PinYin[0].explain.substr(0, WORD_LENGTH);
            obj.Content = obj.Content.replace("<p>", "");
            obj.Content = obj.Content.replace("</p>", "");
            if (obj.Content.length >= WORD_LENGTH)
              obj.Content += "..."
          }
        }
        if (data.ENG && !data.CHN) {
          obj.Type = "eng";
          obj.TypeName = "D";
          if (data.ENG.Soundmark && data.ENG.Soundmark.Eng)
            obj.Remark = data.ENG.Soundmark.Eng;
          if (data.ENG.Paraphrase.length > 0) {
            if (common.checkIsArray(data.ENG.Paraphrase) && data.ENG.Paraphrase[0].ParaphraseList)
              obj.Content = data.ENG.Paraphrase[0].ParaphraseList.join("; ").substr(0, WORD_LENGTH);
            else
              obj.Content = data.ENG.Paraphrase.substr(0, WORD_LENGTH) + "...";
          }
        }
        app.globalData.TempSearchBackNumber = 2;
        //app.globalData.CardList=[];
        app.globalData.CardList2=[];
        
        callback([],obj);
      }
      else{
        callback([]);

      }
    } else {
      callback([]);
    }
  });
}

module.exports = {
  getData: getData,
  postData: postData,
  payMoney: payMoney,
  getLocalHost: getLocalHost,
  getTimeFormat: getTimeFormat,
  getWindowHeight: getWindowHeight,
  getStorageValue: getStorageValue,
  getProgramList: getProgramList,
  gotoFeedback: gotoFeedback,
  getDetailColor: getDetailColor,
  changeStringToView: changeStringToView,
  changeViewToString: changeViewToString,
  encryptUrl: EncryptUrl,
  decryptUrl: DecryptUrl,
  saveTempImage: saveTempImage,
  getTempImage: getTempImage,
  getTaskTodayList: getTaskTodayList,
  updateSearchList: updateSearchList,
  checkIsIPhoneX: checkIsIPhoneX,
  getMemoryLevelAll: getMemoryLevelAll,
  getMemoryLevel: getMemoryLevel,
  getShareImageBackColor: getShareImageBackColor,
  UpdateMiaoguoCardTodayAll: UpdateMiaoguoCardTodayAll,
  setCollect: setCollect,
  UploadUserConfig: UploadUserConfig,
  getServerImage: getServerImage,
  getBaiduToken: getBaiduToken,
  buildInitData: buildInitData,
  getPinyinNormal: getPinyinNormal,
  getHanzi: getHanzi,
  GetHanziUnitWords: GetHanziUnitWords,
  GetTestReportInfo: GetTestReportInfo,
  getUserConfig: getUserConfig,
  getAwardData: getAwardData,
  replaceCardInfoString: replaceCardInfoString,
  searchInfomation:searchInfomation,
}