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.24';
        let domainUrl = 'http://192.168.20.51:8082';
        let viewFileUrl = 'http://192.168.20.214:8120';
        let mallUrl = "http://192.168.20.17:8014";
        // let vtUploadUrl = "http://192.168.20.214:8120";
        let vtUploadUrl = "http://upload.oytour.com";
        let vtViewUrl = "http://192.168.20.214:8130";
        let locationName = window.location.hostname;
        if (locationName.indexOf('testerp.oytour') !== -1) {
          domainUrl = "http://testapi.oytour.com";
          viewFileUrl = "http://upload.oytour.com";
          mallUrl = "https://mallapi.oytour.com";
          vtUploadUrl = "http://upload.oytour.com";
          vtViewUrl = "https://imgfile.oytour.com";
        } else if (locationName.indexOf('oytour') !== -1) {
          domainUrl = "http://reborn.oytour.com";
          viewFileUrl = "http://upload.oytour.com";
          mallUrl = "https://mallapi.oytour.com";
          vtUploadUrl = "http://upload.oytour.com";
          vtViewUrl = "https://imgfile.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,
          mallUrl: mallUrl,
          VTUploadUrl: vtUploadUrl,
          vtViewUrl: vtViewUrl
        };
        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)
      },
      //HTTP提交数据-电商
      Vue.prototype.GetPostDataDS = function (cmd, msg, newCmd) {
        if (msg == null || msg == "") {
          msg = {}
        }
        var timestamp = (new Date()).valueOf();
        var token = "";
        var key = "";
        var JHMallBaseId = 1;
        var JHTenantId = 1;
        if (this.getLocalStorage() != null) {
          token = this.getLocalStorage().MallToken;
          // key = this.getLocalStorage().SecretKey;
          JHMallBaseId = this.getLocalStorage().JHMallBaseId;
          JHTenantId = this.getLocalStorage().JHTenantId;
        }
        // var MallBaseId = 1; //小程序ID
        // var TenantId = 1; //商户Id
        var encodeMsg = encodeURIComponent(JSON.stringify(msg)).toLowerCase();
        var md5Str = md5(`cmd=${cmd}&msg=${encodeMsg}&timestamp=${timestamp}&token=${token}&key=${key}`);
        let tempLanguage = 0;
        if (localStorage.language && localStorage.language != '') {
          if (localStorage.language == "zh-TW") {
            tempLanguage = 1;
          } else if (localStorage.language == "Japanese") {
            tempLanguage = 2;
          }
        }
        var cmdStr = "";
        if (newCmd) {
          cmdStr = newCmd;
        }
        var postData = {
          msg: msg,
          timestamp: timestamp,
          token: token,
          sign: md5Str,
          languageId: tempLanguage,
          cmd: cmdStr,
          MallBaseId: JHMallBaseId,
          TenantId: JHTenantId,
        }
        return postData
      },
      //HTTP提交数据-电商
      Vue.prototype.apipostDS = function (cmd, msg, successCall, faildCall) {
        var apiurl = this.domainManager().mallUrl + cmd;
        var postData = this.GetPostDataDS(cmd, msg, "");
        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) { } else if (res.resultCode == 10005) {
              this.$router.go(-1);
            } else {
              successCall(res);
            }
          }, faildCall)
      }
    //电商文件下载
    Vue.prototype.GetLocalFileDS = function (cmd, msg, fileName, newCmd, successCall) {
      var apiurl = this.domainManager().mallUrl + cmd;
      var postData = this.GetPostDataDS(cmd, msg, newCmd);
      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) { });
    },
      //价钱格式化，三位数逗号分隔，保留两位小数   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');
      },
      //文件类型数组
      Vue.prototype.FileType = function () {
        var fileTypeJson = {
          //主地址npm
          UserImg: "User", //用户相图片
          //常用提交数据URL
          GoodsImg: "Goods", //素材相关文件
          SetImg: "Set", //用户相图片
          Video: "Video", //视频
        };
        return fileTypeJson;
      },
      //上传文件到云存储
      Vue.prototype.UploadFileToTencent = function (path, fileObj, callback) {
        // debugger;
        var upInfo = JSON.parse(localStorage.uploadInfo);

        let maxSize = 500 * 1024
        if ((fileObj.type == "image/png" || fileObj.type == "image/jpeg") && fileObj.size > maxSize) {
          let that = this
          lrz(fileObj, {
            width: 750,
            quality: 0.8
          })
            .then(function (rst) {
              //成功时执行
              var arr = rst.base64.split(',');
              var mime = arr[0].match(/:(.*?);/)[1];
              var bstr = atob(arr[1]);
              var n = bstr.length;
              var u8arr = new Uint8Array(n);
              while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
              }
              var newFile = new File([u8arr], fileObj.name, {
                type: mime
              });

              if (upInfo && upInfo.IsDefault == 1) {
                if (upInfo.StoreType == 1) {
                  that.uploadStart(path, newFile, callback)
                }
                if (upInfo.StoreType == 2) {
                  that.uploadToAli(path, newFile, callback)
                }
              } else {
                that.Error('请先配置上传');
              }
            }).catch(function (error) {
              if (upInfo && upInfo.IsDefault == 1) {
                if (upInfo.StoreType == 1) {
                  that.uploadStart(path, fileObj, callback)
                }
                if (upInfo.StoreType == 2) {
                  that.uploadToAli(path, fileObj, callback)
                }
              } else {
                that.Error('请先配置上传');
              }
            }).always(function () {
              //不管成功或失败，都会执行
            })
        } else {
          if (upInfo && upInfo.IsDefault == 1) {
            if (upInfo.StoreType == 1) {
              this.uploadStart(path, fileObj, callback)
            }
            if (upInfo.StoreType == 2) {
              this.uploadToAli(path, fileObj, callback)
            }
          } else {
            this.Error('请先配置上传');
          }
        }
      },
      Vue.prototype.uploadStart = function (path, fileObj, callback) {
        let that = this
        var upInfo = JSON.parse(localStorage.uploadInfo);
        //获取文件扩展名
        var filename = fileObj.name;
        var index = filename.lastIndexOf(".");
        var suffix = filename.substr(index);
        var timestamp1 = Date.parse(new Date()) + "_" + (Math.ceil(Math.random() * 1000));
        let str = '';
        if (this.isOnline()) {
          str = "/Test"
        }
        var newFileName = str + '/Upload/' + path + "/" + timestamp1 + "" + suffix;
        var uploadMsg = {
          Bucket: upInfo.Bucket,
          Region: upInfo.Region,
          SecretId: upInfo.SecretId,
          SecretKey: upInfo.SecretKey,
        };
        var COS = require('cos-js-sdk-v5');
        var cos = new COS({
          SecretId: uploadMsg.SecretId,
          SecretKey: uploadMsg.SecretKey,
        });
        that.Info('上传中...')
        cos.putObject({
          Bucket: uploadMsg.Bucket,
          Region: uploadMsg.Region, //存储桶所在地域，必须字段
          Key: newFileName, //文件名
          StorageClass: 'STANDARD',
          Body: fileObj, // 上传文件对象
          onProgress: function (progressData) { }
        }, function (err, data) {
          if (data && data.statusCode == 200) {
            var uploadResult = {
              resultCode: 1,
              FileName: fileObj.name,
              FileUrl: "https://" + data.Location
            }
            if (callback) {
              callback(uploadResult);
            }
          } else {
            /*上传文件异常*/
            console.log(err || data);
          }
        });
      },
      //上传至阿里云
      Vue.prototype.uploadToAli = function (path, fileObj, successCall) {
        var upInfo = JSON.parse(localStorage.uploadInfo);
        var OSS = require('ali-oss');
        var oss = new OSS({
          region: upInfo.Region,
          accessKeyId: upInfo.SecretId,
          accessKeySecret: upInfo.SecretKey,
          bucket: upInfo.Bucket
        })
        //获取文件扩展名
        var filename = fileObj.name;
        var index = filename.lastIndexOf(".");
        var suffix = filename.substr(index);
        var timestamp1 = Date.parse(new Date()) + "_" + (Math.ceil(Math.random() * 1000));
        let str = '';
        if (this.isOnline()) {
          str = "/Test"
        }
        var newFileName = str + '/Upload/' + path + "/" + timestamp1 + "" + suffix;
        this.Info('上传中...')
        var result = oss.multipartUpload(newFileName, fileObj, {
          progress: function* (p) { }
        }).then(res => {
          var uploadResult = {
            resultCode: 1,
            FileName: fileObj.name,
            FileUrl: res.res.requestUrls[0].replace('http', 'https')
          }
          successCall(uploadResult);
        })
      },
      //公用判断图片地址 判断是否包含http
      Vue.prototype.getIconLink = function (url) {
        let str = ''
        if (url && url != '') {
          if (url.indexOf('http') != -1) {
            str = url
          } else {
            str = this.domainManager().ImageUrl + url;
          }
          return str;
        }
      },
      //是否是线上环境【发布时修改为true】
      Vue.prototype.isOnline = function () {
        return process.env.NODE_ENV !== 'development';
      },
      //获取文件Blob
      Vue.prototype.getFileBlob = function (objectKey, filename) {
        var co = require('co');
        var OSS = require('ali-oss');
        var oss = new OSS({
          region: 'oss-cn-hangzhou',
          accessKeyId: 'LTAIwE7l9dImZSa3',
          accessKeySecret: 'j47Ajn0d0WzUCIX8Biyj3P2r8QDltI',
          bucket: 'reborndev'
        })
        let url = oss.signatureUrl(objectKey);
        let getBlob = new Promise(resolve => {
          const xhr = new XMLHttpRequest();
          xhr.open('GET', url, true);
          xhr.responseType = 'blob';
          xhr.onload = () => {
            if (xhr.status === 200) {
              resolve(xhr.response);
            }
          };
          xhr.send();
        });
        return getBlob
      },
      Vue.prototype.getAnyFileBlob = function (url) {
        let getBlob = new Promise(resolve => {
          const xhr = new XMLHttpRequest();
          xhr.open('GET', url, true);
          xhr.responseType = 'blob';
          xhr.onload = () => {
            if (xhr.status === 200) {
              resolve(xhr.response);
            }
          };
          xhr.send();
        });
        return getBlob

      },
      //Blob文件上传
      Vue.prototype.uploadSelfBlob = function (path, files, successCall) {
        let that = this;
        var uploadUrl = that.domainManager().VTUploadUrl + "/Upload/UploadBlob?fileType=1&fileLimit=5&&filePath=" + path;
        var formData = new FormData();
        formData.append("myfile", files[0]);
        that.$http.post(uploadUrl, formData, {
          'Content-Type': 'multipart/form-data'
        })
          .then(res => {
            successCall(res);
          })
      }
  }
}
