const qs = require('qs');
const $ = require("jquery");
const axios = require("axios")
var Utils = require('./rePromise');
const baseUrl = "http://192.168.2.236:5858"
//页面映射
const pageMap={
  'YH-KZT':'console.html',
  'YH-KZTKS':'deptConsole.html',
  'YH-JCSJWH-MKSJWH':'moduleManager.html',
  'YH-JCSJWH-TMSJWH':'itemManager.html',
  'YH-BLZK-ZKPF':'qcList.html',
  'YH-BLZK-ZKPFKS':'qcListDept.html',
  'YH-BLZK-ZKPFGR':'qcListPerson.html',
  'YH-TJFX':'statistics.html',
  'YH-QXGL-YHGL':'userManager.html',
  'YH-QXGL-JSGL':'roleManager.html',
  'YH-KSZR-GMKQXZB_XQ':'mukuai.html?from=2',
  'YH-KSZR-TMQXZB_XQ':'singleVeto.html?from=2&special=1',
  'YH-ZKK-GMKQXZB_XQ':'mukuaiControl.html?from=1',
  'YH-ZKK-TMQXZB_XQ':'singleVeto.html?from=1&special=1',
  'YH-YCSJJK':'abnormal.html',
  'YH-ZKK-KSPJZYTS_XQ':'dayDetail.html',
  'YH-ZKK-KSPJZYHF_XQ':'payDetail.html',

  'YH-ZKK-GKSQXZB':'deptScoreDetailControl.html',
  "YH-ZKK-GKSZKPJF_XQ":'deptScoreDetailControl.html',
  'YH-JCSJWH':'deptScoreDetailControl.html',
  "YH-ZKK-GKSQXZB_XQ":'deptScoreDetailControl.html',
  
  "YH-KSZR-KSQXZB_XQ":'deptScoreDetail.html?from=2',
  "YH-ZKK-GKSJJBLZB_XQ":'jiaji.html',
  
  "YH-ZKK-BASYHGLZB_XQ":'partDetailControl.html',
  "YH-KSZR-BASYHGLZB_XQ":'partDetail.html',

  "YH-JCSJWH-ZKLXWH":'assertType.html',
};

//重写assign方法
if (typeof Object.assign != 'function') {
  Object.assign = function (target) {
    'use strict';
    if (target == null) {
      throw new TypeError('Cannot convert undefined or null to object');
    }

    target = Object(target);
    for (var index = 1; index < arguments.length; index++) {
      var source = arguments[index];
      if (source != null) {
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
    }
    return target;
  };
}

window.console = window.console || (function () {
  var c = {}; c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile
    = c.clear = c.exception = c.trace = c.assert = function () { };
  return c;
})();

const getUrlArgObject = function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var reg_rewrite = new RegExp("(^|/)" + name + "/([^/]*)(/|$)", "i");
  var r = window.location.search.substr(1).match(reg);
  var q = window.location.pathname.substr(1).match(reg_rewrite);
  if (r != null) {
    return decodeURIComponent(r[2]);
  } else if (q != null) {
    return decodeURIComponent(q[2]);
  } else {
    return null;
  }
}
const getUrlArgObjectNew = function(name,srcUrl) {
  if(srcUrl.indexOf("?") == -1){
    return ""
  }
  var r = srcUrl.split("?")[1].split("&"),obj={};
  for(let i = 0;i < r.length;i++){
    let tmp = r[i].split("=")
    obj[tmp[0]] = tmp[1]
  }
  return obj[name]
}

const post = function (url, data) {
  const token = getCookie('accessToken') || localStorage.getItem('accessToken')
  if(!token&&window.location.href.indexOf('login')==-1){
    window.location.href = "../login.html"
  }
  let need = window.location.href.indexOf('localhost')!=-1
  return new Utils((resolve, reject) => {
    $.ajax({
      method: 'post',
      url: (need?baseUrl:'')+url,
      async:true,
      cache: false,
      contentType: false,
      processData: false,
      data: JSON.stringify(data),
      contentType: "application/json; charset=UTF-8",
      beforeSend: function (xmlHttp) {
        xmlHttp.setRequestHeader("If-Modified-Since", "0");
        xmlHttp.setRequestHeader("Cache-Control", "no-cache");
        xmlHttp.setRequestHeader("Authorization",token?"Bearer "+token:'')
      },
      success: function (res) {
        resolve({ data: res });
      },
      error: function (error) {
        if(error.status===403||error.status===401){
          const wd = window.parent.window||window;
          wd.location.href = "../login.html";
        }
        reject(error);
      },
    });
  });
}

