var app = new Vue({
  el: "#app",
  data: function () {

    var validmethod = (rule, value, callback) => {
      if (rule.field == "id_name") {
        if (!value) {
          return callback(new Error('请输入真实姓名'));
        } else {
          callback();
        }
      }
      if (rule.field == "id_no") {
        if (!value) {
          return callback(new Error('请输入身份证号'));
        } else {
          callback();
        }
      } else {
        if (!value) {
          return callback(new Error('请输入密码'));
        }
        callback();
      }
    };
    return {
      isaggree: false,
      companyName: "",
      btnloading: true,
      appid:"wxf616c0a459d66081",
      isIdNameEdit: true,
      isIdNoEdit: true,
      code: "",
      state: "",
      openId: "",
      companyId:"",
      wxuser: {},
      rules: {
        id_no: [
          { validator: validmethod, trigger: 'blur' }
        ],
        id_name: [
          { validator: validmethod, trigger: 'blur' }
        ],
      },
    }
  },
  created: function () {
  },
  mounted: function () {
    var self = this;
    var url = window.location.href;
    this.code = this.getUrlParam("code") || "";
    this.state = this.getUrlParam("state") || "";
    var nonceStr = this.getUrlParam("nonceStr") || "";
    var userCode = this.getUrlParam("userCode") || "";
    var sign = this.getUrlParam("sign") || "";

    this.companyId = this.getUrlParam("comid") || this.state;
    console.log(url, this.code, this.state, this.companyId, "------------------");

    var idName = decodeURI(this.getUrlParam("idName") || "");
    var idNo = this.getUrlParam("idNo") || "";
    // %E5%BC%A0%E8%A1%8C%E8%89%AF
    if(this.code) {
      if(!idNo) {
        idNo = localStorage.getItem("idNo");
        if(idNo) {
          this.wxuser.id_no = idNo;
          this.isIdNoEdit = false;
        }
      }

      if(!idName) {
        idName = localStorage.getItem("idName");
        if(idName) {
          this.wxuser.id_name = idName;
          this.isIdNameEdit = false;
        }
      }
      if(!userCode) {
        this.wxuser.userCode = localStorage.getItem("userCode") || "";
      }
      console.log(idName, idNo, "-----------------------2");

      $("#loading").fadeOut();
      // TODO 获取openId
      this.getCompany();
      this.getOpenId();
    } else {
      console.log(idName, idNo, "-----------------------1");
      self.$root.postReq("/web/ecompanywxuserCtl/validateSign", {
        companyId: self.companyId,
        nonceStr: nonceStr,
        userCode: userCode,
        sign: sign,
      }).then(rd => {
        if (rd.status == 0) {
          localStorage.removeItem("idName");
          localStorage.removeItem("idNo");
          localStorage.removeItem("userCode");
          if(idName) {
            localStorage.setItem("idName", idName);
          }
          if(idNo) {
            localStorage.setItem("idNo", idNo);
          }
          if(userCode) {
            localStorage.setItem("userCode", userCode);
          }
    
          url = url.split("?")[0];
          // url = "https://bpohhr.gongsibao.com/bpoproxy"
          // http://192.168.18.125:3000/wxsign?comid=10172&userCode=100018&nonceStr=nonceStrnonceStr&sign=E47D90EA49DCB7E9114A27767DCBF3C2
          var redirect_uri = encodeURIComponent(url);
          var appkey = this.appid;
          var wxurl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appkey}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${this.companyId}#wechat_redirect`;
          window.location.href = wxurl;
        } else {
          alert("签名失败，请关闭该页重试");
        }
      });
    }
  },

  methods: {
    postReq(path, data) {
      return axios.post(path, data).then(function (r) {
        return r.data ? r.data : null;
      })
    },
    getCompany() {
      this.$root.postReq("/web/ecompanywxuserCtl/companyName", {
        companyId: this.companyId
      }).then(rd => {
        if (rd.status == 0) {
          self.companyName = rd.data;
          $("#companyTitle").text(self.companyName || "公司错误");
        } else {
          self.$message.error(`公司不存在`);
        }
      });
    },
    getOpenId() {
      var self = this;
      if(self.openId) {
        return;
      }
      //调用接口,根据用户名判断是否协议
      this.$root.postReq("/web/wxCtl/wxuseropenid", {
        code: self.code
      }).then(rd => {
        if (rd.status == 0) {
          self.openId = rd.data;
          self.btnloading = false;
        } else {
          self.$message.error(`获取openId失败，请退出重试`);
        }
      });
    },
    getUrlParam(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      return r ? unescape(r[2]) : null;
    },
    btnclick: function (pfm, code) {
    },
    showaggreement() {
      window.location.href = "https://bpohhr.gongsibao.com/wxsignaggreement?comid=" + this.companyId;
    },
    save() {
      var self = this;
      if(!self.openId) {
        self.$message.error(`获取openId失败，请刷新重试`);
        return;
      }
      self.btnloading = true;

      self.wxuser.openId = self.openId;
      self.wxuser.code = self.code;
      self.wxuser.ecompany_id = self.companyId;
      self.$refs['wxuserform'].validate((valid) => {
        console.log(valid);
        if (valid) {
            //处理登录逻辑
            self.$root.postReq("/web/ecompanywxuserCtl/saveuser", self.wxuser).then(function(d){
              if(d.status==0) {
                self.$message.success("保存成功");
              } 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;
      //     }
      //   }
      // });
    },
  },
});