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;
      },
      Vue.prototype.md5 = md5;
    //ERP本地缓存
    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 = 'http://192.168.20.9:8083';
        let viewFileUrl = 'http://192.168.1.36:8120';
        let locationName = window.location.hostname;
        if (locationName.indexOf('testerp.oytour') !== -1) {
          domainUrl = "http://testapi.oytour.com";
          viewFileUrl="http://upload.oytour.com";
        } else if (locationName.indexOf('oytour') !== -1) {
          domainUrl = "http://reborn.oytour.com";
          viewFileUrl="http://upload.oytour.com";
        }
        var obj = {
          //主地址
          DomainUrl: domainUrl,
          //常用提交数据URL
          PostUrl: domainUrl + "/api/common/post",
          //上传文件URL
          UploadFileUrl: domainUrl + '/api/File/post',
          //本站模板文件下载地址
          LocalTemplateFileDownLoadUrl: domainUrl,
          //本站文件流下载地址
          LocalFileStreamDownLoadUrl: domainUrl + "/api/file/GetFileFromWebApi",
          //文件预览地址
          ViewFileUrl:viewFileUrl
        };
        return obj;
      },

      //ERP系统文件下载
      Vue.prototype.GetErpLocalFile = 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)
      },

      //价钱格式化，三位数逗号分隔，保留两位小数   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.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);
      },
      //新页面打开页面
      Vue.prototype.OpenNewUrl = function (path, queryObj) {
        var newUrl = this.$router.resolve({
          path: path,
          query: queryObj
        });
        window.open(newUrl.href, '_blank');
      }
  }
}
