var Parse = getApp().Parse;
var company = getApp().globalData.company
const request = require("../../../utils/request");
const qiniuUploader = require("../../../utils/qiniuUploader");
//获取应用实例
const app = getApp()

/**
 * @class NovaAppAuth
 * @memberof module:components
 * @tutorial userauth
 * @desc 通用登录组件
 * # 登录组件相关数据表
 * - _User
 */
Page({
  data: {
    showModal: false,
    logo: "https://file-cloud.fmode.cn/MldI5PBNt7/20210928/g0k1jb034826.png",
    name: "未来商城",
    desc: "江西脑控科技有限公司是国内领先的IT技术企业。专注于互联网+服务，面向政府提供区块链、大数据、物联网、人工智能解决方案",
    wxModel: false,
    avatarUrl: '',
    avatar: '',
    nickname: ''
  },
  onLoad: async function (options) {
    console.log(company)
    let Company = new Parse.Query('Company')
    Company.equalTo("objectId", company)
    let currentCompany = await Company.first()
    if (currentCompany && currentCompany.id) {
      this.setData({
        logo: currentCompany.get('logo'),
        name: currentCompany.get('name'),
        desc: currentCompany.get('desc')
      })
    }
    this.getUptoken()
  },
  async getUptoken() {
    let res = await Parse.Cloud.run('qiniu_uptoken', {
      company: company
    })
    this.setData({
      uptokenURL: res.uptoken,
      domain: res.domain,
      uploadURL: res.zoneUrl
    })
  },
  onShow: function () {
    let userInfo = wx.getStorageSync('userLogin');
    if (userInfo != '') {
      wx.navigateBack();
    };
  },
  onReady: function () {},
  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: async (res) => {
        console.log(res);
        let myInfo = res.userInfo;
        wx.setStorageSync("userLogin", myInfo);
        let userInfo = wx.getStorageSync("userInfo");
        let appId = app.globalData.appid;
        let username, password;
        username = userInfo.openid; // openid作为用户名
        password = userInfo.openid.substr(username.length - 6, 6); // 后六位作为登录密码
        let query = new Parse.Query("_User");
        query.equalTo(`wxapp.${appId}.openid`, username);
        let current = await query.first();
        console.log(current, username, password);
        if (current) {
          let loginUser = await Parse.User.logIn(username, password);
          if (loginUser) {
            // 登陆成功则，更新用户资料，并返回用户信息
            if (!loginUser.get('avatar') || loginUser.get('nickname') == '微信用户') {
              await this.updataUserInfo(myInfo);
            }
            let u = Parse.User.current()
            if (!loginUser.get('mobile')) {
              this.showDialogBtn()
              return;
            } else if (u.get('nickname') == '微信用户' || u.get('nickname') == '' || !u.get('nickname')) {
              this.setData({
                wxModel: true
              })
              return
            }
            setTimeout(() => {
              this.backLoad()
            }, 500)
          }
        } else {
          let user = new Parse.User();
          user.set("username", username);
          user.set("password", password);
          let wxapp = {};
          wxapp[getApp().globalData.appid] = {
            openid: userInfo.openid,
            uniacid: userInfo.uniacid,
            uid: userInfo.id,
          };
          user.set("wxapp", wxapp);
          let signuser = await user.signUp();
          if (signuser) {
            this.updataUserInfo(myInfo);
            this.showDialogBtn()
          }
        }
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  showDialogBtn() {
    this.setData({
      showModal: true
    })
  },
  async getPhoneNumber(e) {
    let {
      code
    } = e.detail
    console.log(code);
    let phoneNumber = await request.getPhone(code)
    let user = Parse.User.current();
    if(phoneNumber) {
      user.set("mobile", phoneNumber);
      user.save().then(res => {})
    }
    if (!user.get('avatar') || user.get('nickname') == '微信用户' || !user.get('nickname')) {
      this.setData({
        showModal: false,
        wxModel: true
      })
      return
    }
    this.backLoad()
  },
  hideModal: function () {
    this.setData({
      showModal: false
    })
  },

  // 用户授权，更新用户信息
  async updataUserInfo(myInfo) {
    let user = Parse.User.current();
    let agentLevel = user.get("agentLevel")
    let invite = wx.getStorageSync('invite')
    user.set("nickname", myInfo.nickName);
    user.set("sex", myInfo.sex);
    user.set("city", myInfo.city);
    user.set("province", myInfo.province);
    user.set("country", myInfo.country);
    user.set("avatar", myInfo.avatarUrl);
    user.set("company", {
      __type: "Pointer",
      className: 'Company',
      objectId: company
    });
    if (invite) {
      let query = new Parse.Query("_User")
      let result = await query.get(invite)
      if (result && result.id && result.get("invite") == user.id) {
        console.error('邀请人不能是自己的下级')
        return
      }
      // 用户没有邀请人， 并且邀请人不是自己
      if (!user.get('invite') && user.id != invite) {
        user.set('invite', {
          __type: "Pointer",
          className: "_User",
          objectId: invite
        })
        user.set('agent', {
          __type: "Pointer",
          className: "_User",
          objectId: invite
        })
      }
    }
    if (agentLevel && agentLevel.id) {
      user.set("agentLevel", {
        __type: "Pointer",
        className: 'UserAgentLevel',
        objectId: agentLevel.id
      });
    }
    user.save().then(res => {
      this.setAccount(res.id)
    });
  },
  async setAccount(user) {
    let qeuryAccount = new Parse.Query("Account")
    qeuryAccount.equalTo("user", user)
    let accountInfo = await qeuryAccount.first()
    if (accountInfo && accountInfo.id) {
      return
    }
    let balance = await this.getalance(user)
    let Account = Parse.Object.extend("Account")
    let account = new Account()
    account.set("user", {
      __type: 'Pointer',
      className: "_User",
      objectId: user
    })
    account.set("company", {
      __type: "Pointer",
      className: 'Company',
      objectId: company
    });
    account.set("balance", balance)
    account.set("bonus", 0)
    account.set("credit", 0)
    account.save().then(Res => {
      return
    })
  },
  async getalance(uid) {
    let sql = `select sum("serviceTime") from "ActivityRegister" 
            where "user" = '${uid}' 
            and "isComplete" is true
            and "company" = 'pmAYN1NesE'
            `;
    let res = await request.customSQL(sql);
    return res[0].sum || 0
  },
  setInvite() {
    let invite = wx.getStorageSync('invite')
    if (invite) {
      // this.getInvite(Parse.User.current(),invite)
      let User = Parse.User.current()
      // console.log(User.get('invite'))
      // console.log(User.id)
      if (invite == User.id || User.get('invite')) {
        console.error('已有邀请人或邀请人不能为自己')
        return
      }
      if (!User.get('invite') && invite) {
        User.set('invite', {
          __type: 'Pointer',
          className: '_User',
          objectId: invite
        })
        User.save().then(res => {
          console.log(res)
        })
      }
    }
  },
  backLoad() {
    let pages = getCurrentPages();
    let beforePage = pages[pages.length - 2];
    let options = {
      isInit: true
    }
    beforePage.onLoad(options)
    wx.navigateBack({
      delta: 1,
    })
  },
  goBack: function () {
    wx.navigateBack({
      delta: 1,
    })
  },

  //手动获取微信头像
  onChooseAvatar(e) {
    console.log(e);
    let {
      avatarUrl
    } = e.detail
    console.log(avatarUrl);
    this.setData({
      avatarUrl
    })
  },

  //获取昵称
  onChangeName(e) {
    console.log('1111');
    console.log(e);
  },
  //确定头像昵称
  async onComplete() {
    let {
      nickname,
      avatarUrl
    } = this.data
    console.log(nickname, avatarUrl);
    if (!nickname || !avatarUrl) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none',
        image: '',
        duration: 1500,
        mask: false,
      });
      return
    }
    //关键注释： https://up-z2.qiniup.com 合法域名必须配置
    try {
      let avatar = await this.updataAvatar(avatarUrl)
      let user = Parse.User.current()
      user.set("avatar", avatar)
      user.set("nickname", nickname)
      user.save().then(res => {
        this.onClose()
        this.backLoad()
      })
    } catch (err) {
      console.warn('https://up-z2.qiniup.com 合法域名必须配置');
      console.log(err);
      this.onClose()
      this.backLoad()
    }
  },
  //关闭弹窗
  onClose() {
    this.setData({
      wxModel: false
    })
  },

  //上传头像
  updataAvatar(url) {
    let that = this;
    return new Promise((resolve, rejcet) => {
      qiniuUploader.upload(
        url,
        async (res) => {
            let img = res.imageURL;
            resolve(img)
          },
          (error) => {
            console.log("error: " + error);
            resolve(false)
          }, {
            region: "SCN",
            uploadURL: that.data.uploadURL,
            domain: that.data.domain,
            uptoken: that.data.uptokenURL,
          }
      );
    })
  },
})