// packageI/diyRormProve/diyRormProveSubmit/diyRormProveSubmit.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isProve: false, //是否已核销成功
    pageMode: null, //页面类型。提交还是核销
    loading: true,
    showCode: false, //核销码弹窗
    finish: false, //倒计时已结束
    status: 0,
    field: {},
    code_url: "", //核销码图片地址
    dataId: "", //提交后的表单数据id
    timer: null,

    thumb: null,
    description: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _mode = null;
    if(options.scene){
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if (chil_arr[0] == "id") {
            this.data.id = chil_arr[1];
          } else if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          } else if (chil_arr[0] == "mode") {
            _mode = chil_arr[1];
          }
        }
      }
    }else {
      _mode = this.options.mode;
      this.data.id = this.options.id;
    }
    if (_mode == "submit") {
      // 会员提交表单
      this.getData();
    } else if (_mode == "prove") {
      this.setData({
        pageMode: "prove"
      });
      this.getProveData();
    }
  },
  getData() {
    // 获取表单数据
    if (!this.options.id) {
      return;
    }
    let urlStr = app.getNetAddresss("plugin.diy-form-prove.frontend.controllers.prove.formDetail");
    app._postNetWork({
      url: urlStr,
      data: {
        id: this.data.id
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          // if (res.data.form_data.is_prove == 0 && res.data.form_data.data_id) {
          //   // 场景：1.已提交但是一直没核销成功，手动删除。2.手动刷新页面
          //   this.data.dataId = res.data.form_data.data_id;
          //   this.delForm();
          //   return;
          // }
          this.setData({
            thumb: res.data.form_data.thumb || null,
            description:res.data.form_data.description || null,
            loading: false,
            field: res.data.form_data.fields,
            status: res.data.form_data.status,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  submit(e) {
    console.log(e.detail);
    // 提交表单数据，提交后需要核销员核销
    let urlStr = app.getNetAddresss("plugin.diy-form-prove.frontend.controllers.prove.saveData");
    app._postNetWork({
      url: urlStr,
      data: {
        form_id: this.data.id,
        form_data: e.detail
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.data.dataId = res.data.id;
          this.getEwmImg(res.data.id);
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  getEwmImg(_id) {
    // 弹窗显示后，需要进行核销，轮询查询核销结果
    let urlStr = app.getNetAddresss("plugin.diy-form-prove.frontend.controllers.prove.proveCode");
    app._postNetWork({
      url: urlStr,
      data: {
        data_id: _id
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.setData({
            code_url: `${res.data.code_url}?${Date.now()}`,
            showCode: true,
            finish: false,
          });
          this.pollTimers(); //轮询
          const countDown = this.selectComponent('.control-count-down');
          countDown.reset();
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  pollTimers() {
    if (this.data.finish) {
      // 超过2分钟有效期
      return;
    }
    let that = this;
    let urlStr = app.getNetAddresss("plugin.diy-form-prove.frontend.controllers.prove.checkProve");
    app._postNetWork({
      url: urlStr,
      data: {
        id: this.data.dataId
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          if (res.data.status == 0) {
            this.data.timer = setTimeout(() => {
              that.pollTimers();
            }, 3000);
          } else {
            wx.showToast({
              icon: "none",
              title: '核销成功',
              duration: 1000,
            });
            this.setData({
              status: 1
            });
            this.initForm();
          }
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  close() {
    let that = this;
    let _text = this.data.finish ? "二维码链接已失效，请重新提交" : "关闭后数据需要重新填写，是否确认关闭";
    wx.showModal({
      title: '提示',
      content: _text,
      success(res) {
        if (res.confirm) {
          that.delForm();
          that.initForm();
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    });
  },
  delForm() {
    // 删除表单记录
    // data_id为提交后的表单数据id
    let urlStr = app.getNetAddresss("plugin.diy-form-prove.frontend.controllers.prove.delProve");
    app._postNetWork({
      url: urlStr,
      data: {
        data_id: this.data.dataId
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.getData();
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  finishTimer() {
    this.setData({
      finish: true
    });
    this.delForm();
    this.initForm();
  },
  initForm() {
    if (this.data.timer) clearTimeout(this.data.timer); //清理定时任务
    this.setData({
      showCode: false,
      code_url: '',
      dataId: null
    });
  },

  // 核销 =======
  getProveData() {
    let urlStr = app.getNetAddresss("plugin.diy-form-prove.frontend.controllers.prove.dataDetail");
    app._postNetWork({
      url: urlStr,
      data: {
        id: this.data.id
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.setData({
            field: res.data.form_data.fields,
            status: 1,
            loading: false,
            isProve: res.data.form_data.is_prove || false,
            thumb: res.data.form_data.thumb || null,
            description: res.data.form_data.description || null
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg,
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定');
              } else if (res.cancel) {
                console.log('用户点击取消');
              }
            }
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });

  },
  proveForm() {
    if(this.data.isProve){
      return;
    }
    let urlStr = app.getNetAddresss("plugin.diy-form-prove.frontend.controllers.prove.submitProve");
    app._postNetWork({
      url: urlStr,
      data: {
        data_id: this.data.id
      },
      success: (resdata) => {
        let res = resdata.data;
        wx.showModal({
          title: '提示',
          content: res.msg,
          success(res) {}
        });
        if (res.result == 1) {
          this.setData({
            isProve: true
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if (this.data.timer) clearTimeout(this.data.timer); //清理定时任务
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.thumb,
      imageUrl: this.data.description
    };
  }
});