const wx2my = require('../wx2my');
const Behavior = require('../Behavior');
import { getAppUserInfo, getC1, getC2, getC3, needOpenCard, getCurrentRouter } from './helper';
import Router from './router';
import ManageDate from './manageDate';
import { cEvent } from './event';
import Http from './Http';
const Promise = require('../lib/bluebird');
const config = require('../config/index').envInfo;
import utils from './util';
let openCardLister = null;
import * as watch from "./watch.js";
const pathData = require('./currentAccessiblePath.js')
/**
 * 单例
 */
const manageDate = new ManageDate();

class WXService extends Http {
  constructor() {
    super();
    this.Promise = Promise;
    this.currentPage = null;
  }

  getToken() {
    return super.getToken();
  }
  /**
   * 所有接口中返回401就登录
   * 返回402 重试 （getUserInfoLimitCount：重试次数）,超过重试次数提示会员系统异常,请联系管理员
   */


  request({
    url,
    data,
    header,
    method,
    dataType,
    responseType,
    success,
    fail,
    complete
  }) {
    return super.request.apply(this, arguments).finally(() => {
      this.setPageLoadStatus();
      wx2my.hideLoading();
    }).catch(res => {
      console.log('res.desc', res)
      if (res.data && res.data.desc.indexOf('未登录') > -1) {
        if (!this.getUserInfoLimitCount) {
          this.getUserInfoLimitCount = 1;
        } else {
          this.getUserInfoLimitCount++;
        }

        console.log('count', this.getUserInfoLimitCount);

        if (this.getUserInfoLimitCount > 3) {
          wx2my.showToast({
            title: '会员系统异常,请联系管理员',
            icon: 'none',
            duration: 2000
          });
        } else {
          this.reLogin();
        }
      } else if (res.msg && res.msg.indexOf('请重新授权') > -1) {
        wx2my.setStorageSync('reLoginErr', true); // wxService.router(`/pages/userCenter/userCenter`).replace()

        console.log("授权跳转");
        wxService.router(`/pages/userCenter/userCenter`).back();
      }
    });
  } // 所有页面都有接口load状态


  setPageLoadStatus() {
    if (this.currentPage) {
      this.nextTick(() => {
        this.currentPage.setData({
          loadStatus: this.state
        });
      });
    }
  }
  /**
   * 页面导航
   * @param url
   * @param switchTab 是否是switchTab导航
   */


  router(url, switchTab) {
    return new Router(url, switchTab);
  }

  back(dintance) {
    this.router().back(dintance);
  }

  replace(url) {
    this.router(url).replace();
  }

  all() {
    return Promise.all.apply(Promise, arguments);
  }
  /**
   * 更新缓存 登陆
   * 
  */
  reLogin() {
    console.log('reLogin')
    wx2my.setStorageSync('token', '');
    wx2my.setStorageSync('reLoginErr', false)

    const app = getApp();
    var _this = this;
    return _this.login().then(result => {
      if (result.authCode) {
        _this.post(`/member/alipay/minaLogin?code=${result.authCode}&brandId=${app.globalData.brandId}` 
        // {
        //   code: result.authCode,
        //   // wechatInfo: null,
        //   brandId: app.globalData.brandId
        // }
        ).then(response => {
          let dataResp = response.data.data;
          wx2my.setStorageSync('token', dataResp.token);
          wx2my.setStorageSync('_baseUserInfo', dataResp);
          wx2my.setStorageSync('reLoginErr', false)

          // 刷新页面
            setTimeout(() => {
              const pages = getCurrentPages()
              const perpage = pages[pages.length - 1]
              perpage.onShow()
            }, 2000)

          return Promise.resolve({
            response
          });
        }).catch(err => {
          return Promise.reject(err);
        });
      } else {
        return Promise.reject({
          state: 2,
          info: res.data.data
        });
      }
    }).catch(err => {
      console.log(err);
    });
  }

  login() {
    return new Promise((resolve, reject) => {
      my.getAuthCode({
        scopes: ['auth_base','auth_ecard'],
        success: (res) => {
          resolve(res);
          wx2my.setStorageSync('_loginCode', res.authCode);
        },
        fail: res => {
          reject(res);
        }
      });
    });
  }

  getBaseUserInfo() {
    if (!this.baseUserInfo) {
      let baseUserInfo = wx2my.getStorageSync('_baseUserInfo');
      this.baseUserInfo = baseUserInfo;
    }

    return this.baseUserInfo;
  } // 通过unionId获取用户信息并更新token(防止token信息过期)


