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

    var validmethod = (rule, value, callback) => {
      if (rule.field == "id_no") {
        if (!value || !value.trim()) {
          return callback(new Error('请输入身份证号'));
        }
      }

      if (rule.field == "front_half_img") {
        if (!value || !value.trim()) {
          return callback(new Error('请上传法人半身照'));
        }
      }

      if (rule.field == "declaration_file") {
        if (!value || !value.trim()) {
          return callback(new Error('请上传声明书'));
        }
      }
      return callback();
    };
    return {
      btnloading: false,
      uploadLoading: null,
      action: "",
      d:{},
      supportInfo: {
        id_no: "",
        front_half_img: "",
        declaration_file: ""
      },
      rules: {
        id_no: [
          { validator: validmethod, trigger: 'blur' }
        ],
        front_half_img: [
          { validator: validmethod, trigger: 'blur' }
        ],
        declaration_file: [
          { validator: validmethod, trigger: 'blur' }
        ],
      },
    }
  },
  created: function () {
  },
  mounted: function () {
    this.getOC();
    $("#loading").fadeOut();
  },

  methods: {
    postReq(path, data) {
      return axios.post(path, data).then(function (r) {
        return r.data ? r.data : null;
      })
    },
    getOC() {
      let self = this;
      this.$root.postReq("/applet/xggApplet/oc", "").then(function (d) {
        d = d.data;
        self.d["key"] = "key";
        self.d["Bucket"] = d.Bucket;
        self.d["OSSAccessKeyId"] = d.OSSAccessKeyId;
        self.d["Signature"] = d.Signature;
        self.d["policy"] = d.policy;
        self.d["success_action_status"] = d.success_action_status;
        self.action = d.url;
        console.log('---------------------------', self.action);
      });
    },

    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) {
    },
    frontHalfImgSuccess(res, file) {
      console.log(res)
      let xml = this.loadXML(res);
      let ossUrl = xml.documentElement.getElementsByTagName("Location")[0].textContent;
      this.supportInfo.front_half_img = ossUrl || "";
      this.uploadLoading.close();
      console.log(xml, ossUrl);
    },
    declarationFileSuccess(res, file) {
      console.log(res)
      let xml = this.loadXML(res);
      let ossUrl = xml.documentElement.getElementsByTagName("Location")[0].textContent;
      this.supportInfo.declaration_file = ossUrl || "";
      this.uploadLoading.close();
      console.log(xml, ossUrl);
    },
    beforeAvatarUpload(file) {
      console.log(file);
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 20MB!');
        return false;
      }

      let ext = ".png";
      let fileNameArr = (file.name || "").split(".");
      if (fileNameArr.length > 1) {
        let fext = fileNameArr.pop().toLowerCase();
        ext = !fext ? ext : `.${fext}`;
      }
      console.log(ext);
      var key = "zc_gth_hc_" + new Date().getTime() + this.randomString(8) + ext;
      this.d.key = key;
      this.uploadLoading = this.$loading({
        lock: true,
        text: '正在上传中，请耐心等待',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      setTimeout(() => {
        this.uploadLoading.close();
      }, 15000);

      return true;
    },
    uploadError(err, file, fileList){
      this.uploadLoading.close();
    },

randomString(len) {
      len = len || 32;
      let chars = '0123456789abcdefghijklmnopqrstuvwxyz_';
      let maxPos = chars.length;
      let arr = [];
      for (i = 0; i < len; i++) {
        arr.push(chars.charAt(Math.floor(Math.random() * maxPos)));
      }
      return arr.join("");
    },
    save() {
      var self = this;
      self.btnloading = true;
      self.$refs['supportForm'].validate((valid) => {
        console.log(valid);
        if (valid) {
          console.log(self.supportInfo);
            //处理登录逻辑
            self.$root.postReq("/applet/xggApplet/supplement", self.supportInfo).then(function(d){
              console.log(d);
              if (d.code == 1) {
                self.$message.success("保存成功");
              } else {
                self.$message.warning(d.msg || "保存失败, 请稍候重试");
              }
              self.btnloading = false;
            });
        } else {
          self.btnloading = false;
          return false;
        }
      });
    },
    loadXML(xmlString){
      var xmlDoc=null;
      if(!window.DOMParser && window.ActiveXObject){
        var xmlDomVersions = ['MSXML.2.DOMDocument.6.0','MSXML.2.DOMDocument.3.0','Microsoft.XMLDOM'];
        for(var i=0;i<xmlDomVersions.length;i++){
          try{
            xmlDoc = new ActiveXObject(xmlDomVersions[i]);
            xmlDoc.async = false;
            xmlDoc.loadXML(xmlString);
            break;
          }catch(e){
          }
        }
      }
      else if(window.DOMParser && document.implementation && document.implementation.createDocument){
        try{
          domParser = new  DOMParser();
          xmlDoc = domParser.parseFromString(xmlString, 'text/xml');
        }catch(e){
        }
      }
      else{
        return null;
      }
      return xmlDoc;
    },
    patnerValid() {
    },
  },
});