const _my = require("../../../__antmove/api/index.js")(my);
const wx = _my;
const face = require("../../../utils/faceCheck/faceCheck");
const {
  getContextByAdminId
} = require("../../../utils/api/api");
const {
  throttle
} = require("../../../utils/throttle/throttle");
const date = require("/utils/util/util");
const app = getApp();
import getAuthThree from '/utils/api/auth_api'
import bus from 'iny-bus'

Page({
  /**
   * 页面的初始数据
   */
  data() {
    return {
      // 输入信息
      inputName: "",
      inputIdcard: "",
      phoneNumber: "",
      userId: null,
      //手机号校验信息
      isShowApplet: null,
      disabledSubmitScan: false,
      eventId: null,
      times: 0
    }
  },
  goto() {
    this.data.times++
    if(this.data.times > 5) {
      this.data.times = 0
      my.reLaunch({
        url: "/pages/index/index"
      })
    }
    
  },
  //查看照片
  watch() {
    wx.previewImage({
      urls: ["https://noise.hz-hanghui.com:8088/yx-fyzd/file/img/instruction.png"]
    });
  },
  authClick: throttle(function () {
    if(this.data.disabledSubmitScan) {
      return
    }
    const taskId = `${date.formatTime(Date.now(), "YYYYMMDDHHNNSS")}${parseInt((Math.random() * 9 + 1) * 10000)}`
    my.setStorage({
      key: 'auth-taskId',
      data: taskId
    })
    my.navigateToMiniProgram({
      appId: app.globalData.authAppId, // 16 位
      path: 'pages/authorize_three/authorize_three',
      query: {
        name: '易行智慧通',
        notify: null,
        token: app.globalData.authAppToken,
        taskId
      }
    })
  }, 5000),
  // 支付宝验证人脸
  async doZFBFaceCheck() {
    let {
      inputName,
      inputIdcard,
      phoneNumber,
      userId
    } = this.data;
    let res = await face.getFace_wxrlxf("/api/next/ZFBConfirmFace", "post", {
      idNumber: inputIdcard,
      phone: phoneNumber,
      username: inputName,
      userId
    })
    if (res.data.status === true) {
      let userInfo = res.data
      userInfo.org = this.data.org
      userInfo.orgId = this.data.orgId
      userInfo.cardIdEx = this.data.cardIdEx
      userInfo.options = this.data.options
      app.data.userInfo = userInfo
      const that = this
      my.alert({
        title: '提示',
        content: '授权成功',
        success() {
          that.setCertificationState(true)
        }
      })
    } else {
      this.setCertificationState(false)
      my.alert({
        title: "提示",
        content: "未查询到认证结果,请重新认证!"
      })
    }
  },
  //获取是否有自定义字段
  getContextByAdminId(orgId) {
    let that = this;
    this.data.isShowApplet = null;
    wx.showLoading({
      title: "检查账号配置中.."
    });
    return getContextByAdminId(orgId).then(res => {
      that.data.isShowApplet = res.data;
    }).finally(() => {
      wx.hideLoading();
    });
  },
  //跳转页面 (是否缓存进入)
  changePage(showModal) {
    if (this.data.isShowApplet) {
      wx.navigateTo({
        url: "/pages/wx_airport/rlxf_userMsg/index?orgId=" + this.data.orgId + "&org=" + this.data.org + "&showModal=" + showModal
      });
    } else {
      wx.reLaunch({
        url: "/pages/wx_airport/rlxf_pass/rlxf_pass?orgId=" + this.data.orgId + "&org=" + this.data.org + "&showModal=" + showModal
      });
    }
  },
  goProblem() {
    wx.navigateTo({
      url: "/pages/wx_airport/problem_report/index?adminId=" + this.data.orgId
    });
  },
  onAppShowHandler(options) {
    console.log(options);
    if(options && options.referrerInfo) {
      // 从三要素认证返回
      if(options.referrerInfo.appId === app.globalData.authAppId && options.referrerInfo.extraData) {
        const authStatus = options.referrerInfo.extraData.authStatus
        if(authStatus) {
          const authTaskId = my.getStorageSync({ key: 'auth-taskId' })
          my.removeStorage({ key: 'auth-taskId' })
          if(authTaskId && authTaskId.data) {
            bus.emit('appShowHandler', authTaskId.data)
          }
        } else {
          my.alert({
            title: '提示',
            content: '授权失败'
          })
        }
      }
    }
  },
  async zfbAuthCallback(authTaskId) {
    my.showLoading({
      content: "加载中..."
    })
    const result = await getAuthThree({taskId: authTaskId, token: app.globalData.authAppToken})
    /**
     * certNo 身份证号
     * certName 姓名
     * phone  手机号
     */
    if(result.errcode) {
      my.alert({
        title: "提示",
        content: "未查询到认证结果,请重新认证!"
      })
      return
    }
    if(!result.data || !result.data.token) {
      my.alert({
        title: "提示",
        content: result.msg
      })
      return
    }
    this.setData({
      inputName: result.data.certName,
      inputIdcard: result.data.certNo,
      phoneNumber: result.data.phone,
      userId: result.data.userId
    })
    this.doZFBFaceCheck()
    my.hideLoading()
  },
  // 设置授权状态
  setCertificationState(isSuccess) {
    if(isSuccess) {
      wx.setStorageSync("userInfo", app.data.userInfo)
      this.changePage(true)
    } else {
      app.data.userInfo = null
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    my.onAppShow(this.onAppShowHandler)
    this.data.eventId = bus.on('appShowHandler', (res) => {
      this.zfbAuthCallback(res)
    })
    let launchOptions = my.getLaunchOptionsSync()
    if(!launchOptions.query) {
      launchOptions = my.getEnterOptionsSync()
    }
    let json = {};
    if (!options.isJump) {
      // var url = decodeURIComponent(options.q);
      // json = verify.GetQueryJson(url);
      json = launchOptions.query || {}
    } else {
      json = options;
    }
    // 测试用
    json = {
      orgId: 54,
      org: '公司测试',
      type: 0,
    //   disinfectAreaId: 5
    };

    let moduleContent = {
      msg: "未检测到区域码,请扫正确的二维码进入小程序哦~",
      show: false
    };
    if (!("orgId" in json)) {
      moduleContent.show = true;
    }
    if (json.orgId == "" || String(json.orgId) == "null" || String(json.orgId) == "undefined") {
      moduleContent.show = true;
      moduleContent.msg = "区域码数据已失效，请联系管理员更新二维码";
    }
    if (moduleContent.show) {
      my.alert({
        title: "提示",
        content: moduleContent.msg
      });
      this.setData({
        disabledSubmitScan: true
      });
      return;
    }
    //保留二维码的参数
    let urlString = "";
    for (let i in json) {
      urlString += `${i}=${json[i]}&`;
    }
    this.data.options = urlString;
    this.data.orgId = json.orgId;
    this.data.org = json.org;
    app.data.type = json.type ? json.type : null;
    await this.getContextByAdminId(json.orgId);
    // 判断缓存
    var userInfo = wx.getStorageSync("userInfo");
    if (userInfo) {
      if (userInfo.orgId != json.orgId) {
        userInfo.createTime = "";
      }
      userInfo.orgId = json.orgId;
      userInfo.org = json.org;
      userInfo.options = urlString;
      wx.setStorageSync("userInfo", userInfo);
      this.changePage(false);
    }
    if ("disinfectAreaId" in json) {
      app.data.disinfectAreaId = json.disinfectAreaId;
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // setTimeout(() => {
    //   this.zfbAuthCallback('2023061316041384222')
    // }, 3000)
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    bus.remove('appShowHandler', this.data.eventId)
    my.offAppShow(this.onAppShowHandler)
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  antmoveAction: function () {
    //执行时动态赋值，请勿删除
  }
});