import { isUndefined } from "util";
import Qs from 'qs'
import _ from 'lodash'
import { Loading } from 'element-ui';
import crypto from 'crypto';

export default {
  install (Vue) {
    Vue.prototype.updateStdReg = function (StdReg) {
      this.$store.commit("updateStdReg", {
        StdReg : StdReg
      });
    }

    Vue.prototype.updateStdMajor = function (stdMajor) {
      this.$store.commit("updateStdMajor", {
        StdMajor : stdMajor
      });
    }

    
    //初始化数据
    Vue.prototype.initData =  function(func){
     return new Promise(async resolve => {
        let _this = this;
        this.$http.post(
          "/enrol/gobal/std/init.htm",
          {},
        ).then((res)=>{
          console.log("0");
          _this.$store.commit("updateInitData", {
              StdReg: res.data.map.StdReg,
              StdImageArray: res.data.map.StdImageArray,
              FrameParamArray: res.data.map.FrameParamArray,
            });

            _this.$store.commit("updateIsUserRegisted", {
              isUserRegisted: true
            });

            // _this.initIsEnroled();



            // _.forEach(res.data.map.FrameParamArray ,(item)=>{
            //   if(item.param_name == 'WeiXinAppId'){
            //     window.WeiXinAppId = item.param_value
            //   }
            //   if(item.param_name == 'WeiXinUrl'){
            //     window.WeiXinUrl = item.param_value
            //   }          
            // })
            if(!isUndefined(func)){
              func.call(this);
            }
            resolve(res.data);
        });
      })
    }   

    Vue.prototype.initIsEnroled =  function(isEnroled){
      this.$store.commit("updateIsEnroled", {
              isEnroled: isEnroled
        });
      // return new Promise(async resolve => {
      //   let _this = this;
      //   this.$http.post(
      //     "/std/stdEnrol/existStdEnrolPayed.htm",
      //     {},
      //   ).then((res)=>{
      //     _this.$store.commit("updateIsEnroled", {
      //       isEnroled: res.data.entity
      //     });
      //   });
      // })
    }

    Vue.prototype.initCertNoMustUpdate =  function(cert_no_must_update){
      this.$store.commit("initCertNoMustUpdate", {
        cert_no_must_update: cert_no_must_update
        });
    }


    Vue.prototype.initLoginData =  function(func){
     let loading =  this.showLoading("初始化数据加载中...");
     return new Promise(async resolve => {
        let _this = this;
        this.$http.post(
          "/std/stdRegInfo/init.htm",
          {},
        ).then((res)=>{
           // 考生没有设置密保或者没有手机号码，跳转设置密码页面
            let isBindPhoneOrSetQuestion = res.data.map.isBindPhoneOrSetQuestion;
            if(isBindPhoneOrSetQuestion == '0'){
              window.location.href = './login/phone.html';
              return;
            }

            let std_report_form = res.data.map.std_report_form;
            if(std_report_form == 'true'){
              window.location.href = './login/reportform.html';
              return;
            }

          if(res.data.map.config.uploadServerUrl) 
            window.uploadServerUrl = res.data.map.config.uploadServerUrl;
          
          if(res.data.map.config.photoHttp) {
            window.photoHttp = res.data.map.config.photoHttp;
          }
           
          if(res.data.map.config.isRemotePhoto) {
            window.isRemotePhoto = res.data.map.config.isRemotePhoto;
          }

            let stdReg = res.data.map.stdRegInfo;

            //如果是新注册 未完善信息用户 或导入状态
            if(stdReg.status === 0 || stdReg.status === 1){
              let def= {
                std_source:"",
                std_eng_name: "",
                political_status: "",
                std_nation: "",
                std_family_reg: "",
                school_id: "",
                std_edu: "",
                std_occupation: "",
                std_healthy: "",
                std_birth: "",
                major_id: "",
                major_code: "",
                major_name: "",
                std_mobile: "",
                std_postcode: "",
                std_address: "",
                email: "",
                remark: "",
              }
              
              // _.assignIn(stdReg,def);
              function customizer(objValue, srcValue) {
                return _.isUndefined(objValue) ? srcValue : objValue;
              }
               
              var defaults = _.partialRight(_.assignInWith, customizer);
              defaults(stdReg,def);

              this.goUrl("/personalInfo");
            }
             
          _this.$store.commit("updateInitData", {
              StdReg: stdReg,
              dict: res.data.map.dict,
              StdMajor: res.data.map.stdMajor,
            });

            _this.$store.commit("updateIsUserRegisted", {
              isUserRegisted: true
            });

            let payedList =  _this.$options.filters["dataArrayFilter"](this.courseList, {
              fee_status: 1
            });
            if(payedList.length >0){
              _this.$store.commit("updateIsEnroled",{isEnroled:true});
            }

            //  _this.initIsEnroled();


            // _.forEach(res.data.map.FrameParamArray ,(item)=>{
            //   if(item.param_name == 'WeiXinAppId'){
            //     window.WeiXinAppId = item.param_value
            //   }
            //   if(item.param_name == 'WeiXinUrl'){
            //     window.WeiXinUrl = item.param_value
            //   }          
            // })
            if(!isUndefined(func)){
              func.call(this);
            }
            this.hideLoading(loading)
            resolve(res.data);
        });
      })
    }   

    //更新登录状态
    Vue.prototype.updateUserRegistedStatus = function(isUserRegisted){
      this.$store.commit("updateIsUserRegisted", {
        isUserRegisted: _.isUndefined(isUserRegisted)?true:isUserRegisted
      });
    }    
  
    /// 通用方法
    Vue.prototype.goUrl = function(url){
      this.$router.push(url);
    }

    Vue.prototype.go = function(obj){
      this.$router.push(obj);
    }

    Vue.prototype.showLoading = function(text){
      return Loading.service({ fullscreen: true,text:text || "数据加载中.." });
    }
    
    Vue.prototype.hideLoading = function(loading){
      this.$nextTick(() => { 
        loading.close();
      });
    }

    Vue.prototype.confirm = function(text,title,func){
      this.$confirm(text, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if(func && func.confirm){
          func.confirm.apply(this,[]);
        }
      }).catch(() => {
        if(func && func.cancel){
          func.cancel.apply(this,[]);
        }
      })
    }

    Vue.prototype.message = function(type , msg){
      this.$message({
        type: type,
        message: msg
      });     
    } 

    Vue.prototype.alert = function(text,title ='信息提示',options){
      this.$alert(text, title, options)
    }  
    
    Vue.prototype.Qs = Qs;

    Vue.prototype.formatDataTime = function(write){
      var res = this.shortDateString(write.exam_start_time) + " " + this.shortMinuteString(write.exam_start_time);
      if (write.exam_start_time != write.exam_end_time)
        res += "-" + this.shortMinuteString(write.exam_end_time);
      else
        res += " 开考";
      return res;
    }

    Vue.prototype.shortDateString = function(date){
      if (date == undefined)
        return "";
      if (_.isDate(date))
        date = date.toJSON();
      if (date.length > 10)
        return date.substr(0, 10);
      return date;
    }

    Vue.prototype.shortMinuteString = function(date){
      if (date == undefined)
        return "";
      if (_.isDate(date))
        date = date.toJSON();
      if (date.length > 10)
        return date.substr(11, 5);
      return date;
    }

    //数据字典转换
    Vue.prototype.transConfigData = function(array){
      let newArray = [];
      array.forEach(element => {
        newArray.push({
          name: element.dict_text,
          value: element.dict_value,
        })
      });
      return newArray;
    }  
 
    Vue.prototype.wxUploadStdImage = function(img,fn){
      let _this = this;
      let wx = this.$wechat;
      wx.chooseImage({
        count : 1, // 默认9
        sizeType : [ 'compressed' ], // 可以指定是原图还是压缩图，默认二者都有'original',
        sourceType : [ 'album', 'camera' ], // 可以指定来源是相册还是相机，默认二者都有
        success : function(res) {
          var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
          wx.uploadImage({
            localId : localIds[0], // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips : 1, // 默认为1，显示进度提示
            success : function(serverRes) {
              var serverId = serverRes.serverId; // 返回图片的服务器端ID
              console.log(`serverId:`+ serverId);                
              //显示loading
              _this.showLoading("上传中...");
              //请求服务保存图片信息
              _this.$http.post(
                "/enrol/wx/std/image/upload.htm",
                _this.Qs.stringify({
                  std_id : _this.StdReg.std_id,
                  media_id : serverId,
                  type : img.image_type
                }),
                _this.$http.headers.FORM
              ).then((res)=>{
                _this.hideLoading();
                if(res.data.errorMsg){
                  _this.alert(res.data.errorMsg);
                  return;
                }
                if (fn)
                  fn.call();              
              });

            }
          })
        }
      });

    }

    Vue.prototype.find = function(obj,array){
      if(!array) return {};
      return _.find(array, obj);
    };

    Vue.prototype.findDict = function(array,value){
      let dict = array.find(
        e => parseInt(e.dict_value) == parseInt(value) || e.dict_value + "" == value + ""
      );
      return dict?dict.dict_text:"";
    },

    Vue.prototype.md5 = function(valte){
      var md5 = crypto.createHash('md5');
      return md5.update(valte).digest('hex');
    }

  }
}
