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

@Injectable({
  providedIn: 'root',
})
export class AccountService {
  company: string = '';
  wxAppId = '';
  wxpayEnabled: boolean = false;
  appid: string = localStorage.getItem('WECHAT_APP_ID') || 'wx86a6c35812a41d41';
  shareInfo: any;
  userVip:any //会员权益
  constructor(
    public toast: ToastController,
    private authServ: AuthService,
    private http: HttpClient,
    private httpSver: HttpService
  ) {
    this.company = this.authServ.company;
    this.getUserOpenid();
    this.getVip()
  }

  /* 如果是微信内置浏览器，获取登录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: 'hey聊', // 分享标题
          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(() => {});
      });
  }
  setTradeNo() {
    let now = new Date();
    let tradeNo =
      'C' +
      String(now.getFullYear()) +
      (now.getMonth() + 1) +
      now.getDate() +
      now.getHours() +
      now.getMinutes() +
      now.getSeconds() +
      now.getMilliseconds() +
      Math.floor(Math.random() * 10000);
    return tradeNo;
  }

  // 存支付记录
  async setOrder(params: {
    type: string;
    gid: string;
    price: number;
    total_fee: number;
    tradeNo: string;
    out_trade_no: string;
    payType: string;
    code?: string;
  }): Promise<any> {
    let url = 'https://server.fmode.cn/api/apig/created-order';
    return new Promise((res, rej) => {
      this.http
        .post(url, {
          fcompany: this.company,
          uid: Parse.User.current()?.id,
          type: params.type,
          gid: params.gid,
          invite: Parse.User.current()?.get('invite')?.id,
          params: params,
        })
        .subscribe(
          (data: any) => {
            //console.log(data);
            res(data.data);
          },
          (err) => {
            rej(err);
          }
        );
    });
  }
  //充值记录
  async creatdRechargeLog(param: {
    tradeNo: string;
    payType: string;
    price: number;
    credit:number
  }) {
    const user = Parse.User.current()!;
    //查询账户
    let Account = new Parse.Query('Account');
    Account.equalTo('company', this.company);
    Account.equalTo('user', user?.id);
    Account.select('objectId');
    let account = await Account.first();
    if (!account?.id) {
      account = await this.createdAccount(user.id);
    }
    let query = new Parse.Query('AccountLog');
    query.equalTo('orderNumber', param.tradeNo);
    query.equalTo('targetAccount', account?.id);
    query.notEqualTo('isVerified', true);
    query.notEqualTo('isDeleted', true);
    let alog = await query.first();
    if (alog?.id) {
      return alog;
    }
    let parseAccountLog = Parse.Object.extend('AccountLog');
    let accountLog = new parseAccountLog();
    accountLog.set('isVerified', false);
    accountLog.set('user', {
      __type: 'Pointer',
      className: '_User',
      objectId: user.id,
    });
    accountLog.set('company', {
      __type: 'Pointer',
      className: 'Company',
      objectId: this.company,
    });
    accountLog.set('targetAccount', {
      __type: 'Pointer',
      className: 'Account',
      objectId: account?.id,
    });
    accountLog.set('fromName', 'system');
    accountLog.set('fromAccountName', 'system');
    accountLog.set('orderNumber', param.tradeNo);
    accountLog.set('desc', `${param.payType}充值${param.price}`);
    accountLog.set('assetType', 'balance');
    accountLog.set('orderType', `${param.payType}-recharge`);
    accountLog.set('payType', param.payType);
    accountLog.set('assetCount', param.credit);
    accountLog.set('serviceFee', param.price)
    return await accountLog.save();
  }
  // 生成一条待支付AccountLog记录
  async saveAccountLog(param: {
    price: number;
    tradeNo: string;
    orderType: string;
    payType: string;
    orderId?: string;
  }) {
    // 查询当前订单是否已有支付记录
    const user = Parse.User.current()!;
    //查询账户
    let Account = new Parse.Query('Account');
    Account.equalTo('company', this.company);
    Account.equalTo('user', user?.id);
    Account.select('objectId');
    let account = await Account.first();
    if (!account?.id) {
      account = await this.createdAccount(user.id);
    }
    let Query = new Parse.Query('AccountLog');
    Query.equalTo('company', this.company);
    Query.equalTo('user', user.id);
    Query.equalTo('orderNumber', param.tradeNo);
    Query.equalTo('fromAccount', account.id);
    Query.equalTo('payType', param.payType);
    let result = await Query.first();
    if (result && result.id) {
      return result;
    }
    let AccountLog = Parse.Object.extend('AccountLog');
    let tool = new AccountLog();
    tool.set('fromAccount', {
      __type: 'Pointer',
      className: 'Account',
      objectId: account.id,
    });
    tool.set('user', {
      __type: 'Pointer',
      className: '_User',
      objectId: user.id,
    });
    param.orderId && tool.set('orderId', param.orderId);
    tool.set('company', {
      __type: 'Pointer',
      className: 'Company',
      objectId: this.company,
    });
    tool.set('orderType', param.orderType);
    tool.set('isVerified', false);
    tool.set(
      'fromName',
      user?.get('nickname') ? user.get('nickname') : user?.get('mobile')
    );
    tool.set('orderNumber', param.tradeNo);
    tool.set('targetName', 'system');
    tool.set('payType', param.payType);
    tool.set('assetCount', param.price);
    return await tool.save();
  }
  /* 激活Account */
  async createdAccount(uid: string): Promise<Parse.Object> {
    let Account = new Parse.Query('Account');
    Account.equalTo('company', this.company);
    Account.equalTo('user', uid);
    let account: any = await Account.first();
    if (!account?.id) {
      let obj = Parse.Object.extend('Account');
      account = new obj();
      account?.set('user', {
        __type: 'Pointer',
        className: '_User',
        objectId: uid,
      });
      account?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.company,
      });
      account?.set('balance', 0);
      account = await account?.save();
    }
    return account;
  }

  async updateAccountLog(info: object, orderid: string) {
    let url = 'https://server.fmode.cn/api/apig/saveAccountLog';
    return new Promise((res, rej) => {
      this.http
        .post(url, {
          company: this.company,
          uid: Parse.User.current()?.id,
          orderid: orderid,
          info: info,
        })
        .subscribe(
          (data: any) => {
            console.log(data);
            res(true);
          },
          async (err) => {
            console.warn(err);
            const toast = await this.toast.create({
              message: '支付成功，订单记录异常',
              color: 'warning',
              duration: 1500,
            });
            toast.present();
            rej();
          }
        );
    });
  }

  async updateRecharge(accountLog: Parse.Object): Promise<Parse.Object> {
    accountLog?.set('isVerified', true);
    await accountLog?.save();
    return accountLog;
  }

  async getVip(uid?:string):Promise<any>{
    const url = 'https://server.fmode.cn/api/user/vip'
    let data = await this.httpSver.httpRequst(url,{uid: uid ?? Parse.User.current()?.id},'POST');
    if(!uid) this.userVip = data.data
    return data.data
  }
}
