import { showToast } from './utils/feedback'
import { formatTime, arrRemoveObj, getTypeItem,setCache } from './utils/util'
import * as socketApi from './utils/websocket'

// const baseUrl = "https://dp-test.g107.com/";//测试
const baseUrl = "https://app109758.eapps.dingtalkcloud.com/";//测试
var that;
var yearArr = [];
var year = formatTime(new Date()).year;
for (var i = 2018; i <= year; i++) {
  yearArr.push(i);
}
App({
  //自定义全局变量
  globalData: {
    baseUrl: baseUrl,
    // webScoketUrl: "test-ding.g107.com",//webScoket测试
    webScoketUrl: "app109758.eapps.dingtalkcloud.com",
    showToast: showToast,//提示框
    arrRemoveObj: arrRemoveObj,//删除数组的某一项
    year: formatTime(new Date()).year,//当前年
    month: formatTime(new Date()).month,//当前月
    day: formatTime(new Date()).day,//当前日
    month_tow: formatTime(new Date()).month_tow,//当前月份
    allDate: formatTime(new Date()).allDate,//带时分
    types: [],
    userData:"",
    token:'',
    ALIOSS_URL: 'https://gdyapp.oss-cn-shenzhen.aliyuncs.com',
    imgHttpUrl: 'https://intesys.cms.g107.com/integral.php/Api/get_signature',
    corpId: '',
    yearArr: yearArr,
    isAdministrator: false,//是否管理员
    isCreator: false,//是否是创始人
    corpMessage: '',//企业套餐信息
    usersList: [],//缓存的人员列表
    socketApi: socketApi,//长连接
  },
  //获取积分类型
  getTypes(callBack) {
    this.$get("api/integral/types", {}).then((res) => {
      this.globalData.types = res.data.data.list;
      callBack();
    })
  },
  //获取套餐信息
  getCorp(corpId) {
    this.$get("api/order/corp", { corp_id: corpId }).then((res) => {
      this.globalData.corpMessage = res.data.data;
    })
  },
  routerGet2(url, data = {}, Accept) {
    return new Promise(function (resolve, reject) {
      dd.httpRequest({
        url: baseUrl + url,
        method: 'GET',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'A-Token': that.globalData.token,
          'Accept': Accept ? Accept : ''
        },
        data: data,
        timeout: 10000,
        dataType: 'json',
        success: function (res) {
          if (res.data.code == 1) {
            if (res.data.refresh_token && res.data.refresh_token != that.globalData.token) {
              that.globalData.token = res.data.refresh_token
            }
            resolve(res);
          } else if (res.data.code == 401) {
            that.globalData.showToast("授权已过期");
            // reject(res);
          } else {
            that.globalData.showToast(res.data.msg)
            // reject(res);
          }
        },
        fail: function (res) {
          if (res.errorMessage == 'NETWORK ERROR') {
            dd.alert({
              title: '网络异常',
              content: '网络异常，请检查网络是否畅通，再重新进入应用',
              buttonText: '我知道了',
              success: () => { },
            });
            return;
          }
          reject(res);
        }
      });
    })
  },
  routerGet(url, data = {}, Accept) {
    return new Promise(function (resolve, reject) {
      dd.showLoading();
      dd.httpRequest({
        url: baseUrl + url,
        method: 'GET',
        timeout: 10000,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'A-Token': that.globalData.token,
          'Accept': Accept ? Accept : ''
        },
        data: data,
        dataType: 'json',
        success: function (res) {
          if (res.data.code == 1) {
            if (res.data.refresh_token && res.data.refresh_token != that.globalData.token) {
              that.globalData.token = res.data.refresh_token
            }
            resolve(res);
          } else if (res.data.code == 401) {
            that.globalData.showToast("授权已过期");
            // reject(res);
          } else {
            that.globalData.showToast(res.data.msg)
            // reject(res);
          }
        },
        fail: function (res) {
          if (res.errorMessage == 'NETWORK ERROR') {
            dd.alert({
              title: '网络异常',
              content: '网络异常，请检查网络是否畅通，再重新进入应用',
              buttonText: '我知道了',
              success: () => { },
            });
            return;
          }
          reject(res);
        },
        complete: function () {
          dd.hideLoading();
        }
      });
    })
  },
  routerPost(url, data = {}, Accept) {
    return new Promise(function (resolve, reject) {
      dd.httpRequest({
        url: baseUrl + url,
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'A-Token': that.globalData.token,
          'Accept': Accept ? Accept : ''
        },
        timeout: 10000,
        data: data,
        dataType: 'json',
        success: function (res) {
          if (res.data.code == 1) {
            if (res.refresh_token && res.data.refresh_token != that.globalData.token) {
              that.globalData.token = res.data.refresh_token
            }
            resolve(res);
          } else if (res.data.code == 401) {
            that.globalData.showToast("授权已过期");
            reject(res);
          } else if (res.data.code == 3000) {
            reject(res);
          } else {
            that.globalData.showToast(res.data.msg);
            reject(res);
          }
        },
        fail: function (res) {
          if (res.error == 19 || res.error == 13) {
            if (url == 'api/integral/review/a/entry' || url == 'api/integral/point/entry') {
              let sum = 0;
              if (data) {
                sum = Number(JSON.parse(data.items).length) * Number(JSON.parse(data.members).length);
              }
              that.$post('api/e', { sum: sum, message: '钉钉小程序' }).then(res => { })
            }
          }
          if (res.errorMessage == 'NETWORK ERROR') {
            dd.alert({
              title: '网络异常',
              content: '网络异常，请检查网络是否畅通，再重新进入应用',
              buttonText: '我知道了',
              success: () => { },
            });
            return;
          }
          reject(res);
        }
      });
    })
  },
  //封装post
  $post(url, data = {}, Accept) {
    return that.routerPost(url, data, Accept);
  },
  //封装get
  $get(url, data = {}, Accept) {
    return that.routerGet(url, data, Accept);
  },
  //封装get
  $get2(url, data = {}, Accept) {
    return that.routerGet2(url, data, Accept);
  },
  //免登 isShowStart是否显示引导页
  login(corpId, callBack, errBack = function () { }, isShowStart = false) {
    if (that.globalData.token) {
      callBack(true)
    } else {
      dd.getAuthCode({
        success: function (res) {
          that.$post('api/ding/login', { authCode: res.authCode, corpId: corpId }).then(res => {
            if (res.data.code == 1) {
              let user = res.data.data;
              // var isStart = false;
              if (user.is_official == 1) {
                // if (user.is_creator) {
                //   that.globalData.isCreator = true;
                //   isStart = true;
                // }
                that.globalData.token = user.token;
                that.globalData.userData = user;
                var getIsStart = dd.getStorageSync({ key: 'isStart' });//判断是否需要打开引导页
                console.log(JSON.stringify(user));
                // that.getUserList();//缓存人员列表
                that.setRouters();
                // if (isStart && !getIsStart.data && isShowStart) {//判断是否需要打开引导
                //   dd.reLaunch({
                //     url: '../start/start'
                //   })
                // } else {
                  callBack(true);
                // }
              } else {
                callBack(false);
              }
            } else if (res.data.code == 3000) {
              that.globalData.showToast("员工信息同步中，请稍后进入")
            } else {
              that.globalData.showToast(res.msg)
            }
          }).catch(err => {
             console.log(JSON.stringify(err))
            errBack(err.data);
            return
            if (err.data.code == 2001) {
              dd.confirm({
                title: '尊敬的用户',
                content: '你当前的套餐已到期',
                confirmButtonText: '去续费',
                cancelButtonText: '暂不需要',
                success: (result) => {
                  if (result.confirm) {
                    dd.reLaunch({
                      url: `../../deploy/addMoney/addMoney`
                    })
                  }
                },
              });
            }
          })
        },
        fail: function (err) {
          console.log(JSON.stringify(err))
          that.globalData.showToast("错误" + JSON.stringify(err))
        }
      });
    }
  },
  //返回用户Code
  returnCode(data) {
    let list=this.globalData.usersList;
    if(Array.isArray(data)){
      let result =data.map(e=>{
        if(list[e]){
          return list[e].code
        }
      })
      return JSON.stringify(result)
    }else{
      data=data.toString()
      var arr = data.split(",");
      let result =arr.map(e=>{
        if(list[e]){
          return list[e].code
        }
      })
      return result.toString()
    }
  },
  setRouters() {
    let main = this.globalData.userData.permission_info.main;
    let per_role = this.globalData.userData.permission_info.per_role; // 用户的身份
    if (per_role == 'manager') {
      if (main == 1) {
        // 主管理员
        this.plusStoSet('masterAdministrator');
      } else {
        // 子管理员
        this.plusStoSet('childAdministrator');
      }
    } else {
      // 员工||创始人||部门管理员
      // if (this.globalData.isCreator) {
      //   this.plusStoSet('creator');
      // } else 
      if (this.globalData.userData.manage_dept_list.length > 0) {
        this.plusStoSet('deptManager');
      } else {
        this.plusStoSet('employee');
      }
    }
  },
  plusStoSet(val) {
    setCache('role', val);
  },
  // 判断当前登录者是否有某项权限
  getPermis(type){
    /* type为传入的权限id*/
    let jurisdictions = this.globalData.userData.permission_info.permission.map((item) => {
      return item.id
    })
    return jurisdictions.indexOf(type) >= 0
  },
  getUserList() {
    this.$get("api/per/user/employee_list", { page: 0, page_size: 0 }).then((res) => {
      let list = res.data.data.list
      let data = {}
      for (let i in list) {
        if (list[i].is_scope === 0||list[i].is_official ===0) {
					list[i].name = list[i].name + '(未启用)';
				}
        data[list[i].id] = list[i];
      }
      that.globalData.usersList = data;
    })
  },
  getTypesItem(id) {
    return getTypeItem(this.globalData.types, id);
  },
  updateApp() {
    const updateManager = dd.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      // console.log(res.hasUpdate) // 是否有更新
    })
    updateManager.onUpdateReady(function (ret) {
      // console.log(ret.version) // 更新版本号
      dd.confirm({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
    })
  },
  onLaunch(options) {
    dd.globalData = this.globalData;
    that = this;
    that.updateApp();
    // that.getTypes(function () { });
    // that.getCorp(options.query.corpId);
    that.globalData.corpId = options.query.corpId;
  },
});