// // 导出
// const expJson = (url,data) =>{
//   const token = getCookie('accessToken')
//   if(!token&&window.location.href.indexOf('login')==-1){
//     window.location.href = "../login.html"
//   }
//   let need = window.location.href.indexOf('localhost')!=-1
//   console.log('bbbbbbbb',url)
//   return new Utils((resolve, reject) => {
//     $.ajax({
//       method: 'post',
//       // url: (need?baseUrl:'')+url,
//       url: url,
//       async:true,
//       cache: false,
//       contentType: false,
//       processData: false,
//       data: JSON.stringify(data),
//       contentType: "application/json; charset=UTF-8",
//       // contentType: "application/vnd.ms-excel;charset=UTF-8",
//       responseType: 'blob', //必须添加，否则会乱码
//       beforeSend: function (xmlHttp) {
//         xmlHttp.setRequestHeader("If-Modified-Since", "0");
//         xmlHttp.setRequestHeader("Cache-Control", "no-cache");
//         // xmlHttp.setRequestHeader("Authorization",token?"Bearer "+token:'')
//         xmlHttp.setRequestHeader("Authorization",'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9. .vVhXSiar5iUsb36XCdO5RlxP4PBhhvQPUhrWNlZuAFoURwdico5UU-6rrgrpZNhb8SyI8dlQGxcEND6qppHvDBKOco6WbbUUg0AKMx8resktupMsTdhfhZe5xApNsDJPuo6lEDVQtuzPg0H5kNpnZOArqsZjXWn2W4fLIpmTy8uKU3mhU2hkENHBkalsNcQlDcg-ZhhPDTuEESsfwR2mvMxzBFvhm4rQxuJA6pHrreT5Yx5D1h6oap12R5ung5eR08v3Ip29hvpaCyyrbK96-ph4LUpenjWjzdvCNP2FAZmlCkXn5QgGcjpZydiFp1O9wJj9jzmOKA2S1AR9KnTemw')
//       },
//       success: function (res) {
//         resolve({ data: res });
//       },
//       error: function (error) {
//         // if(error.status===403||error.status===401){
//         //   const wd = window.parent.window||window;
//         //   wd.location.href = "../login.html";
//         // }
//         reject(error);
//       },
//     });
//   });
// }
// 导出
const expJson = (url,data) =>{
  const token = getCookie('accessToken')
  if(!token&&window.location.href.indexOf('login')==-1){
    window.location.href = "../login.html"
  }
  let need = window.location.href.indexOf('localhost')!=-1
  return axios({
    method:'post',
    url:(need?baseUrl:'')+url,
    data: data,
    contentType: "application/vnd.ms-excel" ,
    responseType: 'blob',//必须添加，否则会乱码
    headers:{
      Authorization:"Bearer "+token
    }
  })
}




 //导出接口返回流下载
 function downloadExportedData(data, fileName) {
  var blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
  var downloadElement = document.createElement('a');
  var href = window.URL.createObjectURL(blob); //创建下载的链接
  downloadElement.href = href;
  downloadElement.download = fileName; //下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); //点击下载
  document.body.removeChild(downloadElement); //下载完成移除元素
  window.URL.revokeObjectURL(href);
}