  getUserInfo() {
    const baseUserInfo = this.getBaseUserInfo();
    wx2my.showLoading({
      title: '正在加载...',
      icon: 'none'
    });
    console.log(JSON.stringify(baseUserInfo));
    return this.get('i-user/info', {
      unionId: baseUserInfo.unionId,
      minaOpenId: baseUserInfo.openId
    }).then(res => {
      console.log('i-user/info res is %o ', res);

      if (res.data.code === -10001) {
        this.showToast(`${res.data.message}`);
        return Promise.reject({
          state: -10001
        });
      } else if (res.data.data.isMember === '1') {
        let baseUserInfo = this.getBaseUserInfo();
        let newBaseUserInfo = {
          ...baseUserInfo,
          ...res.data.data
        };
        this.baseUserInfo = newBaseUserInfo;
        wx2my.setStorageSync('_baseUserInfo', newBaseUserInfo);

        wx2my.setStorageSync('token', res.data.data.token);
        this.startReport();
        return Promise.resolve({
          state: 1,
          info: res.data.data
        });
      } else {
        // this.openCard()
        return Promise.resolve({
          state: 2,
          info: res.data.data
        });
      }
    }).finally(() => {
      wx2my.hideLoading();
    });
  }

  getManageDate() {
    return manageDate;
  }

  selectAll(selector, options) {
    return new Promise((resolve, reject) => {
      wx2my.createSelectorQuery().selectAll('.page-body').fields(options, res => {
        resolve(res);
      }).exec();
    });
  }

  scrollOffset() {
    return new Promise((resolve, reject) => {
      wx2my.createSelectorQuery().selectViewport().scrollOffset(function(res) {
        resolve(res);
      }).exec();
    });
  }

  showModal(config = {}) {
    return new Promise((resolve, reject) => {
      wx2my.showModal({
        ...config,
        success: res => {
          if (res.confirm) {
            config.success ? config.success(res) : resolve(res);
          } else {
            reject(res);
          }
        },
        fail: err => {
          console.error(err);
        }
      });
    });
  }
  getAssPath() {
    const paths = pathData
    let pathArr = []
    for (const key in paths) {
      if (paths.hasOwnProperty(key)) {
        let pathObj = {}
        pathObj[key] = paths[key]
        pathArr.push(pathObj)
      }
    }
    return pathArr
  }

