import { Injectable } from '@angular/core';
import Parse from 'parse';
import { HttpClient } from '@angular/common/http';
import { AuthService } from './auth.service';
declare var wx: any;

@Injectable({
  providedIn: 'root',
})
export class AccountService {
  company: string = '';
  wxAppId = '';
  wxpayEnabled: boolean = false;
  appid: string = localStorage.getItem('WECHAT_APP_ID') || 'wxb4193c93ae9aa696';
  shareInfo: any;
  constructor(private authServ: AuthService, private http: HttpClient) {
    this.company = this.authServ.company;
    this.getUserOpenid();
  }

  /* 如果是微信内置浏览器，获取登录code */
  async getUserOpenid() {
    let ua = navigator.userAgent.toLowerCase();
    let isWeixin = ua.indexOf('micromessenger') != -1;
    let code = this.getQueryStringByName('code');
    let openid = localStorage.getItem('openid');
    if (!openid) {
      if (!Parse.User.current()) return;
      let wechat = Parse.User.current()?.get('wechat');
      openid = wechat?.[this.appid]?.openid;
      if (isWeixin) {
        if (!code) {
          this.authWechat();
        } else {
          await this.getwechat(code);
        }
      }
    }
  }
  authWechat(url: string = '/account/billing') {
    if (!localStorage.getItem('openid')) {
      // let REDIRECT_URI = "https://ai.fmode.cn" + url;
      let REDIRECT_URI = window.location.href;
      REDIRECT_URI = encodeURIComponent(REDIRECT_URI);
      // console.log(REDIRECT_URI);
      // console.log(
      //   "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
      //     this.appid +
      //     "&redirect_uri=" +
      //     REDIRECT_URI +
      //     "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
      // );
      window.location.href =
        'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
        this.appid +
        '&redirect_uri=' +
        REDIRECT_URI +
        '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
      return;
    }
  }
  //根据QueryString参数名称获取值
  getQueryStringByName(name: string) {
    let result = location.search.match(
      new RegExp('[?&]' + name + '=([^&]+)', 'i')
    );
    if (result == null || result.length < 1) {
      return '';
    }
    return result[1];
  }
  async getwechat(
    code: string,
    url: string = '/account/billing'
  ): Promise<boolean> {
    return new Promise(async (resolve, reject) => {
      this.http
        .post(`https://server.fmode.cn/api/wechat/get_wx`, {
          company: this.company,
          code: code,
        })
        .subscribe(
          async (res: any) => {
            console.log(res);
            if (res && res.code == 200 && res.data.openid) {
              let openid = res.data.openid;
              // localStorage.setItem('authData', JSON.stringify(res.data))
              localStorage.setItem('openid', openid);
              localStorage.removeItem('code');
              let wxopts: any = {};
              (wxopts[this.appid] = {
                openid: openid,
              }),
                Parse.User.current()?.set('wechat', wxopts);
              await Parse.User.current()?.save();
              resolve(true);
            }
          },
          async (err) => {
            console.log('Error updating items', err);
            this.authWechat(url);
            reject(false);
          }
        );
    });
  }
  /* 获取微信签名 */
  getWXSignPackageInWechat() {
    let params = {
      company: this.company,
      href: encodeURIComponent(location.href.split('?')[0]),
    };
    this.http
      .post(`https://server.fmode.cn/api/wechat/getconfig`, params)
      .subscribe((response) => {
        // 返回的签名信息
        let res: any = response;
        const signPackage = res.data;
        this.wxAppId = signPackage.appid;
        this.wxpayEnabled = true;

        wx.config({
          debug: false, // 开启调试模式
          appId: signPackage.appid, // 必填，公众号的唯一标识
          timestamp: signPackage.timestamp, // 必填，生成签名的时间戳
          nonceStr: signPackage.nonceStr, // 必填，生成签名的随机串
          signature: signPackage.signature, // 必填，签名，见附录1
          jsApiList: [
            'chooseWXPay', // JSAPI微信支付
            'onMenuShareTimeline', //分享到微信朋友圈
            'onMenuShareAppMessage', //分享给微信朋友
            'onMenuShareQQ', //分享到QQ
            'onMenuShareQZone', //分享到QQ空间
            'updateAppMessageShareData', //分享到微信及QQ（新接口）
            'updateTimelineShareData', //分享到朋友圈”及“分享到QQ空间（新接口
          ], // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });

        let url = 'https://ai.fmode.cn';
        let pathname = location.pathname;
        url + pathname + '?invite=' + Parse.User.current()?.id;
        let shareInfo = this.shareInfo || {
          title: '爱聊', // 分享标题
          desc: '全新互动1：1视频直播娱乐体验', // 分享描述
          link: url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          type: 'link', //分享类型,music、video或link，不填默认为link
          imgUrl:
            'https://file-cloud.fmode.cn/E4KpGvTEto/20230822/3mkf41033623275.png', // 分享图标
          success: function () {
            // 设置成功
            console.log('分享成功');
          },
          error: function () {
            console.log('分享失败');
          },
          cancel: function () {
            console.log('取消分享');
          },
        };

        wx.ready(() => {
          wx.updateAppMessageShareData(shareInfo); //分享到微信好友或者qq好友
          wx.updateTimelineShareData(shareInfo); //分享到朋友圈或者qq空间
        });
        wx.error(() => {});
      });
  }

  async saveAccountLog(
    info: object,
    orderid: string,
    company: string,
    message: any
  ) {
    let url = 'https://test.fmode.cn/api/apig/saveAccountLog';
    return new Promise((res, rej) => {
      this.http
        .post(url, {
          company: company,
          uid: Parse.User.current()?.id,
          orderid: orderid,
          info: info,
        })
        .subscribe(
          (data: any) => {
            console.log(data);
            res(true);
          },
          (err) => {
            console.warn(err);
            message && message.error('请求超时，请稍后再试');
            rej();
          }
        );
    });
  }
  setTradeNo() {
    let now = new Date();
    let tradeNo =
      'C' +
      this.company +
      String(now.getFullYear()) +
      (now.getMonth() + 1) +
      now.getDate() +
      now.getHours() +
      now.getMinutes() +
      now.getSeconds() +
      now.getMilliseconds();
    return tradeNo;
  }

  // 存支付记录
  async setOrder(type: string, params: any, message?: any): Promise<any> {
    let url = 'https://server.fmode.cn/api/apig/created-order';
    return new Promise((res, rej) => {
      this.http
        .post(url, {
          fcompany: this.company,
          type: type,
          gid: params.id,
          uid: Parse.User.current()?.id,
          params: params,
        })
        .subscribe(
          (data: any) => {
            //console.log(data);
            res(data.data);
          },
          (err) => {
            message?.error('网络错误,订单创建失败');
            rej(err);
          }
        );
    });
  }
}