//判断浏览器是否为Ie8
const isIe8 = function () {
  var DEFAULT_VERSION = 8.0;
  var ua = navigator.userAgent.toLowerCase();
  var isIE = ua.indexOf("msie") > -1;
  var safariVersion;
  if (isIE) {
    safariVersion = ua.match(/msie ([\d.]+)/)[1];
  }
  if (safariVersion <= DEFAULT_VERSION) {
    return true
  }
}
const setCookie = function(name,value){
  let Days = 30;
  let exp = new Date();
  exp.setTime(exp.getTime() + Days*24*60*60*1000);
  document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

//读取cookies
const getCookie =function(name){
  let arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
  if(arr=document.cookie.match(reg))
      return unescape(arr[2]);
  else
      return null;
}

//删除cookies
const delCookie = function(name){
  let exp = new Date();
  exp.setTime(exp.getTime() - 1);
  let cval=getCookie(name);
  if(cval!=null)
      document.cookie= name + "="+cval+";expires="+exp.toGMTString();
};

//弹窗关闭事件
$(".modal .close").click(function(){
  $(".modal").hide();
});
//计算容器高度
function setBoxHeight(){
  const ht=window.innerHeight;
  $(".content-box").height((ht-55)+'px');
  $(".flaw-table").height((ht-70)+'px');
  $(".content-ht").height((ht-120)+"px");
  $(".scroll-table tbody").css("max-height",(ht-200)+"px")
}
setBoxHeight();
$(window).resize(function(){
  setBoxHeight();
});

//判断有无某一权限
function hasData(data){
  let lis = JSON.parse(getCookie("codeLis"))||[]
  if(lis.indexOf(data)>-1){//有权限
    return true
  }
  return false;
}
//定位对应明细菜单
function focusMenuItem(code){
  const ele = $(parent.document).find(".menu .page[code="+code+"]");
  const parEle = ele.parents(".list-1");
  if(!parEle.is(".list-1-show")){
    parEle.click();
  }
  //console.log($(parent.document).find(".menu .page[code='YH-ZKK-GMKQXZB_XQ']"))
  ele.click();
}
function emptyBox(name,showNum){
  let showNumer = showNum || 18
  let str = `<tr><td colspan="${showNumer}" style="text-align: center;color: #aaa">
  <img style="margin-top:50px;width:100px;" src="${require('../images/empty1.png')}" />
  <p style="margin-top:20px;margin-bottom:30px;color:#ccc;position:relative;left:5px;">${name||'暂无数据~'}</p>
  </td></tr>`
  return str
}
function picEmptyData(dom,str){
  let empty = `<div class="emptyBoxHome">
      <img src="${require('../images/emptyHome.png')}">
      <p>${str||"暂无数据~"}</p>
  </div>
  `
  $(dom).css({"position":"relative","display":"block"}).html(empty)
}
function setTitleTxt(dom,from){
  console.log(dom,from)
  if(!from){
    $(dom?dom:".partTitle").find("a").remove()
  }
}

//mode=1:本月，mode=2:本年，mode="default":默认情况（1周） startDateDefault：mode不等于1和2开始日期，endDateDefault：mode不等于1和2结束日期
function setDatePicker(picker1,picker2,mode,startDateDefault,endDateDefault){
  $.datepicker.regional['zh-CN'] = {
    clearText: '清除',
    clearStatus: '清除已选e799bee5baa6e59b9ee7ad9431333361303131日期',
    closeText: '关闭',
    closeStatus: '不改变当前选择',
    prevText: '<上月',
    prevStatus: '显示上月',
    prevBigText: '<<',
    prevBigStatus: '显示上一年',
    nextText: '下月>',
    nextStatus: '显示下月',
    nextBigText: '>>',
    nextBigStatus: '显示下一年',
    currentText: '今天',
    currentStatus: '显示本月',
    monthNames: ['一月','二月','三月','四月','五月','六月', '七月','八月','九月','十月','十一月','十二月'],
    monthNamesShort: ['一月','二月','三月','四月','五月','六月', '七月','八月','九月','十月','十一月','十二月'],
    yearNamesShort: ['一月','二月','三月','四月','五月','六月', '七月','八月','九月','十月','十一月','十二月'],
    monthStatus: '选择月份',
    yearStatus: '选择年份',
    weekHeader: '周',
    weekStatus: '年内周次',
    dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
    dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
    dayNamesMin: ['日','一','二','三','四','五','六'],
    dayStatus: '设置 DD 为一周起始',
    dateStatus: '选择 m月 d日, DD',
    dateFormat: 'yy-mm-dd',
    firstDay: 1,
    initStatus: '请选择日期',
    isRTL: false};
    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
    let startDate = "", endDate=new Date()
   
    let year = new Date().getFullYear()
    let month = new Date().getMonth() + 1
    if(mode == '1'){
        startDate = new Date(`${year}-${month}-01`)
    }else if(mode == '2'){
        startDate = new Date(`${year}-01-01`)
    } else if(mode == 'default'){
      startDate = new Date(`${year}-01-01`)
    }else {
        startDate = startDateDefault || new Date()
        endDate = endDateDefault || new Date()
    }
    if(picker1){
      picker1.datepicker({
        yearRange: "2015:"+year,
        changeMonth: true,
        changeYear: true,
        dateFormat:"yy/mm/dd",
    }).datepicker( "setDate", startDate);
    }
    if(picker2){
      picker2.datepicker({
        yearRange: "2015:"+year,
        changeMonth: true,
        changeYear: true,
        dateFormat:"yy/mm/dd"
      }).datepicker( "setDate",endDate); 
    }
    
}

  //mode=1获取开始时间，mode=1获取结束时间
function getPickerDate(picker,mode){
  if(!picker){
    return
  }
  let date = picker.val().trim()
  if(mode == 1){
    return date.replace(/\//g,'-') + ' 00:00:00'
  }else if(mode == 2){
    return date.replace(/\//g,'-') + ' 23:59:59'
  }
}
function isMac(){
  var isMac = /macintosh|mac os x/i.test(navigator.userAgent);
  return isMac
}
module.exports = {
  pageMap,
  post,
  getUrlArgObject,
  getUrlArgObjectNew,
  isIe8,
  setCookie,
  getCookie,
  delCookie,
  setBoxHeight,
  hasData,
  focusMenuItem,
  emptyBox,
  picEmptyData,
  setTitleTxt,
  downloadExportedData,
  expJson,
  setDatePicker,
  getPickerDate,
  isMac
};
