import { getPagesQuery } from "../../../../core/utils";
import { getCertQrCode, queryCertDetail, queryServiceByCode } from './../../services';
const app = getApp();
Page({
  data: {
    loading: true,
    pageInfo: {},
    serviceInfo: {},
    shouldRefresh: false,
    imgSrcPrefix: app.globalData.imgSrcPrefix
  },

  async onLoad({
    certType,
    certServiceCode
  }) {
    /* 证件类型 */
    const _certType = getPagesQuery('certType');
    /* 证件对应的服务码 */


    const _certServiceCode = getPagesQuery('certServiceCode');

    this.certType = certType || _certType;
    this.serviceCode = certServiceCode || _certServiceCode;
    await this.onStart();
    this.onRunTimer();
  },

  onUnload() {
    if (this.timer) clearTimeout(this.timer);
  },

  updateData(data) {
    return new Promise(resolve => this.setData(data, resolve));
  },

  async onStart() {
    await this.fetchCertDetail(this.certType);
    await this.fetchServiceInfo(this.serviceCode);
    await this.fetchQrCode(this.certType);
    await this.updateData({
      loading: false
    });
  },

  /*
  * 获取服务详情
  * */
  async fetchServiceInfo(code) {
    const [err, data] = await queryServiceByCode(code);
    if (err) return;
    const {
      extInfo,
      imgUrl
    } = data || {};
    const {
      pageInfo
    } = this.data;
    await this.updateData({
      serviceInfo: data,
      pageInfo: { ...pageInfo,
        extInfo,
        imgUrl
      }
    });
  },

  /*
  * 获取二维码详情
  * */
  async fetchQrCode(certType) {
    const [err, data] = await getCertQrCode(certType);
    if (err) return;
    const {
      pageInfo
    } = this.data;
    await this.updateData({
      pageInfo: { ...pageInfo,
        ...data
      }
    });
  },

  /*
  * 获取卡片详情
  * */
  async fetchCertDetail(certType) {
    const [err, data] = await queryCertDetail(certType);
    if (err) return;
    await this.updateData({
      pageInfo: data
    });
  },

  /*
  * 定时器
  * */
  onRunTimer() {
    const {
      extInfo
    } = this.data.pageInfo;
    const {
      certCodeRate = 60
    } = extInfo || {};
    this.timer = setTimeout(async () => {
      await this.updateData({
        shouldRefresh: true
      });
    }, 1000 * +certCodeRate);
  },

  async onRefreshHandel() {
    this.onRunTimer();
    await this.updateData({
      shouldRefresh: false
    });
    await this.fetchQrCode(this.certType);
  }

});