  trialList() {
    let localPath = this.getAssPath()
    my.showLoading({
      title: '加载中'
    })
    return this.get(`/member/trial/list`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          my.hideLoading()
          // 对应的path
          let currentPaths = [];
          localPath.forEach(item => {
            if (item.hasOwnProperty(data)) {
              currentPaths = item[data]
            }
          })
          return Promise.resolve({ currentPaths })
        }
      }
    })
  }


  getSystemInfo() {
    return new Promise((resolve, reject) => {
      wx2my.getSystemInfo({
        success: res => {
          resolve(res);
        },
        fail: res => {
          reject(res);
        },
        complete: res => { }
      });
    });
  } // handlerPage (page) {
  //   const AccreditWhitePages = [
  //     'pages/welcome/welcome'
  //   ] // 免授权页面白名单
  //   const _self = this
  //   const app = _self.getApp()
  //   const baseUserInfo = wx.getStorageSync('_baseUserInfo')
  //   if (baseUserInfo && baseUserInfo.isMember === '1') {
  //     app.globalData.openCard = true
  //   }
  //   return new Promise((resolve, reject) => {
  //     let accreditUserInfo = wx.getStorageSync('_accreditUserInfo')
  //     if (app.globalData.openCard && accreditUserInfo) {
  //       resolve()
  //       return false
  //     }
  //     if (AccreditWhitePages.indexOf(page.route) > -1) {
  //       resolve()
  //     } else if (accreditUserInfo) {
  //       getAppUserInfo().then(() => {
  //         if (this.lock) {
  //           return false
  //         }
  //         if ((!baseUserInfo || baseUserInfo.isMember !== '1') && needOpenCard()) {
  //           reject({ state: 1 })
  //           _self.lock = false
  //         } else {
  //           _self.lock = false
  //           resolve()
  //         }
  //       }).catch((res) => {
  //         reject()
  //       })
  //     } else {
  //       reject({ state: 1 })
  //     }
  //   }).catch((err) => {
  //     if (err && err.state === 1) {
  //       const modifyMottoRoute = [
  //         "pos/express/pages/orderList/orderList",
  //         "pos/express/pages/confirm/confirm"
  //       ]
  //       let router = '/pages/welcome/welcome';
  //       if (modifyMottoRoute.indexOf(page.route) > -1) {
  //         page.options.motto = 'express';
  //       }
  //       wxService.router('/pages/welcome/welcome').search({
  //         route: `${page.route}`,
  //         options: JSON.stringify(page.options)
  //       }).replace()
  //     }
  //     return Promise.reject()
  //   })
  // }
  // 设置异步的全局变量值


  initAppGlobalDataSync() {
    const app = this.getApp();

    if (!app.globalData.userInfo) {
      const userInfo = wx2my.getStorageSync('_userInfo');
      app.globalData.userInfo = userInfo;
    }

    if (!app.globalData.baseUserInfo) {
      const baseUserInfo = wx2my.getStorageSync('_baseUserInfo');
      app.globalData.baseUserInfo = baseUserInfo;
    }
  }

  page(config) {
    const _self = this;
    config.data.experAccessible;

    const CONFIG_PAPGE = {
      onLoad: function(...args) {
        const page = this;
        _self.initAppGlobalDataSync();
        watch.setWatcher(page);
        config.onLoad && config.onLoad.apply(page, args);
      },
      onShow: function(...args) {
        const page = this;
        _self.currentPage = page;
        config.onShow && config.onShow.apply(page, args);
        // 获取当前页
        let router = getCurrentRouter()
        const baseUserInfo = _self.getBaseUserInfo()
        if (baseUserInfo) {
          try {
            _self.trialList().then(res => {
              if (!res) return false
              const { currentPaths } = res
              if (currentPaths.indexOf(router.route) > -1 && isExperiencer) {
                this.setData({
                  experAccessible: true
                })
              } else {
                this.setData({
                  experAccessible: false
                })
              }
            })

          } catch (e) {console.log('e', e) }

        }
      },
      onReady: function(...args) {
        config.onReady && config.onReady.apply(this, args);
      },
      onHide: function(...args) {
        const page = this;
        config.onHide && config.onHide.apply(this, args);
      },
      onUnload: function(...args) {
        config.onUnload && config.onUnload.apply(this, args);
      },
      onPageScroll: function(...args) {
        config.onPageScroll && config.onPageScroll.apply(this, args);
      },
      onShareAppMessage: function(...args) {
        const page = this;
        const baseUserInfo = wx2my.getStorageSync('_baseUserInfo');
        let openId = '';

        if (baseUserInfo) {
          openId = baseUserInfo.openId;
        } // 处理页面分享


        if (config.onShareAppMessage) {
          try {
            let shareConfig = config.onShareAppMessage.apply(this, args);

            if (!shareConfig) { } else { }

            return shareConfig;
          } catch (e) {
            console.error(e);
          }
        }
      }
    };
    Page(Object.assign({}, config, CONFIG_PAPGE));
  }

  checkSession() {
    return new Promise((resolve, reject) => {
      wx.checkSession({
        success: data => {
          resolve(data);
        },
        fail: data => {
          reject(data);
        }
      });
    });
  }

  nextTick(fn) {
    if (wx2my.nextTick) {
      wx2my.nextTick(() => {
        fn();
      });
    } else {
      setTimeout(() => {
        fn();
      }, 0);
    }
  }

  showToast({
    title,
    icon = 'none'
  }) {
    wx2my.showToast({
      title,
      icon
    });
  }

  getConnectedWifi() {
    return new Promise((resolve, reject) => {
      wx.getConnectedWifi({
        success: res => {
          resolve(res);
        },
        fail: res => {
          reject(res);
        },
        complete: () => { }
      });
    });
  }

  navigateToMiniProgram(options) {
    const _self = this;

    const promise = new Promise((resolve, reject) => {
      if (!openCardLister) {
        openCardLister = cEvent.on('openCardSuccess', function(data) {
          openCardLister = null;
          resolve(data);
        });
      }

      this.showOpenCardModal({
        _self,
        options,
        reject
      });
    });
    return promise;
  }

  showOpenCardModal({
    options,
    _self,
    reject
  }) {
    if (this.showOpenCardModelLock) {
      return false;
    }

    this.showOpenCardModelLock = true; // 避免多次弹出开卡对话窗
    // 开卡

    wx2my.navigateToMiniProgram({
      appId: 'wxeb490c6f9b154ef9',
      // 固定为此 appid，不可改动
      extraData: options,
      // 包括 encrypt_card_id, outer_str, biz三个字段，须从 step3 中获得的链接中获取参数
      success: function(data) {
        console.log('navigateToMiniProgram success data is %o', data);
        _self.lock = false;
      },
      fail: function(data) {
        console.log('navigateToMiniProgram fail data is %o', data);
        this.router('/pages/userCenter/userCenter'); // this.router('/pages/welcome/welcome')

        _self.lock = false;
        reject(data);
      },

      complete() {
        _self.showOpenCardModelLock = false;
      }

    }); // wx.showModal({
    //   title: '请激活会员卡',
    //   content: '为了您更好的购物体验，请您先完善会员信息',
    //   showCancel: true,
    //   success: res => {
    //     if (res.confirm) {
    //       wx.navigateToMiniProgram({
    //         appId: 'wxeb490c6f9b154ef9', // 固定为此 appid，不可改动
    //         extraData: options, // 包括 encrypt_card_id, outer_str, biz三个字段，须从 step3 中获得的链接中获取参数
    //         success: function (data) {
    //           console.log('navigateToMiniProgram success data is %o', data)
    //           _self.lock = false
    //         },
    //         fail: function (data) {
    //           console.log('navigateToMiniProgram fail data is %o', data)
    //           _self.lock = false
    //           reject(data)
    //         }
    //       })
    //     } else {
    //       this.router('/pages/welcome/welcome')
    //       console.log('取消开卡跳转')
    //     }
    //   },
    //   complete: () => {
    //     this.showOpenCardModelLock = false
    //   }
    // })
  }
  /**
   * 开卡
  */
  openCard() {
    const baseUserInfo = wx2my.getStorageSync('_baseUserInfo') && wx2my.getStorageSync('_baseUserInfo').data;
    console.log('open', baseUserInfo)
    return new Promise((resolve, reject) => {
       if (baseUserInfo && baseUserInfo.memberActivateStatus ) {
        console.log('已开卡')
        wxService.openCardList()
        resolve(baseUserInfo)
      } else if (!baseUserInfo || !baseUserInfo.memberActivateStatus) {
        let url = decodeURIComponent(baseUserInfo.applyCardUrl)
        console.log('去开卡', url);
         return my.addCardAuth({
          url: `${url}`,
          success: (res) => {
            let alipayUserId = baseUserInfo && baseUserInfo.member && baseUserInfo.member.alipayUserId
            let requestId = res && res.result && res.result.request_id 
            // 支付宝激活会员卡 /alipay/cardOpen
            this.cardOpen(requestId,alipayUserId)
          },
          fail: (res) => {
             console.log('授权失败', res)
          // my.alert({ content: '授权失败' });
          },
        });
      } else {
        reject({
          state: 0
        });
      }
    }); 
  }
  // 支付宝激活会员卡
  cardOpen(requestId,alipayUserId) {
    this.post(`/member/alipay/cardOpen`, {
      requestId,
      alipayUserId
    }).then(res => {
      let baseUserInfo = wx2my.getStorageSync('_baseUserInfo').data;
      baseUserInfo.member = res.data.data
      baseUserInfo.memberActivateStatus = true
      wx2my.setStorageSync('_baseUserInfo', baseUserInfo);

      setTimeout(()=>{
        this.router('/pages/userCenter/userCenter'); 
      })
    }).catch(err => {
      console.log('err', err)
    });
  } 

  /**
   * 查看微信卡包中的卡券
   */
  openCardList() {
    // wechatCardId wechatCode
    my.openCardList();

    // const {
    //   wechatCardId,
    //   wechatCode
    // } = wx2my.getStorageSync('_baseUserInfo');
    // wx.openCard({
    //   cardList: [{
    //     cardId: wechatCardId,
    //     code: wechatCode
    //   }],

    //   success(res) {
    //     console.log('openCardList success', res);
    //   },

    //   fail(err) {
    //     console.log('openCardList fail data is %o', err);
    //   }

    // });
  }

  getRandom(num = 1) {
    let random = Math.random();

    if (random < 0.1) {
      random += 0.1;
    }

    let precision = 1;

    for (let i = 1; i <= num; i++) {
      precision = precision * 10;
    }

    return Math.floor(random * precision);
  } // 打开登录弹框


  openAuthModal() {
    return new Promise((resolve, reject) => {
      resolve({
        isAuthorization: true
      });
      return false;
    });
  }

}

const wxService = new WXService();
module.exports = wxService;