<template>
  <div>
    <router-view />
  </div>
</template>

<script>
import Vue from "vue";
import ErrorCode from "./assets/js/errorCode.js";
import utils from "./assets/js/utils";
import _def from "./assets/js/define";
import _apiHelper from "./assets/js/apiHelper.js";
import _appConf from "./app.conf";
import _gis from "./assets/js/location-common.js";
import { constants } from "fs";
import wx from "weixin-js-sdk";
import VConsole from "vconsole";
import apiHelper from "./assets/js/apiHelper.js";

export default {
  name: "App",
  data: function() {
    return {
      jsSDKReady: false // js sdk是否已经初始化完成
    };
  },
  beforeCreate() {
    // 进入页面后先整理一些参数
    var that = this;
    let sup8 = {
      _def: _def,
      _appConf: _appConf,
      env: _def.env.run,
      permissionLevel: 1,
      urlparams: utils.parseUrl(),
      $utils: utils,
      queryEventId: undefined, // 解码、查防伪要使用同一个eventid 用于记日志
      UA: { ua: navigator.userAgent, geo: {} }
    };
    sup8.role = _.find(sup8._def.role, {
      code: sup8.urlparams.role
    }) || {
      permissionLevel: 1
    };

    // //获取用户设备、地理信息
    // that.sup8.UA = {
    //   ua: navigator.userAgent,
    //   geo: {}
    // };

    utils.setAppKey();

    // 系统产生一些上下文参数，所有组件都可以使用
    sup8.context = sup8.$utils.updateContext(sup8.context, sup8.urlparams);

    Vue.prototype.sup8 = sup8;
  },
  methods: {
    // 跳转到错误页
    gotoErrorPage(error, errorMsg) {
      this.sup8.gotoError = true;
      this.sup8.msg = errorMsg;
      this.sup8.error = error;
      this.$router.push("/error");
    },

    /**
     *过滤出基础组件，只要当前模板包含的
     */
    filterComponentList(pages, baseCompList) {
      var that = this;
      let compList = [];

      if (!pages || pages.length <= 0) {
        return compList;
      }

      // 当前模板中包含的基础组件编号
      let baseCompIdsInPages = [];
      pages.forEach(a => {
        a.components.forEach(v => {
          if (!_.includes(baseCompIdsInPages, v.baseCompId)) {
            baseCompIdsInPages.push(v.baseCompId);
            // debugger;

            compList.push({
              id: v.baseCompId,
              SrcPath: v.srcPath,
              bundleName: v.bundleName || "",
              ver: v.ver || "",
              componentViewName: v.componentViewName || "",
              componentPropViewName: v.componentPropViewName || ""
            });
          }
        });
      });

      //   baseCompIdsInPages = _.uniq(baseCompIdsInPages);

      //   _.forEach(baseCompList, function(p) {
      //     if (_.includes(baseCompIdsInPages, p.id)) {
      //       compList.push(p);
      //     }
      //   });
      return compList;
    },

    /**
     * 获取产品信息
     * @param {list} compList 需要注册的组件列表
     * @param {boolean} importPropView 是不是要注册属性视图组件
     */
    registComponent(compList, importPropView) {
      let that = this;

      let defaultCompList = [
        { name: "导航栏", componentViewName: "CompCell", bundleName: null }
      ];
      compList = _.concat(compList, defaultCompList);

      _.forEach(compList, function(ch, key) {
        // debugger;
        var viewDir = "";
        if (ch.SrcPath) {
          viewDir = ch.SrcPath;
        } else if (!ch.bundleName) {
          viewDir = that.sup8._appConf.systemComponentsPath;
        } else {
          viewDir =
            that.sup8._appConf.installComponentsPath +
            ch.bundleName +
            "_" +
            ch.ver +
            "/components/";
        }
        var compViewPath = viewDir + ch.componentViewName;
        var componentViewName = ch.componentViewName + (ch.id || "");

        // console.log(compViewPath, componentViewName);
        Vue.component(componentViewName, () => import(`${compViewPath}`));

        if (!!importPropView && !!ch.componentPropViewName) {
          let compPropsName = ch.componentPropViewName + (ch.id || "");
          let compPropsPath = viewDir + ch.componentPropViewName;
          Vue.component(compPropsName, () => import(`${compPropsPath}`));
        }
      });
    },

    // 使用百度地图获取地理位置信息
    getGeoByBaiduMap(successCb, errorCb) {
      let that = this;

      try {
        let gis = new _gis();
        gis.getGeo(function(res) {
          that.sup8.UA.geo = res;
          let channel = res.latitude + "," + res.longitude;
          sessionStorage.setItem("gps", channel);
          sessionStorage.setItem("geo", JSON.stringify(res));
          that.sup8.context.channel = channel;
          that.sup8.context.geo = res;

          console.log("地理位置", that.sup8.context.geo);
          !!successCb && successCb();
        });
      } catch (error) {
        !!errorCb && errorCb();
      }
    },

    // 使用微信SDK获取地理位置信息
    getGeoByWX(successCb, errorCb) {
      let that = this;
      wx.getLocation({
        type: "wgs84", // 默认为wgs84的gps坐标
        success: function(res) {
          console.log("WX getLocation success:", res);
          var latitude = res.latitude; // 纬度
          var longitude = res.longitude; // 经度
          that.wgs84TransformBM(longitude, latitude, successCb, errorCb);
        },
        cancel: function(e) {
          console.log("WX getLocation 拒绝:", e);
          that.getGeoByBaiduMap(successCb, errorCb);
        },
        fail: function(e) {
          console.log("WX getLocation 失败:", e);
          that.getGeoByBaiduMap(successCb, errorCb);
        }
      });
    },

    // 配置jssdk
    initWxJsSdk(eno, successCb, errorCb) {
      if (this.jsSDKReady) {
        !!successCb && successCb();
        return;
      }

      let that = this;
      let defaultEno = "000000000000";

      _apiHelper.getWxJsSdkConfig(
        eno,
        location.href.split("#")[0],
        1,
        function(res) {
          if (!res || !res.flag || !res.data) {
            if (eno == defaultEno) {
              !!errorCb && errorCb();
            } else {
              that.initWxJsSdk(defaultEno, successCb, errorCb);
            }
          } else {
            res = res.data;
            that.sup8.context.wx_user = res;
            wx.config({
              debug: false, // 开启调试模式,
              appId: res.appId, // 必填，企业号的唯一标识，此处填写企业号corpid
              timestamp: res.timestamp, // 必填，生成签名的时间戳
              nonceStr: res.nonceStr, // 必填，生成签名的随机串
              signature: res.signature, // 必填，签名，见附录1
              jsApiList: ["scanQRCode", "getLocation", "closeWindow"] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });
            wx.ready(function() {
              console.log("wx.ready");
              that.jsSDKReady = true;
              !!successCb && successCb();
              // that.getGeoByWX(successCb);
            });
            wx.error(function(e) {
              console.log("wx.error", e);
              !!errorCb && errorCb();
              // that.getGeoByBaiduMap(successCb);
            });
          }
        },
        function(e) {
          // that.getGeoByBaiduMap(successCb);
          !!errorCb && errorCb();
        }
      );
    },

    // 获取位置信息
    getGeo(successCb, errorCb) {
      let that = this;
      if (sessionStorage.geo) {
        try {
          that.sup8.context.geo = JSON.parse(sessionStorage.geo);
          that.sup8.context.channel =
            that.sup8.context.geo.latitude +
            "," +
            that.sup8.context.geo.longitude;
          sessionStorage.gps = that.sup8.context.gps =
            that.sup8.context.channel;

          !!successCb && successCb();
          return;
        } catch (error) {}
      }

      // 如果是微信进入，获取定位权限
      if (that.sup8.$utils.isWechat() && !that.sup8.$utils.isWechatdevtools()) {
        const eNo = that.sup8.context.eno || defaultEno;
        this.initWxJsSdk(eNo, function() {
          that.getGeoByWX(successCb, errorCb);
        });
      } else {
        // 获取定位信息,不是微信使用百度定位
        that.getGeoByBaiduMap(successCb, errorCb);
      }
    },

    // 超8平台：获取微信用户信息
    getWxUserInfo(ok_cb, err_cb) {
      if (sessionStorage.wxUser) {
        this.sup8.context.wxUser = JSON.parse(sessionStorage.wxUser);
        ok_cb && ok_cb();
        return;
      }

      if (this.sup8.urlparams.userInfo) {
        let wxUser = JSON.parse(this.sup8.urlparams.userInfo);
        // if (wxUser.IsSuccess && wxUser.ResponseData) {
        //   wxUser = wxUser.ResponseData;
        sessionStorage.setItem("wxUser", JSON.stringify(wxUser));
        this.sup8.context.wxUser = wxUser;
        ok_cb && ok_cb();
        // } else {
        //   this.gotoErrorPage(ErrorCode.wxOauthError);
        // }
      } else {
        let url = encodeURIComponent(location.href);
        let eno = this.sup8.context.eno;
        let scopeType = "1";
        let wechatHost = "";

        location.href = `${_appConf.baseConfig.wechat}/OAuth/GetOAuth?enterpriseNo=${eno}&scopeType=${scopeType}&redirectUrl=${url}`;
      }
    },

    // CCN平台：获取微信用户信息
    getWxUserInfoByCCN(ok_cb, err_cb) {
      //   apiHelper.CCNWechatPlatform.getAuthorizeInfo(
      //     "63da3f54aaf40ca5e7a991066a64037006574340"
      //   );
      //   return;
      let that = this;
      if (sessionStorage.wxUser) {
        this.sup8.context.wxUser = JSON.parse(sessionStorage.wxUser);
        ok_cb && ok_cb();
        return;
      }

      if (this.sup8.urlparams.authorizeCode) {
        apiHelper.getAuthorizeInfo(
          this.sup8.urlparams.authorizeCode,
          function(res) {
            // 授权成功
            if (res.ret) {
              that.gotoErrorPage(ErrorCode.wxOauthError);
              return;
            }
            sessionStorage.wxUser = JSON.stringify(res);
            that.sup8.context.wxUser = res;
            ok_cb && ok_cb();
          },
          function(err) {
            // 授权失败
            that.gotoErrorPage(ErrorCode.wxOauthError);
          }
        );
      } else {
        apiHelper.getCCNToken(
          function(token) {
            let redirectUrl = encodeURIComponent(location.href);
            if (that.sup8.h5Template.WeChatAuthorized == 0) {
              // 隐式授权
              location.href = `http://auth.weixin.zhsh.co/api/wechat/authorize-code?token=${token}&redirectUrl=${redirectUrl}&scopes=snsapi_base`;
            } else {
              // 显示授权
              location.href = `http://auth.weixin.zhsh.co/api/wechat/authorize-code?token=${token}&redirectUrl=${redirectUrl}`;
            }
            // location.href = `http://auth.weixin.zhsh.co/api/wechat/authorize-code?token=${token}&redirectUrl=${redirectUrl}`;
          },
          function(err) {
            that.gotoErrorPage(ErrorCode.wxOauthError);
          }
        );
      }
    },

    /**
     * 将微信定位的wgs84坐标转为百度地图坐标，并获取地址详细信息
     * @param lng {string} 经度
     * @param lat {string} 纬度
     * @param cb {function} 成功回调
     */
    wgs84TransformBM(lng, lat, successCb, errorCb) {
      var that = this;
      var ggPoint = new BMap.Point(lng, lat);
      var convertor = new BMap.Convertor();
      var pointArr = [];
      pointArr.push(ggPoint);
      convertor.translate(pointArr, 1, 5, data => {
        if (data.status === 0) {
          $.ajax({
            url: `http://api.map.baidu.com/geocoder/v2/?ak=DAkHeza7GMvAuA5FL2p8GAZxC84WoMLh&location=${data.points[0].lat},${data.points[0].lng}&output=json&pois=1`,
            dataType: "jsonp",
            callback: "BMap._rd._cbk43398",
            success: function(res) {
              console.log("百度经纬度转地址", res);
              if (res.status == 0) {
                let mapInfo = {
                  latitude: data.points[0].lat,
                  longitude: data.points[0].lng,
                  map: "baidu",
                  addressComponent: res.result.addressComponent
                };

                let channel = data.points[0].lat + "," + data.points[0].lng;
                sessionStorage.setItem("gps", channel);
                that.sup8.context.channel = channel;
                that.sup8.context.geo = mapInfo;
                sessionStorage.setItem("geo", JSON.stringify(mapInfo));
                !!successCb && successCb();
              } else {
                console.log("[失败]百度经纬度转地址", res);
                !!errorCb && errorCb();
              }
            },
            error: function(e) {
              console.log("[失败]百度经纬度转地址", e);
              !!errorCb && errorCb();
            }
          });
        }
      });
    }
  },

  created() {},
  mounted() {
    let debug = localStorage.getItem("debug");
    if (
      debug == 1 ||
      (_appConf &&
        _appConf.baseConfig.env &&
        _.includes([1, 2, 3, 4], _appConf.baseConfig.env))
    ) {
      var vConsole = new VConsole();
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
