var app = new Vue({
  el: "#app",
  data: function () {
    let checkField = (rule, value, callback) => {
      console.log(this.apiInfo.form_field);
      if (rule.field == "idName") {
        if (!value) {
          return callback(new Error('请输入真实姓名'));
        } else {
          callback();
        }
      }
      if (rule.field == "idNo") {
        if (!value) {
          return callback(new Error('请输入身份证号'));
        } else {
          callback();
        }
      }
      if (this.apiInfo.form_field.mobile && rule.field == "mobile") {
        if (!value) {
          return callback(new Error('请输入手机号'));
        } else {
          callback();
        }
      }
      if (this.apiInfo.form_field.bankNo && rule.field == "bankNo") {
        if (!value) {
          return callback(new Error('请输入银行卡号'));
        } else {
          callback();
        }
      }
      callback();
    };
    return {
      isaggree: false,
      companyName: "",
      btnloading: true,
      wxAppId:"wxf616c0a459d66081",
      isIdNameEdit: true,
      isIdNoEdit: true,
      code: "",
      state: "",
      openId: "",
      companyId:"",
      wxuser: {},
      apiInfo: {form_field:{}},
      params: {},
      rules: {
        idNo: [
          { validator: checkField, trigger: 'blur' }
        ],
        idName: [
          { validator: checkField, trigger: 'blur' }
        ],
        mobile: [
          { validator: checkField, trigger: 'blur' }
        ],
        bankNo: [
          { validator: checkField, trigger: 'blur' }
        ],
      },
    }
  },
  created: function () {
  },
  mounted: function () {
    let self = this;
    let url = window.location.href;
    // 微信返回参数
    this.code = this.getUrlParam("code") || "";
    this.state = this.getUrlParam("state") || "";

    if(this.code) {
      let rparams = localStorage.getItem("requestParams");
      if (!rparams) {
        alert("请求失败，请刷新重试");
        return;
      }
      console.log(rparams, "-----------------------2");
      this.params = JSON.parse(rparams);

      $("#loading").fadeOut();
      // api信息
      this.getApiInfo();
      // 获取openId
      this.getOpenId();
    } else {
      // 第一次请求参数
      localStorage.removeItem("requestParams");
      this.params.appId = this.getUrlParam("appId");
      this.params.ecid = this.getUrlParam("ecid");
      this.params.sign = this.getUrlParam("sign");
      this.params.userId = this.getUrlParam("userId");
      this.params.nonceStr = this.getUrlParam("nonceStr");
      this.params.idName = decodeURIComponent(this.getUrlParam("idName"));
      this.params.idNo = this.getUrlParam("idNo");
      this.params.mobile = this.getUrlParam("mobile");
      this.params.bankNo = this.getUrlParam("bankNo");
      localStorage.setItem("requestParams", JSON.stringify(this.params));
      this.getApiInfo();
      console.log(this.params, "-----------------------");
      self.$root.postReq("/web/cwxsignapiCtl/checkSign", {
        params: this.params,
      }).then(rd => {
        if (rd.status == 0) {
          url = url.split("?")[0];
          // url = "https://bpohhr.gongsibao.com/bpoproxy";
          // http://127.0.0.1:3333/wxsign?comid=10172&userCode=100018&nonceStr=nonceStrnonceStr&sign=E47D90EA49DCB7E9114A27767DCBF3C2
          let redirect_uri = encodeURIComponent(url);
          let wxAppId = this.wxAppId;
          let wxurl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wxAppId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=1#wechat_redirect`;
          window.location.href = wxurl;
          console.log(wxurl);
        } else {
          alert(rd.msg || "签名失败，请关闭该页重试");
        }
      });
    }
  },

  methods: {
    postReq(path, data) {
      return axios.post(path, data).then(function (r) {
        return r.data ? r.data : null;
      })
    },
    getApiInfo() {
      let self = this;
      this.$root.postReq("/web/cwxsignapiCtl/getApiInfo", {
        params: this.params
      }).then(rd => {
        if (rd.status == 0) {
          self.apiInfo = rd.data || {};

        } else {
          self.$message.error(rd.msg || "api配置错误");
        }
      });
    },
    getOpenId() {
      let self = this;
      if(self.params.openId) {
        return;
      }
      //调用接口,根据用户名判断是否协议
      this.$root.postReq("/web/wxCtl/wxuseropenid", {
        code: self.code
      }).then(rd => {
        if (rd.status == 0) {
          self.params.openId = rd.data;
          self.btnloading = false;
        } else {
          self.$message.error(`获取openId失败，请退出重试`);
        }
      });
    },
    getUrlParam(name) {
      let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      let r = window.location.search.substr(1).match(reg);
      return r ? unescape(r[2]) : "";
    },
    showaggreement() {
      // window.location.href = "https://bpohhr.gongsibao.com/bpowxsignaggreement.js";
      if (this.apiInfo.app_type == 1) {
        let p = {
          companyName: this.apiInfo.companyName || "",
          addr: this.apiInfo.addr || "",
          phone: this.apiInfo.phone || "",
          idName: this.params.idName || "",
          mobile: this.params.mobile || "",
        };
        localStorage.setItem("aggreement_params", JSON.stringify(p));
        window.location.href = "https://bpohhr.gongsibao.com/bpowxsignaggreement2";
      } else {
        let p = {
          nameA: this.apiInfo.companyName,
          name: this.params.idName || ""
        };
        localStorage.setItem("aggreement_params", JSON.stringify(p));
        window.location.href = "https://bpohhr.gongsibao.com/bpowxsignaggreement3";
      }
    },
    subform() {
      let msg;
      self.btnloading = true;
      if (this.apiInfo.app_type != 0) {
        msg = "提交信息后，会进行静默签约《薪必果分包协议》，是否同意？";
      } else {
        msg = "确定提交信息？";
      }
      if(confirm(msg)){
        this.save();
      } else {
        self.btnloading = false;
      }
    },
    save() {
      let self = this;
      if(!self.params.openId) {
        self.$message.error(`获取openId失败，请刷新重试`);
        return;
      }
      self.btnloading = true;
      self.$refs['userform'].validate((valid) => {
        console.log(valid);
        if (valid) {
            //处理登录逻辑
            self.$root.postReq("/web/cwxsignapiCtl/saveSign", {params: self.params}).then(function(d){
              console.log(d);
              if(d.status==0) {
                self.$message.success("保存成功");
                if (d.data.redirectUrl) {
                  window.location.href = d.data.redirectUrl;
                }
              } else {
                self.$message.warning(d.msg || "登录失败, 请稍候重试");
              }
              self.btnloading = false;
            });
        } else {
          self.btnloading = false;
          return false;
        }
      });
    },
    patnerValid() {
      // var self = this;
      // //调用接口,根据用户名判断是否协议
      // this.$root.postReq("/web/userCtl/patnerValid", {
      //   userName: self.loginForm.userName
      // }).then(rd => {
      //   self.showAggree = false;
      //   if (rd.status == 0) {
      //     if (rd.data == "1") {
      //       self.showAggree = true;
      //     }
      //   }
      // });
    },
  },
});