let Parse = getApp().Parse;
let company = getApp().globalData.company
const request = require("../../utils/request");
const qiniuUploader = require("../../utils/qiniuUploader");
//获取应用实例
const app = getApp()
const real = require('../../utils/real')
var timer
/**
 * @class NovaAppAuth
 * @memberof module:components
 * @tutorial userauth
 * @desc 通用登录组件
 * # 登录组件相关数据表
 * - _User
 */
Page({
  data: {
    phoneModal: false, //短信验证码登录弹窗
    logo: "https://file-cloud.fmode.cn/MldI5PBNt7/20210928/g0k1jb034826.png",
    name: "未来商城",
    desc: "江西脑控科技有限公司是国内领先的IT技术企业。专注于互联网+服务，面向政府提供区块链、大数据、物联网、人工智能解决方案",
    wxModel: false,
    avatarUrl: '',
    avatar: '',
    nickname: '',
    check: false,
    mobile: '', //手机号
    verilyCode: '', //验证码
    s: 0, //获取验证码倒计时 秒/s
    countDown: false
  },
  onLoad: async function (options) {
    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()
    this.getAgreement() //用户协议
  },
  async getUptoken() {
    let res = await Parse.Cloud.run('qiniu_uptoken', {
      company: company
    })
    this.setData({
      uptokenURL: res.uptoken,
      domain: res.domain,
      uploadURL: res.zoneUrl
    })
  },
  async getAgreement() {
    let query = new Parse.Query('ContractAgreement')
    query.equalTo('type', 'wxapp')
    query.equalTo('company', company)
    query.select('title', 'content')
    let res = await query.first()
    if (res?.id) {
      this.setData({
        agreement: res.toJSON()
      })
    }
  },
  /* 是否同意授权协议 */
  getAgreementAuth() {
    if (!this.data.check && this.data.agreement) {
      wx.showModal({
        title: '提示',
        content: `请您仔细阅读并充分理解相关条款，点击同意即代表已阅读并同意《${this.data.agreement.title || '用户隐私协议'}》`,
        showCancel: true,
        cancelText: '取消',
        cancelColor: '#000000',
        confirmText: '同意',
        confirmColor: '#3CC51F',
        success: (result) => {
          if (result.confirm) {
            this.setData({
              check: true,
            })
            // this.getUserProfile()
          }
        },
        fail: () => { },
        complete: () => { }
      });
      return
    }
    // this.getUserProfile()
    return true
  },
  /* 判断是否绑定手机号 */
  async getUserProfile() {
    if (!Parse.User.current()?.id) {
      await getApp().checkAuth(true)
    }
    let currentUser = Parse.User.current()
    /* 如果手机号存在，已注册过判断是否上传过头像昵称信息 */
    if (currentUser?.get('mobile')) {
      wx.setStorageSync("userLogin", currentUser.id);
      if (currentUser.get('nickname') == '微信用户' || currentUser.get('nickname') == '' || !currentUser.get('nickname')) {
        this.setData({
          wxModel: true
        })
        return
      }
      this.backLoad()
      return
    }
    return true
  },
  /* 短信验证码登录弹窗 */
  async showDialogBtn() {
    let auth = this.getAgreementAuth()
    if (!auth) return
    let userProfile = await this.getUserProfile()
    if (!userProfile) return
    this.setData({
      phoneModal: true
    })
  },
  async getPhoneNumber(e) {
    let auth = this.getAgreementAuth()
    if (!auth) return
    let userProfile = await this.getUserProfile()
    if (!userProfile) return
    let {
      code
    } = e.detail
    console.log(code);
    let phoneNumber = await request.getPhone(code)
    if(phoneNumber) this.authMobileUser(phoneNumber)
  },

  //合并User与绑定手机号逻辑
  async authMobileUser(mobile) {
    let currentUser = Parse.User.current()
    let queryMobUser = new Parse.Query('_User')
    queryMobUser.equalTo('mobile', mobile)
    queryMobUser.equalTo('company', company)
    queryMobUser.notEqualTo('type', 'admin')
    queryMobUser.notEqualTo('isDeleted', true)
    // queryMobUser.exists(`wxapp.${getApp().globalData.appid}`)
    let resMobUser = await queryMobUser.first()
    if (resMobUser?.id) {
      //请求User合并API，获取token重新登录，再更新昵称头像信息等
      let token = await this.getUpdateUserToken(currentUser.id, resMobUser.id)
      console.log(token);
      if (token) {
        Parse.User.become(token).then(async user => {
          // let user = Parse.User.current();
          wx.setStorageSync("userLogin", user.id);
          if (!user.get('avatar') || user.get('nickname') == '微信用户' || !user.get('nickname')) {
            this.setData({
              phoneModal: false,
              wxModel: true
            })
            return
          }
          this.backLoad()
          return
        })
          .catch(err => {
            console.log('登录失败：', err);
            wx.setStorageSync("sessionToken", null);
            wx.showModal({
              title: '提示',
              content: '登录信息过期，请退出重新进入小程序',
              showCancel: false,
              cancelText: '取消',
              cancelColor: '#000000',
              confirmText: '确定',
              confirmColor: '#3CC51F',
              success: (result) => {
                if (result.confirm) {
                  wx.exitMiniProgram()
                }
              },
            });
            return
          })
        return
      }
      return
    }
    currentUser.set('mobile', mobile)
    await currentUser.save()
    if (!currentUser.get('avatar') || currentUser.get('nickname') == '微信用户' || !currentUser.get('nickname')) {
      this.setData({
        phoneModal: false,
        wxModel: true
      })
      return
    }
    this.backLoad()
    return
  },
  async getUpdateUserToken(oldUser, newUserId) {
    return new Promise((resolve, reject) => {
      wx.login({
        success: function (res) {
          let parms = {
            oldUserId: oldUser,
            newUserId: newUserId,
            appId: getApp().globalData.appid,
            code: res.code,
            companyId: company,
            appType: getApp().globalData.appType || ''
          }
          if (res.code) {
            let url = 'https://server.fmode.cn/api/wxapp/combine/user'
            wx.request({
              url: url,
              data: parms,
              header: { 'content-type': 'application/json' },
              method: 'POST',
              async success(res) {
                console.log(res);
                let data = res.data
                if (data.code == 200) {
                  wx.setStorageSync("sessionToken", data.data.token);
                  resolve(data.data.token)
                } else {
                  console.log(data?.mess);
                  wx.showModal({
                    title: '提示',
                    content: data?.mess,
                    showCancel: false,
                    cancelText: '取消',
                    cancelColor: '#000000',
                    confirmText: '确定',
                    confirmColor: '#3CC51F',
                    success: (result) => {
                      if (result.confirm) {
                      }
                    },
                    fail: () => { },
                    complete: () => { }
                  });
                  resolve()
                }
              },
            });
          }
        },
        fail: function (err) {
          wx.showModal({
            title: '提示',
            content: '登录超时，请稍后重试',
            showCancel: false,
            cancelText: '取消',
            cancelColor: '#000000',
            confirmText: '确定',
            confirmColor: '#3CC51F',
            success: (result) => {
              if (result.confirm) {
              }
            },
            fail: () => { },
            complete: () => { }
          });
          console.warn('小程序wx.login失败');
          resolve()
        }
      });
    })
  },

  //获取验证码
  async getPhoneCode() {
    let { mobile, s, countDown } = this.data
    if (!real.isPoneAvailable(mobile)) {
      wx.showToast({
        title: '手机号格式有误',
        icon: 'error',
        duration: 1500,
        mask: false,
      });
      return
    }
    if(countDown || s > 0) return
    this.setData({
      countDown:true
    })
    let parsm = {
      company: company,
      mobile: mobile
    }
    let code = await this.getRequest(parsm, 'message')
    if(code?.code == 1){
      this.setData({
        s:60
      })
      this.decrementTime()
    }else{
      wx.showToast({
        title: '验证码获取失败',
        icon: 'error',
        image: '',
        duration: 1500,
        mask: false,
      });
      this.setData({
        countDown:false
      })
    }
  },
  //接口请求
  getRequest(parsm, apig) {
    return new Promise((resolve, rej) => {
      let url = 'https://server.fmode.cn/api/apig/'
      wx.request({
        url: url + apig,
        data: parsm,
        header: { 'content-type': 'application/json' },
        method: 'POST',
        dataType: 'json',
        responseType: 'text',
        success: (result) => {
          console.log(result);
          resolve(result.data)
        },
        fail: () => {
          resolve(false)
        },
        complete: () => { }
      });
    })
  },
  // 倒计时
  decrementTime(){
    timer = setTimeout(() => {
      let { s } = this.data
      if(s == 0){
        this.setData({ countDown:false })
        timer && clearTimeout(timer)
        return
      }
      s--
      this.setData({
        s:s
      })
      this.decrementTime()
    }, 1000);
  },
  //验证码绑定手机号登录
  async completePhone() {
    let { mobile, verilyCode } = this.data
    if(!real.isPoneAvailable(mobile) || !verilyCode.toString().trim()){
      wx.showToast({
        title: '手机号或验证码不正确',
        icon: 'none',
        image: '',
        duration: 1500,
        mask: false,
      });
      return
    }
    let parsm = {
      mobile: mobile,
      code:verilyCode
    }
    let isVerify = await this.getRequest(parsm, 'verifyCode')
    console.log(isVerify);
    if(isVerify.code == 200){
      this.authMobileUser(mobile.toString())
    }else{
      wx.showToast({
        title:isVerify?.msg || '验证码错误',
        icon: 'none',
        image: '',
        duration: 1500,
        mask: false,
      });
      return
    }
  },
  //关闭手机号授权弹窗
  hideModal: function () {
    this.setData({
      phoneModal: false
    })
  },
  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,
      }
      );
    })
  },
  //选择勾选用户协议
  onCheckAgreement() {
    this.setData({
      check: !this.data.check
    })
  },
  //附件下载
  openFile() {
    let {
      agreement
    } = this.data
    let url = agreement.content,
      name = agreement.title
    const _this = this;
    let rep = this.getFileType(url)
    console.log(url, name);
    wx.showLoading({
      title: '加载中',
    })
    wx.downloadFile({
      url: url, //要预览的PDF的地址
      filePath: wx.env.USER_DATA_PATH + `/${name}.${rep}`,
      success: function (res) {
        console.log(res);
        if (res.statusCode === 200) { //成功
          var Path = res.filePath //返回的文件临时地址，用于后面打开本地预览所用
          console.log(Path)
          wx.openDocument({
            filePath: Path, //要打开的文件路径
            showMenu: true,
            success: function (res) {
              wx.hideLoading()
              console.log(res, '打开PDF成功');
            },
            fail: function (res) {
              console.log(res)
              wx.hideLoading()
            }
          })
        }
      },
      fail: function (res) {
        wx.hideLoading()
        console.log(res); //失败
      },
    })
  },
  //解析文件类型
  getFileType(url) {
    let pdfReg = /^.+(\.pdf)$/
    let txtReg = /^.+(\.txt)$/
    let wordReg = /^.+(\.doc|\.docx)$/
    let excelReg = /^.+(\.xls|\.xlsx)$/
    let jpgPng = /^.+(\.png)$/
    let jpgJpg = /^.+(\.jpg)$/
    let jpgJpeg = /^.+(\.jpeg)$/
    if (pdfReg.test(url)) {
      return 'pdf'
    }
    if (txtReg.test(url)) {
      return 'txt'
    }
    if (wordReg.test(url)) {
      return 'docx'
    }
    if (excelReg.test(url)) {
      return 'xls'
    }
    if (jpgPng.test(url)) {
      return 'png'
    }
    if (jpgJpg.test(url)) {
      return 'jpg'
    }
    if (jpgJpeg.test(url)) {
      return 'jpeg'
    }
  },

  onShow: function () {
    let userLogin = wx.getStorageSync('userLogin');
    if (userLogin != '') {
      wx.navigateBack();
    };
  },
  onReady: function () {

  },
})