// packageH/signPage/personBank/personBank.js
const app = getApp();
Page({
  data: {
    activeName: '',
    step: 1,
    checkboxGroup: [],
    protocolShow: false,
    agreement: {},
    form: {
      name: "",
      id_no: "",
      tel: "",
      captcha: "",
      face_auth_mode: ''
    },
    authcode: "",
    bank_no: "",
    flow_id: "",
    count: "",
    timer: null,
    imgcode: "", //图形验证码

    is_real_name: false,
    real_name_auth_set: {},
    shop_name: '',
    realNameProtocolShow: false,
    is_bind_mobile: 0,
    is_mobile: 1
  },

  onLoad: function (options) {
    if (options.from === 'bindRealName') {
      this.setData({
        is_real_name: true
      });
      this.getimgdata();
      this.getAuth();
    } else {
      this.getPersonData();
      this.getAgreement();
    }
  },
  onReady: function () {

  },


  //绑定图形验证码的值
  captchainp(e) {
    let val = e.detail.value;
    this.setData({
      "form.captcha": val.trim(),
    });
  },
  //获取图片验证码
  getimgdata() {
    let urlStr = app.getNetAddresss("home-page.getCaptcha");
    app._getNetWork({
      url: urlStr,
      validateBol: 2,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          if (res.data.captcha) {
            this.setData({
              imgcode: res.data.captcha.img
            });
          }
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });

  },
  getAuth() {
    let queryUrl = app.getNetAddresss('plugin.real-name-auth.frontend.auth.index');
    app._getNetWork({
      url: queryUrl,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result === 1) {
          if (res.data.protocol_set && res.data.protocol_set.content) {
            res.data.protocol_set.content = res.data.protocol_set.content.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block" ');
            res.data.real_name_auth_set.content = res.data.real_name_auth_set.content.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block" ');
          }

          this.setData({
            real_name_auth_set: res.data.real_name_auth_set,
            agreement: res.data.protocol_set,
            shop_name: res.data.shop_name,
            is_bind_mobile: res.data.is_bind_mobile,
          });
        } else {
          console.log(res.msg);
        }
      },
      fail: function (err) {
        console.log(err, "失败-----------");
      }
    });
  },
  sureAuthIdentify() {
    let queryUrl = "";
    let json = {};
    const TIME_COUNT = 60;
    if (this.data.is_bind_mobile != 1) {
      this.data.form.is_mobile = this.data.is_mobile;
    }
    if (app._isTextEmpty(this.data.form.captcha) && this.data.imgcode) {
      wx.showToast({
        icon: "none",
        title: "请填写图形验证码",
        duration: 1500,
      });
      return;
    }
    if (this.data.activeName == 1) {
      queryUrl = app.getNetAddresss("plugin.real-name-auth.frontend.auth.authTel");
      json = this.data.form;
    } else if (this.data.activeName == 2) {
      queryUrl = app.getNetAddresss("plugin.real-name-auth.frontend.auth.authBank");
      this.setData({
        ['form.bank_no']: this.data.bank_no
      });
      json = this.data.form;
    }
    app._postNetWork({
      url: queryUrl,
      data: json,
      success: (resdata) => {
        this.data.timer = null;
        if (resdata.data.result === 1) {
          let res = resdata.data;
          app.tips("已发送");
          this.setData({
            flow_id: res.data.flowId
          });
          if (!this.data.timer) {
            this.countDown = TIME_COUNT;
            this.data.timer = setInterval(() => {
              if (this.countDown > 0 && this.countDown <= TIME_COUNT) {
                this.setData({
                  count: --this.countDown
                });
              } else {
                clearInterval(this.data.timer);
                this.data.timer = null;
              }
            }, 1000);
          }
        } else {
          wx.showModal({
            title: "提示",
            content: resdata.data.msg,
            showCancel: false
          });
        }
      }
    });
  },
  sendAuthCode() {
    let url = "";
    let json = {};
    if (this.data.activeName == 1) {
      url = app.getNetAddresss("plugin.real-name-auth.frontend.auth.telSms");
      json = {
        flow_id: this.data.flow_id,
        code: this.data.authcode
      };
    } else if (this.data.activeName == 2) {
      url = app.getNetAddresss("plugin.real-name-auth.frontend.auth.bankSms");
      json = {
        flow_id: this.data.flow_id,
        code: this.data.authcode
      };
    } else {
      url = app.getNetAddresss("plugin.real-name-auth.frontend.auth.authFace");
      json = {
        name: this.data.form.name,
        id_no: this.data.form.id_no,
        tel: this.data.form.tel,
        face_auth_mode: this.data.form.face_auth_mode == 1 ? 'ESIGN' : '',
        callback_url: "/packageG/index/index"
      };
    }
    if (this.data.is_bind_mobile != 1) {
      json.is_mobile = this.data.is_mobile;
    }
    app._postNetWork({
      url,
      data: json,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result === 1) {
          let value;
          if (this.data.real_name_auth_set.auth_scene.indexOf('1') > -1) {
            value = wx.getStorageSync("yz_redirect");
          } else {
            value = wx.getStorageSync("real_name_redirect");
          }
          if (this.data.activeName == 3) {
            this.setData({
              flow_id: res.data.flowId
            });
            wx.navigateToMiniProgram({
              appId: 'wx1cf2708c2de46337', // 上链公证签小程序APPID
              path: '/pages/index/index', // 上链公证签页面地址
              extraData: {
                requestObj: { // 必填，入参
                  flowId: res.data.flowId, // 必填，认证流程Id
                  type: 'REALNAME', // 必填，业务类型：实名 REALNAME
                  env: 'prod' // 非必填，对接环境：线上 prod(默认）, 模拟 sml(用于对接调试阶段）
                },
                callbackObj: { // 非必填，回传数据：签署完成后会将此数据完整回传
                  url: `/${value}`,
                },
                envVersion: 'release',
              },
            });
            wx.removeStorageSync("real_name_redirect");
            // wx.redirectTo({
            // 	url: `/packageH/signPage/signPage?url=${res.data.data.authUrl}`,
            // });
          } else {
            app.tips('认证成功');
            if (value) {
              wx.redirectTo({
                url: `/${value}`,
                fail: function (err) {
                  // 防止跳转不了
                  wx.reLaunch({
                    url: "/packageG/index/index",
                  });
                }
              });
              wx.removeStorageSync("real_name_redirect");
            } else {
              wx.reLaunch({
                url: "/packageG/index/index",
              });
            }
          }
        } else {
          wx.showModal({
            title: "提示",
            content: resdata.data.msg,
            showCancel: false
          });
        }
      },
      fail(err) {
        app.tips(err.msg);
      }
    });
  },

  // 人员数据
  getPersonData() {
    let queryUrl = app.getNetAddresss('plugin.yun-sign.frontend.h5.person.check-person-approve');
    app._getNetWork({
      url: queryUrl,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result === 1) {
          // 已经认证成功
          this.setData({
            person: res.data
          });
          if (res.status == "SUCCESS") {
            wx.navigateTo({
              url: `/packageH/signPage/identifyResult/identifyResult?show=person`,
            });
          }
        } else {
          console.log(res.msg);
        }
      },
      fail: function (err) {
        console.log(err, "失败-----------");
      }
    });
  },

  // 获取认证协议内容
  getAgreement() {
    let queryUrl = app.getNetAddresss('plugin.yun-sign.frontend.person.get-agreement');
    app._postNetWork({
      url: queryUrl,
      showToastIn: true,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result === 1) {
          this.setData({
            agreement: res.data
          });
        } else {
          app.tips(res.msg);
        }
      }
    });
  },

  // 第一步---> 开始认证按钮
  getMemberData() {
    if (this.data.checkboxGroup.length <= 0 && (!this.data.is_real_name || this.data.agreement.status == 1)) {
      return;
    }
    if (this.data.is_real_name) {
      // 跳转过来的实名认证
      this.setData({
        step: 2
      });
      return;
    }

    if (this.data.checkboxGroup.length < 1) {
      wx.showModal({
        content: "请先同意并勾选协议",
        showCancel: false
      });
      return;
    }
    let queryUrl = app.getNetAddresss('plugin.yun-sign.frontend.h5.person.get-person-auth-info');
    app._postNetWork({
      url: queryUrl,
      success: (resdata) => {
        this.setData({
          step: 2
        });
        let res = resdata.data;
        if (res.result === 1) {
          this.setData({
            ['form.name']: resdata.data.name,
            ['form.tel']: resdata.data.tel
          });
        } else {
          app.tips(res.msg);
        }
      },
      fail: function (err) {
        console.log(err, "失败-----------");
      }
    });
  },

  // 第二步 ---> 进行认证按钮
  toStep() {
    if (!this.data.form.name) {
      app.tips('请先填写姓名');
      return;
    }
    if (!this.data.form.id_no) {
      app.tips('请先填写身份证号');
      return;
    }
    if (!this.data.form.tel) {
      app.tips('请先填写手机号');
      return;
    }
    if (!this.data.activeName) {
      app.tips('请先选择认证方式');
      return;
    }

    if (this.data.is_real_name) {
      // 跳转过来的实名认证
      this.setData({
        step: 3
      });
    } else {
      this.checkPersonData();
    }
  },
  checkPersonData() {
    let queryUrl = app.getNetAddresss('plugin.yun-sign.frontend.person.check-person-approve-by-idNo');
    app._getNetWork({
      url: queryUrl,
      showToastIn: true,
      data: {
        name: this.data.form.name,
        idNo: this.data.form.id_no,
        tel: this.data.form.tel,
      },
      success: (resdata) => {
        if (resdata.data.result === 1) {
          let res = resdata.data;
          this.setData({
            person: res.data
          });
          if (res.data.status_code == 99) {
            wx.showModal({
              title: '提示',
              content: '您在认证中心已经完成认证，无需重复认证',
              showCancel: false,
              success() {
                wx.navigateTo({
                  url: `/packageH/signPage/identifyResult/identifyResult?show=person`,
                });
              }
            });
          } else {
            this.setData({
              step: 3
            });
          }
        } else {
          wx.showModal({
            content: resdata.data.msg,
            showCancel: false
          });
        }
      },
      fail: function (err) {
        console.log(err, "失败-----------");
      }
    });
  },

  // 获取短信验证码
  sureIdentify() {
    if (this.data.activeName == 2 && !this.data.bank_no) {
      app.tips("请先填写银行卡");
      return;
    }

    if (this.data.is_real_name) {
      // 跳转过来的实名认证
      this.sureAuthIdentify();
      return;
    }

    let queryUrl = "";
    let json = {};
    const TIME_COUNT = 60;
    if (this.data.activeName == 1) {
      queryUrl = app.getNetAddresss("plugin.yun-sign.frontend.h5.person.auth-tel-v2");
      json = this.data.form;
    } else if (this.data.activeName == 2) {
      queryUrl = app.getNetAddresss("plugin.yun-sign.frontend.h5.person.auth-bank-card-v2");
      this.setData({
        ['form.bank_no']: this.data.bank_no
      });
      json = this.data.form;
    }
    app._postNetWork({
      url: queryUrl,
      data: json,
      success: (resdata) => {
        this.data.timer = null;
        if (resdata.data.result === 1) {
          let res = resdata.data;
          app.tips("已发送");
          this.setData({
            flow_id: res.data.data.flowId
          });
          if (!this.data.timer) {
            this.countDown = TIME_COUNT;
            this.data.timer = setInterval(() => {
              if (this.countDown > 0 && this.countDown <= TIME_COUNT) {
                this.setData({
                  count: --this.countDown
                });
              } else {
                clearInterval(this.data.timer);
                this.data.timer = null;
              }
            }, 1000);
          }
        } else {
          wx.showModal({
            title: "提示",
            content: resdata.data.msg,
            showCancel: false
          });
        }

      }
    });
  },


  // 第三步----> 立即认证按钮
  sendCode() {
    if (this.data.activeName == 2 && !this.data.bank_no) {
      app.tips("请先填写银行卡");
      return;
    }
    if (this.data.activeName != 3 && !this.data.flow_id) {
      app.tips("请先获取验证码");
      return;
    }
    console.log(this.data.authcode);
    if (this.data.activeName != 3 && !this.data.authcode) {
      app.tips("请先填写验证码");
      return;
    }
    if (this.data.activeName == 3 && !this.data.form.face_auth_mode) {
      console.log(typeof this.data.activeName, this.data.form);
      app.tips("请先选择识别方式");
      return;
    }

    if (this.data.is_real_name) {
      // 跳转过来的实名认证
      this.sendAuthCode();
    } else {
      this.sendAuthRequest();
    }
  },
  sendAuthRequest() {
    let url = "";
    let json = {};
    if (this.data.activeName == 1) {
      url = app.getNetAddresss("plugin.yun-sign.frontend.person.check-tel-sms-code");
      json = {
        flow_id: this.data.flow_id,
        authcode: this.data.authcode
      };
    } else if (this.data.activeName == 2) {
      url = app.getNetAddresss("plugin.yun-sign.frontend.person.check-bank-sms-code");
      json = {
        flow_id: this.data.flow_id,
        authcode: this.data.authcode
      };
    } else {
      url = app.getNetAddresss("plugin.yun-sign.frontend.h5.person.auth-face-v2");
      json = {
        name: this.data.form.name,
        id_no: this.data.form.id_no,
        tel: this.data.form.tel,
        face_auth_mode: this.data.form.face_auth_mode,
        callback_url: ''
      };
    }

    app._postNetWork({
      url,
      data: json,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result === 1) {
          if (this.data.activeName == 3) {
            // wx.showModal({
            //   content: "跳转h5，暂未使用web-view",
            //   cancelColor: 'cancelColor',
            // })
            // window.location.href = res.data.data.authUrl;
            wx.redirectTo({
              url: `/packageH/signPage/signPage?url=${res.data.data.authUrl}`,
            });
          } else {
            app.tips(res.msg);
            wx.redirectTo({
              url: '/packageH/signPage/identifyResult/identifyResult?show=person',
            });
          }
        } else {
          wx.showModal({
            title: "提示",
            content: resdata.data.msg,
            showCancel: false
          });
        }
      },
      fail(err) {
        app.tips(err.msg);
      }
    });
  },

  // methodes

  // 协议阅读情况
  onAgree(event) {
    this.setData({
      checkboxGroup: event.detail
    });
  },

  // 显示 popup
  showProtocol() {
    this.setData({
      protocolShow: true
    });
  },

  showAuthProtocol() {
    this.setData({
      realNameProtocolShow: true
    });
  },

  // 关闭popup
  closePopup() {
    this.setData({
      protocolShow: false,
      realNameProtocolShow: false
    });
  },

  // 表单修改
  handlerInput(event) {
    let type = event.target.dataset.type;
    this.setData({
      [`${type}`]: event.detail
    });
  },


  /**
   * 隐藏
   */
  onHide() {
    clearInterval(this.data.timer);
  }
});