import md5 from 'js-md5'
import co from 'co'
import MsgBus from '../utils/msgBus'

export default{
  data:{
    loginUser: {},
    apiurl: ''
  },
  install(Vue, options){
    Vue.prototype.MsgBus = MsgBus;
    //消息成功提示
    Vue.prototype.Success = function (msg) {
      this.$message({
        message: msg,
        duration: 2000,
        type: "success"
      });
    },
      //错误提示
      Vue.prototype.Error = function (msg) {
        this.$message({
          message: msg,
          duration: 2000,
          type: "error"
        });
      },

      //一般提示
      Vue.prototype.Info = function (msg) {
        this.$message({
          message: msg,
          duration: 2000,
          type: "info"
        });
      },
      //警告提示
      Vue.prototype.Warning = function (msg) {
        this.$message({
          message: msg,
          duration: 2000,
          type: "warning"
        });
      },
      //Confirm
      Vue.prototype.Confirm = function (msg, callback) {
        this.$confirm(msg, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            if (typeof callback === 'function') {
              callback();
            }
          })
          .catch(() => {
            this.Info("已取消操作");
          });
      },
      Vue.prototype.random_string = function (len) {
        len = len || 32;
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = chars.length;
        var pwd = '';
        for (let i = 0; i < len; i++) {
          pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
      },
    //ERP本地缓存
    Vue.prototype.md5 = md5;
    Vue.prototype.getLocalStorage = function () {
      var localStorageData = window.localStorage["loginUserInfo"];
      if (localStorageData !== undefined && localStorageData != 'undefined') {
        return JSON.parse(localStorageData).data;
      } else {
        return null;
      }
    },
     //域名管理对象
     Vue.prototype.domainManager = function () {
      let domainUrl = '';
      let mallUrl = ""; //商城API
      let locationName = window.location.hostname;
      // domainUrl = "http://127.0.0.1";
       domainUrl = "http://192.168.1.13:8083";
      //  domainUrl = "http://192.168.1.48:8015";
      //domainUrl = "http://192.168.1.21:8069";

      let javaUrldo = "";
      javaUrldo = locationName.indexOf('oytour') !== -1 || locationName.indexOf('viitto') !== -1 ? (locationName.indexOf('oytour') !== -1 ? "http://efficient.oytour.com" : "http://47.96.12.235:9001") : "http://192.168.2.215:9000";
      //商城API
      mallUrl = "http://192.168.1.21:8014";
      if (locationName.indexOf('testerp.oytour') !== -1) {
        domainUrl = "http://testapi.oytour.com";
        mallUrl = "https://mallapi.oytour.com";
      } else if (locationName.indexOf('oytour') !== -1) {
        domainUrl = "http://reborn.oytour.com";
        mallUrl = "https://mallapi.oytour.com";
      }
      var obj = {
        //主地址
        DomainUrl: domainUrl,
        //常用提交数据URL
        PostUrl: domainUrl + "/api/common/post",
        //上传文件URL
        UploadFileUrl: domainUrl + '/api/File/post',
        //本站模板文件下载地址
        LocalTemplateFileDownLoadUrl: domainUrl,
        //酒店接口
        HotelApi: "http://reborn.oytour.com/api/common/post",
        //阿里服务器地址
        AliUrl: "https://reborndev.oss-cn-hangzhou.aliyuncs.com",
        //本站文件流下载地址
        LocalFileStreamDownLoadUrl: domainUrl + "/api/file/GetFileFromWebApi",
        //PDF文件预览地址
        PDFViewUrl: domainUrl + "/plug/pdf/web/viewer.html?file=",
        //SocketUrl
        WebSocketUrl: "ws://192.168.1.110:8080?account=",
        //google地图图片地址
        GoogleMapImageUrl: "http://imgfile.oytour.com",
        //上传站点
        UploadUrl: locationName.indexOf('oytour') !== -1 || locationName.indexOf('viitto') !== -1 ? "http://upload.oytour.com" : "http://192.168.1.214:8120",
        //文件站点
        ViittoFileUrl: locationName.indexOf('oytour') !== -1 || locationName.indexOf('viitto') !== -1 ? "http://imgfile.oytour.com" : 'http://192.168.1.214:8130',
        javaUrl: locationName.indexOf('oytour') !== -1 || locationName.indexOf('viitto') !== -1 ? (locationName.indexOf('oytour') !== -1 ? "http://efficient.oytour.com" : "http://47.96.12.235:9001") : "http://192.168.2.17:8087",
        javaUrlNew: locationName.indexOf('oytour') !== -1 || locationName.indexOf('viitto') !== -1 ? (locationName.indexOf('oytour') !== -1 ? "http://property.oytour.com" : "http://47.96.12.235:9001") : "http://192.168.2.17:8087",
        //Java接口本站文件流下载地址
        JavaLocalFileStreamDownLoadUrl: javaUrldo,
        mallUrl: mallUrl,
      };
      return obj;
    },
    //下载文件
    Vue.prototype.GetLocalFile = function (cmd, msg, fileName, successCall) {
      var apiurl = this.domainManager().LocalFileStreamDownLoadUrl;
      var timestamp = (new Date()).valueOf();
      var token = "";
      var key = "";
      var tokenData={};
      var localStorage = window.localStorage["loginUserInfo"];
      if (localStorage !== undefined && localStorage != 'undefined') {
        tokenData = JSON.parse(localStorage);
      }
      token = tokenData.data.ErpToken;
      var encodeMsg = encodeURIComponent(JSON.stringify(msg)).toLowerCase();
      var md5Str = md5(`cmd=${cmd}&msg=${encodeMsg}&timestamp=${timestamp}&token=${token}&key=${key}`);
      var postData = {
        "msg": msg,
        "cmd": cmd,
        "timestamp": timestamp,
        "token": token,
        "sign": md5Str,
        "groupId":tokenData.data.Group_Id,
        "requestFrom":6
      }
      this.$http.post(apiurl, postData, {
        responseType: 'arraybuffer'
      }).then((res) => {
        let blob = new Blob([res.data], {
          type: "application/vnd.ms-excel"
        })
        let url = URL.createObjectURL(blob);
        let link = document.createElement('a');
        link.href = url;
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
        successCall(res);
      }).catch(function (res) {});
    },
    //HTTP提交数据
    Vue.prototype.apipost = function (cmd, msg, successCall, faildCall, isOnline) {
      if (msg == null || msg == "") {
        msg = {}
      }
      var token = "";
      var key = "";
      var tokenData={};
      var localStorage = window.localStorage["loginUserInfo"];
      if (localStorage !== undefined && localStorage != 'undefined') {
        tokenData = JSON.parse(localStorage);
      }
      token = tokenData.data.ErpToken;
      var timestamp = (new Date()).valueOf();
      var apiurl = this.domainManager().PostUrl;
      this.apiurl = apiurl;

      var branchId = tokenData.data.School_Id;
      var departmentId = 1;
      var departmentName = 1;
      var groupName = tokenData.data.GroupName;
      var branchName = tokenData.data.SchoolName;
      var uName = tokenData.data.AccountName;

      var encodeMsg = encodeURIComponent(JSON.stringify(msg)).toLowerCase();
      var md5Str = md5(`cmd=${cmd}&msg=${encodeMsg}&timestamp=${timestamp}&token=${token}&key=${key}`);

      var postData = {
        "msg": msg,
        "cmd": cmd,
        "timestamp": timestamp,
        "token": token,
        "sign": md5Str,
        "branchId":branchId, //公司id
        "departmentId":departmentId, //部门id
        "groupName":groupName, //集团名称
        "branchName":branchName, //公司名称
        "departmentName":departmentName, //部门名称
        "uName":uName //用户名称
      }
      this.$http.post(apiurl, postData, {
        headers: {
          'Content-Type': 'application/json',
          'Referer-Viitto': this.$route.path
        }
      })
        .then(res => {
          if (res.data.resultCode == 10000 || res.data.resultCode == 10001) {
            this.$router.push({
              path: '/login'
            });
          } else if (res.resultCode == 10005) {
            this.$router.go(-1);
          } else {
            successCall(res);
          }
        }, faildCall)
    },
      Vue.prototype.uploadFile = function (path, files, successCall) {

        if (files && files.length > 0) {
          let nameList = new Array()
          for (let index = 0; index < files.length; index++) {
            nameList.push(this.random_string());
          }
          var oss = new OSS({
            region: 'oss-cn-chengdu',
            accessKeyId: 'LTAIwE7l9dImZSa3',
            accessKeySecret: 'j47Ajn0d0WzUCIX8Biyj3P2r8QDltI',
            bucket: 'vt-im-bucket'
          })
          let that = this;
          let checkpoint = null;
          let percentage = 0;
          co(function* () {
            for (let index = 0; index < files.length; index++) {
              let fileName = nameList[index]

              fileName = "/New" + path + fileName + "." + files[index].name.split('.').pop()
              var result = yield oss.multipartUpload(fileName, files[index], {
                progress: function* (p) {},
                mime: 'application/octet-stream'
              })
              successCall(result);
            }
          }).catch(function (err) {

          });
        }
      },

      //价钱格式化，三位数逗号分隔，保留两位小数   duanjun
      Vue.prototype.moneyFormat = function (value) {
        let nStr = Number(value).toFixed(2)
        nStr += '';
        let x = nStr.split('.');
        let x1 = x[0];
        let x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
          x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
      },
      //验证只能输入整数【负数：isMinus传true】
      Vue.prototype.checkInteger = function (item, filed, isMinus) {
        var value = "" + item[filed]; //转字符串
        var t = value.charAt(0);
        value = value.replace(this.$commonUtils.Regex.isInteger, "");
        //是否允许负数
        if (isMinus && t == '-') {
          value = '-' + value;
        }
        item[filed] = value;
      },
      //验证只能输入2位小数【负数：isMinus传true】
      Vue.prototype.checkPrice = function (item, filed, isMinus) {
        var value = "" + item[filed]; //转字符串
        var t = value.charAt(0);
        value = value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
        value = value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
        value = value
          .replace(".", "$#$")
          .replace(/\./g, "")
          .replace("$#$", ".");
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
        //如果第一位是负号，则允许添加   如果不允许添加负号 可以把这块注释掉
        //是否允许负数
        if (isMinus && t == '-') {
          value = '-' + value;
        }
        item[filed] = value;
      },
      //用户权限验证
      Vue.prototype.CheckUserAuth = function (authCode, successCall, faildCall) {
        let localStorageJson = this.getLocalStorage();
        var newCode = ',' + authCode + ',';
        if (("," + localStorageJson.ActionMenuCode + ",").indexOf(newCode) > -1) {
          var data = {
            resultCode: 1,
            data: 1,
          };
          var res = {
            data: data
          }
          successCall(res);
        } else {
          this.apipost("userauth_get_GetCheckUserAuthService", {
            actionMenuCode: authCode
          }, successCall, faildCall);
        }
      },
      Vue.prototype.QjGroupId = function (msg) {
        let GroupId = 2;
        return GroupId;
      },
      Vue.prototype.orderBy = function (source, orders, type) {
        if (
          source instanceof Array &&
          orders instanceof Array &&
          orders.length > 0
        ) {
          var ordersc = orders.concat([]);
          var sorttype = type || "asc";
          var results = [];
          var totalSum = {};

          function grouporder(source, orders, totalSum) {
            source.sort(function (a, b) {
              var convertA = a[orders[0]];
              var convertB = b[orders[0]];
              if (typeof convertA == "string" && typeof convertB == "string") {
                if (sorttype.toUpperCase() == "ASC") {
                  return convertA.localeCompare(convertB);
                } else {
                  return convertB.localeCompare(convertA);
                }
              } else {
                if (sorttype.toUpperCase() == "ASC") {
                  return convertA - convertB;
                } else {
                  return convertB - convertA;
                }
              }
            });
            var groupmap = new Map();
            source.forEach(item => {
              if (groupmap.has(item[orders[0]])) {
                groupmap.get(item[orders[0]]).push(item);
              } else {
                groupmap.set(item[orders[0]], []);
                groupmap.get(item[orders[0]]).push(item);
              }
            });
            orders.shift();
            for (let [key, val] of groupmap) {
              totalSum[key] = {};
              totalSum[key].name = key;
              totalSum[key].value = val.length;
              if (orders.length == 0) {
                results = results.concat(val);
              } else {
                totalSum[key].children = {};
                var orderscopy = orders.concat([]);
                grouporder(val, orderscopy, totalSum[key].children);
              }
            }
          }
          grouporder(source, ordersc, totalSum);
          return {
            results: results,
            totalSum: totalSum
          };
        } else {
          return source;
        }
      },
      //PDF预览
      Vue.prototype.previewPDF = function (url) {
        window.open(url);
      }

  }
}
