import { showToast } from './utils/feedback'
import { formatTime, arrRemoveObj, getTypeItem } from './utils/util'

// const baseUrl = "https://test-ding.g107.com/";//测试
const baseUrl = "https://ding.insys.g107.com/";//正式
var that;
var yearArr = [];
var year = formatTime(new Date()).year;
for (var i = 2018; i <= year; i++) {
  yearArr.push(i);
}
App({
  //自定义全局变量
  globalData: {
    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: '',
    // token:' eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvZGluZy5pbnN5cy5nMTA3LmNvbVwvYXBpXC9kaW5nXC9sb2dpbiIsImlhdCI6MTYwMDMxNDM0NywiZXhwIjoxNjAwOTE0MzQ3LCJuYmYiOjE2MDAzMTQzNDcsImp0aSI6IjgwMFJUS0J4RllIbnU5M3EiLCJzdWIiOjIsInBydiI6ImNhNjQ4OWQ1MGYyNDA3YTY3ODMwZTgwOTBkMDE0ODgzNTY4NTk2MmIiLCJyb2xlIjoiZW1wbG95ZWUifQ.E1RiQ6uMRICoL-2qDTeh5j5y-QLaUsGGs6PYLm-_1m8',
    ALIOSS_URL: 'https://integralsys.oss-cn-shenzhen.aliyuncs.com',
    imgHttpUrl: 'https://intesys.cms.g107.com/integral.php/Api/get_signature',
    corpId: '',
    yearArr: yearArr,
    isAdministrator: false,//是否管理员
    isCreator: false,//是否是创始人
    corpMessage: '',//企业套餐信息
  },
  //获取积分类型
  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,
        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',
        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 : ''
        },
        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 {
            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);
        }
      });
    })
  },
  //封装post
  $post(url, data = {}, Accept) {
    // if (url == 'api/ding/login') {
    //   return that.routerPost(url, data, Accept);
    // }
    // if (!that.globalData.token) {
    //   dd.navigateTo({
    //     url: '../../init/init'
    //   })
    //   return Promise.reject("登录中")
    // } else {
    return that.routerPost(url, data, Accept);
    // }
  },
  //封装get
  $get(url, data = {}, Accept) {
    // if (url == 'api/integral/types' || url == 'api/order/corp') {
    //   return that.routerGet(url, data, Accept);
    // }
    // if (!that.globalData.token) {
    //   dd.navigateTo({
    //     url: '../../init/init'
    //   })
    //   return Promise.reject("登录中")
    // } else {
    return that.routerGet(url, data, Accept);
    // }
  },
  //封装get
  $get2(url, data = {}, Accept) {
    // if (url == 'api/integral/types' || url == 'api/order/corp') {
    //   return that.routerGet2(url, data, Accept);
    // }
    // if (!that.globalData.token) {
    //   dd.navigateTo({
    //     url: '../../init/init'
    //   })
    //   return Promise.reject("登录中")
    // } else {
    return that.routerGet2(url, data, Accept);
    // }
  },
  //免登
  login(corpId, callBack) {
    if (that.globalData.token) {
      callBack(true)
    } else {
      dd.getAuthCode({
        success: function (res) {
          // console.log(res.authCode,corpId)
          // return;
          that.$post('api/ding/login', { authCode: res.authCode, corpId: corpId }).then(res => {
            if (res.data.code == 1) {
              var { token, user } = res.data.data;
              var isStart = false;
              if (user.is_official == 1) {
                user.employee_detail.role_list.forEach(item => {
                  if (item.name == 'creator') {
                    that.globalData.isCreator = true;
                    isStart = true;
                  }
                  if (item.name == 'admin' || item.name == 'creator' || item.name == 'point_manager' || item.name == 'dept_manager') {
                    that.globalData.isAdministrator = true;
                  }
                });
                that.globalData.token = token;
                that.globalData.userData = user;
                var getIsStart = dd.getStorageSync({ key: 'isStart' });//判断是否需要打开引导页
                // console.log(JSON.stringify(user));
                if (isStart && !getIsStart.data) {//判断是否需要打开引导
                  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 => {
            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(err)
        }
      });
    }
  },

  getTypesItem(id) {
    return getTypeItem(this.globalData.types, id);
  },
  onLaunch(options) {
    that = this;
    that.getTypes(function () { });
    that.getCorp(options.query.corpId);
    that.globalData.corpId = options.query.corpId;
  },
});
