import {
  tracking,
  snConfig,
  getVisitDeviceUser,
  visitorCodeSignOut
} from './utils/api/api'
import {
  getForm,
  getDate,
  formatTime
} from './utils/index/index'

import {
  closeSecondaryScreen, openCycleSecondaryScreen, openSecondaryScreen
} from './utils/index/callAmpe'
App({
  data: {
    // 用户输入身份证号
    inputIdCard: '',
    // 用户输入手机号
    inputPhone: '',
    //设备上报心跳
    TIME_COUNT: 60,
    timer: null,
    //用户信息
    userInfo: {
      avatar: '',
      idCardPhoto: '',
      xm: '',
      sfzh: '',
      phone: '',
      workPlace: '',
      carNumber: '',
      // xm: '张佳燕',
      // sfzh: '331082199910045826',
      // phone: '15888632412',
    },
    // 刷证获取到的用户信息
    brushingCardUserIInfo: {},
    // 拜访成功数据信息
    visitoMsgData: {},
    // 签离成功的用户信息
    signOffMsg: {},
    // 刷身份证是否开始
    isOkBrushingCard: false,
    // 扫码登记是否开始
    isOkQrCodeSignIn: false,
    // 刷脸是否开始
    isokFaceScan: false,
    // 刷脸初始化是否成功
    isFaceScanInitialize: false, // 是否捕获到联网查询错误
    isNetworkQueryError: true,
    clickRetryNum: 0, //获取用户信息重试次数
    isSecondaryScreenState: true, // 是否能加载到副屏
    cycleIntervalId: null, // 副屏展示定时器
    cycleIntervalSwitch: false, // 副屏展示是否开启
    secondaryPageImagesIndex: 0,
  },
  onLaunch(options) {
    // this.initGlobalDataWatcher();
    let snDisposition = my.getStorageSync({
      key: 'snDisposition'
    }).data;
    if (snDisposition) {
      this.globalData.snDisposition = snDisposition
    }
    this.globalData.snDisposition.id = null
    this.getSecondaryScreenState()
    this.getSystemInfo()
    this.getSystemInfoSync()
    this.getDeviceInformation()
    this.initialize()
    this.brushingCard()
    this.scanCode()

    // this.snConfig()
  },
  onShow(options) {
    // 从后台被 scheme 重新打开
  },
  // 初始化
  initialize() {
    // 刷脸初始化
    let params = {
      "action": "initFace",
      "event": "open",
      "taskId": "2",
      "params": {
        "scope": "auth_user,order_service"
      }
    }
    console.log('刷脸初始化开始');
    my.call("ampeHHCommunication", params, res => {
      console.log(res, '刷脸初始化结束')
      if (res.success) {
        this.data.isFaceScanInitialize = true
      }
    });
  },
  initSecondaryScreen() {
    // 启用首页副屏
    console.log(this.data.isSecondaryScreenState && this.globalData.snDisposition.secondaryPageSwitch)
    if (this.data.isSecondaryScreenState && this.globalData.snDisposition.secondaryPageSwitch) {
      console.log('打开副屏轮播', this.data.isSecondaryScreenState);
      openCycleSecondaryScreen()
    }

    // console.log('关闭副屏', app.data.isSecondaryScreenState)
    // if (app.data.isSecondaryScreenState && app.globalData.snDisposition.secondaryPageSwitch) {
    //   // closeSecondaryScreen()
    //   closeCycleSecondaryScreen()
    // }
  },
  // 获取副屏状态
  getSecondaryScreenState() {
    let params = {
      "action": "getSecondaryScreenState",
      "event": "open",
      "taskId": "10",
    }
    try {
      my.call("ampeHHCommunication", params, res => {
        console.log(res, '获取副屏状态')
        this.data.cycleIntervalId && clearInterval(this.data.cycleIntervalId);
        this.data.isSecondaryScreenState = false
        this.data.secondaryPageImagesIndex = 0
        if (res.success) {
          // 副屏展示状态 显示1 关闭 0  暂不支持 -1(没加载到副屏)
          let screenState = res.data.getSecondaryScreenState;
          this.data.isSecondaryScreenState = true
          if (screenState == -1) {
            this.data.cycleIntervalSwitch = false
          } else if (screenState == 1) {
            closeSecondaryScreen()
          }
          this.initSecondaryScreen()
          console.log('ampeHHCommunication', res);
          console.log(this.data.isSecondaryScreenState)
        } else {
          this.data.cycleIntervalSwitch = false
        }
      })
    } catch (error) {
      console.log(error);
    }
  },

  //设备上报心跳的接口 60秒调一次
  trackingInterval() {
    let {
      TIME_COUNT,
      timer,
      count
    } = this.data
    if (!timer) {
      count = TIME_COUNT;
      timer = setInterval(async () => {
        if (count > 0 && count <= TIME_COUNT) {
          count--;
        } else {
          clearInterval(timer);
          this.data.timer = null;
          await this.tracking()
          this.trackingInterval()
        }
      }, 60 * 1000)
    }
  },
  async tracking() {
    let form = {
      sn: this.globalData.sn
    }
    try {
      let res = await tracking(form)
    } catch (error) {
      console.log(error);
    }
  },
  // 获取设备信息
  getDeviceInformation() {
    let params = {
      "action": "getDeviceInfo",
      "event": "open",
      "taskId": "4"
    }
    let that = this
    try {
      my.call('ampeHHCommunication', params, res => {
        console.log(res, '获取设备信息');
        if (res.data) {
          that.globalData.deviceInformation = res.data
          that.globalData.sn = res.data.sn
          that.snConfig()
          that.tracking()
          that.trackingInterval()
        }
      });
    } catch (error) {
      console.log(error);
    }
  },
  getSystemInfo() {
    // 利用callback回调 解决页面异步调取 数据的问题 todo
    my.getSystemInfo({
      success: (res) => {
        // 通过宽高比例判断屏幕类型
        if (res.screenWidth / res.screenHeight > 1) {
          this.globalData.isPortraitScreen = false
          console.log('getSystemInfo====>横屏模式');
        } else {
          this.globalData.isPortraitScreen = true
          console.log('getSystemInfo====>竖屏模式');
        }
      },
      fail: (err) => {
        console.log(err);
      }
    });

  },
  // 获取版本号
  getSystemInfoSync() {
    const accountInfo = my.getAccountInfoSync();
    this.globalData.appVersion = accountInfo.miniProgram.version
  },
  // 获取设备配置
  async snConfig() {
    let data = {
      "token": this.globalData.FKJConfiguration,
      "sn": this.globalData.sn
    }
    try {
      let res = await snConfig(data)
      this.globalData.snDisposition = res.data
      my.setStorageSync({
        data: res.data,
        key: 'snDisposition'
      });
    } catch (error) {
      console.log(error);
    }
  },
  // 刷身份证监听
  brushingCard() {
    my.on('initIDCardListener', res => {
      console.log("刷身份证监听", this.data.isOkBrushingCard, res.data)
      if (!this.data.isOkBrushingCard && !this.data.isokFaceScan) {
        if (res.data) {
          this.data.isOkBrushingCard = true
          this.data.brushingCardUserIInfo = res.data
          this.data.brushingCardUserIInfo.name = this.data.brushingCardUserIInfo.name.replace(/\s*/g, "")
          setTimeout(()=>{
            closeSecondaryScreen()
            this.data.cycleIntervalSwitch = false
          }, 1000)
          this.data.userInfo.idCardPhoto = res.data.photoBase64
          my.reLaunch({
            url: '/pages/resultPage/index?result=首页刷证',
          })
        } else {
          my.showToast({
            content: '刷证失败，请重试',
            duration: 2000
          });
        }
      } else {
        return
      }

    })
  },
  //开启⼆维码监听
  scanCode() {
    my.on('initQRListener', async res => {
      console.log('⼆维码监听 ', res.data)
      // 扫码登记
      if (res.data && res.data.qrCode && res.data.qrCode.indexOf('HHFKJ') > -1) {
        if (!this.data.isOkQrCodeSignIn) {
          this.data.isOkQrCodeSignIn = true
          let data = getForm(res.data.qrCode)
          this.getVisitDeviceUser(data)
        }
      } else if (res.data && res.data.qrCode) {
        if (res.data.qrCode.indexOf('\\000026') > -1 || res.data.qrCode.indexOf('\\000029') > -1) {
          res.data.qrCode = res.data.qrCode.slice(7)
        }
        console.log(res.data.qrCode);
        // 扫码签离
        let data = {
          sn: this.globalData.sn,
          code: res.data.qrCode
        }
        console.log(data);
        try {
          let res = await visitorCodeSignOut(data)
          console.log(res.data);
          this.data.signOffMsg = res.data
          setTimeout(()=>{
            closeSecondaryScreen()
            this.data.cycleIntervalSwitch = false
          }, 1000)
          my.reLaunch({
            url: '/pages/resultPage/index?result=签离成功'
          });
        } catch (error) {
          console.log(error);
          my.showToast({
            content: error.msg || '扫码失败，请重试',
            duration: 2000
          });
        }
      } else {
        my.showToast({
          content: '扫码失败，请重试',
          duration: 2000
        });
      }
    })
  },
  // 小程序二维码登记
  async getVisitDeviceUser(data) {
    let data1 = {
      userId: data.serId,
      timestamp: data.timestamp,
    }
    try {
      let res = await getVisitDeviceUser(data1)
      this.data.userInfo.avatar = res.data.avatar
      this.data.userInfo.xm = res.data.username
      this.data.userInfo.sfzh = res.data.idNumber
      this.data.userInfo.phone = res.data.phone
      this.data.userInfo.visitorUnit = res.data.workPlace
      this.data.userInfo.carnum = res.data.carNumber
      this.data.userInfo.verifyType = 6; // 二维码
      this.data.userInfo.certContent = res.data; // 身份证阅读器返回全部
      let reminderAuth = this.globalData.snDisposition.reminderAuth;
      // 是否跳转到提示页
      if (reminderAuth) {
        my.reLaunch({
          url: '/pages/tipsPage/index'
        })
      } else {
        // 是否启用副屏处理中页面
        let processingPageSwitch = this.globalData.snDisposition.processingPageSwitch;
        if (this.data.isSecondaryScreenState && processingPageSwitch) {
          console.log('打开副屏', this.data.isSecondaryScreenState);
          closeSecondaryScreen()
          this.data.cycleIntervalSwitch = false
          openSecondaryScreen(this.globalData.snDisposition.processingPageImage || '')
        }
        my.reLaunch({
          url: '/pages/interviewee/index'
        })
      }
    } catch (error) {
      console.log(error);
      this.data.isOkQrCodeSignIn = false
      setTimeout(()=>{
        closeSecondaryScreen()
        this.data.cycleIntervalSwitch = false
      }, 1000)
      my.reLaunch({
        url: '/pages/resultPage/index?result=结果页超时&&timer=' + this.globalData.snDisposition.resultPageTimeout,
      })
    }
  },
  globalData: {
    isPortraitScreen: null,// 是否为竖屏：true竖屏 false横屏
    // 13CD002006700011  137D002002300009 118D002000500012 136D002002300012
    sn: '',
    appVersion: '', //app版本号
    // 获取访客机配置token
    FKJConfiguration: '01f8624317168a4a52fd89f673a3ccbc',
    // 所修改内容的类型 0：修改基本设置 1：修改高级设置 2：超时时长设置 3：语音设置 4：密码设置
    modifyType: [0, 1, 2, 3, 4],
    //访客机配置
    snDisposition: {
      mode: null,
      sn: null,
      status: null,
      useAlipayFace: true,
      useIdcard: true,
      usePersonCard: true,
      voiceVolume: 80,
      mpassword: "117521",
      purchaserId: null,
      applicationTypeId: null,
      deviceModelHardwareId: null,
      deviceModelEnvironmentId: null,
      systemTypeCode: null,
      noIdcardRegister: false,
      noIdcardInputPhone: true,
      wxScanRegister: false,
      zfbScanRegister: false,
      wxQrcodeUrl: "https://tx.hz-hanghui.com:8088/yx-fyzd/faceCheckVisitor?type=2",
      zfbQrcodeUrl: "https://tx.hz-hanghui.com:8088/yx-fyzd/faceCheckVisitor?type=2",
      visiteeUrl: "https://tx.hz-hanghui.com:8088/yx-fyzd/api/v1/fkj/visitee/list",
      areaUrl: "https://tx.hz-hanghui.com:8088/yx-fyzd/api/v1/fkj/area/info",
      transitPushSwitch: true, // 启用进出记录推送 默认值：true
      transitPushUrl: "https://tx.hz-hanghui.com:8088/yx-fyzd/visitorReport",
      printVisitorList: false,
      signOut: true,
      riskCheck: false,
      hiddenButton: false,
      reminderAuth: false, // 是否启用注意事项提示语
      reminder: '', // 注意事项提示图片
      reminderPlayText: '', // 提示标语播报文本
      confirmCountdownSwitch: true, // 是否启用确定倒计时
      confirmCountdownTime: 15,
      secondaryPageSwitch: true, // 是否启用副屏轮播图
      secondaryPageImages: [], // 副屏轮播图（0/5）
      processingPageSwitch: true, // 是否启用副屏处理中页面
      processingPageImage: '', // 副屏处理中页面图
      generalQrcode: true,
      generalQrcodeTitle: "",
      ethQrcode: true,
      ethQrcodeTitle: "梯控二维码",
      ethQrcodeUrl: "https://tx.hz-hanghui.com:8088/yx-fyzd/api/v1/fkj/visitor/eth/qrCode",
      chooseVisiteeTimeout: 90,
      readIdcardTimeout: 15,
      inputIdcardTimeout: 30,
      inputPhoneTimeout: 30,
      singOutTimeout: 15,
      resultPageTimeout: 5,
      successVoice: "比对成功",
      failVoice: "比对失败，请重试，或刷身份证",
      registerSuccessVoice: "正在打印访客单",
      readIdcardVoice: "请刷身份证",
      inputIdcardVoice: "请输入身份证号",
      inputPhoneVoice: "请输入手机号",
      connectSearchVoice: "正在联网查询信息，请耐心等待",
      singOutVoice: "请将二维码对准设备的扫码窗",
      notDesensitizedColumn: [],
      registerNotDesensitizedColumn: [],
      faceTimeout: 40,
      oneToOneTimeout: 40,
      connectSearchTimeout: 40,
      faceFailHandInput: false,
      visitReason: '', // 拜访事由选项
      expirationDate: null, // 使用时间期限
    },
    // 设备信息
    deviceInformation: {},
    // 获取三要素在线配置接口
    serviceAddress: '',
    // 获取用户信息
    appId: '3292340fd1d913395fe32f781399604a',
    appKey: 'hhLOhU8Wb5x',
    appSecret: '3ade6850270e2964bb7499492493e464ceccf937',
    privateKey: 'wxuoukkrts68aqwv',
    // ⾃然⼈⻛险评分查询
    appIdRisk: 'be454b553daa209177e8d51883e828d2',
    appKeyRisk: 'hh0SLerEB5E',
    appSecretRisk: '2ec80e28fa7c98936fd053c9b72aa81692bb5ec5',
    privateKeyRisk: 'yfxrbbnnmsyuteaj',
    // ⾃然⼈⻛险评分查询结果 1:正常2:逃犯3:其他
    riskResult: 1,
    expirationDateOpenNum: 0, // 到期提醒打开次数
  },
  /*globalDataWatchers: {},

  /!**
   * 初始化递归监听
   *!/
  initGlobalDataWatcher() {
    this.observe(this.globalData);
  },

  /!**
   * 递归监听对象
   * @param {Object} obj 要监听的对象
   * @param {String} parentKey 父路径
   *!/
  observe(obj, parentKey = '') {
    const watchers = this.globalDataWatchers;

    Object.keys(obj).forEach(key => {
      let value = obj[key];
      const fullPath = parentKey ? `${parentKey}.${key}` : key; // 完整路径

      // 如果是对象，递归监听其子属性
      if (value && typeof value === 'object') {
        this.observe(value, fullPath);
      }

      // 定义 getter 和 setter
      Object.defineProperty(obj, key, {
        configurable: true,
        enumerable: true,
        get() {
          return value;
        },
        set: newValue => {
          if (newValue !== value) {
            value = newValue;
            console.log(`${fullPath} 被更新为:`, newValue);

            // 触发监听器
            if (watchers[fullPath]) {
              watchers[fullPath].forEach(callback => callback(newValue));
            }

            // 如果新值是对象，递归监听其子属性
            if (newValue && typeof newValue === 'object') {
              this.observe(newValue, fullPath);
            }
          }
        },
      });
    });
  },

  /!**
   * 添加监听器
   * @param {String} path 属性路径
   * @param {Function} callback 回调函数
   *!/
  watchGlobalData(path, callback) {
    if (!this.globalDataWatchers[path]) {
      this.globalDataWatchers[path] = [];
    }
    this.globalDataWatchers[path].push(callback);
  },
  /!**
   * 移除监听器
   * @param path 属性路径
   * @param callback 回调函数
   *!/
  unwatchGlobalData(path, callback) {
    const watchers = this.globalDataWatchers[path];
    if (watchers) {
      this.globalDataWatchers[path] = watchers.filter(cb => cb !== callback);
    }
  },*/
});
