const qs = require('qs');
const $ = require("jquery");
// var Promise = require('./rePromise');
var Promise = require("bluebird");
let warn = require('./../images/icon-warning.png').replace(/^undefined/g, '')
let success = require('./../images/icon-success.png').replace(/^undefined/g, '')
let iconWarning = require('./../images/icon_waring_white.png').replace(/^undefined/g, '')
let iconWarning1 = require('./../images/icon_warning.png').replace(/^undefined/g, '')
let iconSymptomPush = require('./../images/icon_symptom_push.png').replace(/^undefined/g, '')
let iconLisPush = require('./../images/icon_lis_push.png').replace(/^undefined/g, '')
let iconPacsPush = require('./../images/icon_pacs_push.png').replace(/^undefined/g, '')
let iconScalePush = require('./../images/icon_scale_push.png').replace(/^undefined/g, '')
let iconNursePush = require('./../images/icon_nurse_push.png').replace(/^undefined/g, '')

let iconOperationPush = require('./../images/icon_operation_push.png').replace(/^undefined/g, '')
let iconDrugPush = require('./../images/icon_drug_push.png').replace(/^undefined/g, '')
let iconDiagPush = require('./../images/icon_diag_push.png').replace(/^undefined/g, '')
let iconDiagPush2 = require('./../images/icon_diag_push2.png').replace(/^undefined/g, '')
let iconCommonTreatPush = require('./../images/icon_drug_push.png').replace(/^undefined/g, '')
let iconCheckupPush = require('./../images/icon_checkup_push.png').replace(/^undefined/g, '')
let iconTreat = require('./../images/zhiliao.png').replace(/^undefined/g, '')
let writingNorms = require('./../images/writingNorms.png').replace(/^undefined/g, '')

let iconTreatMedicine = require('./../images/treat_icon.png').replace(/^undefined/g, '')
let iconCaseWrite = require('./../images/icon_case_write.png').replace(/^undefined/g, '')
let intelligentDiagnosis = require('./../images/intelligentDiagnosis.png').replace(/^undefined/g, '')
let therapeuticSchedule = require('./../images/therapeuticSchedule.png').replace(/^undefined/g, '')




//重写assign方法imgR
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 config = {
  pushInner: '/sys/push/push',
  indicationPush:'/sys/push/indicationPush',
    indicationPushCache: '/sys/mr/getIndicationMr',
  calculate: '/api/data/calc/calculate',
  disclaimer: '/sys/disclaimerInfo/getDisclaimerInfo',
  information: '/kl/conceptInfo/getStaticKnowledge',
  getStaticKnowledgeForHIS:'/kl/conceptInfo/getStaticKnowledgeForHIS', //对接一对多
  informationMore: '/api/data/conceptDetail/getConceptDetails',
  pushScale: '/api/data/push/pushScale',
  getSysSetInfoDatas: '/sys/plan/getSysPlanInfoDatas',
  getMr: '/sys/mr/getMr', //页面推送患者信息
  getMr2: '/sys/mr/getMr', //icss推送患者信息
  getVersion: '/sys/versionInfo/getVersionInfoAlls',
  getStaticKnowledge: '/kl/conceptInfo/staticKnowledgeIndex',//静态知识检索
  getStaticScale: '/api/data/search/getScale',
  dictionaryInfo: '/sys/dictionaryInfo/getList', //字典信息
  getPushSet:'/sys/plan/getSysPlanInfoDatas', //获取推送配置
  analyse:'/api/data/mrqc/analyse',
  getHosptDeptUsal:'/api/data/concept/getHosptDeptUsal', //获取科室常用标签
  caseWritingPrompt:'/sys/mrqc/caseWritingPrompt',//病历书写规范提示
  followUp:'/sys/push/pushPlan', //随访计划
  ruleTypeMap:{     //大数据推送参数featureType对应
    '22':'1,2',
    '11':'3',
    '8':'4,5'
  },
  staticSearch:'/kl/conceptInfo/staticIndexPage', //检索静态知识
}
const isLocal = window.location.hostname.indexOf('localhost') !=-1;
const imageUrlPrefix = isLocal ?'http://192.168.2.241:82':'http://'+window.location.hostname+':82';
// const getUrlArgObject = function(parm) {  
//   var query = decodeURI(window.location.search);
//   var args = qs.parse(qs.parse(query.substr(1)));
//   return args[parm];//返回对象  
// } 

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 get = function (url, data) {
    return new Promise((resolve, reject) => {
        $.ajax({
            method: 'get',
            url: url,
            //data: data,
            contentType: "application/json; charset=UTF-8",
            beforeSend: function (xmlHttp) {
                xmlHttp.setRequestHeader("If-Modified-Since", "0");
                xmlHttp.setRequestHeader("Cache-Control", "no-cache");
            },
            success: function (res) {
                resolve({data: res});
            },
            error: function (error) {
                reject(error);
            },
        });
    });
}
const post = function (url, data) {
  return new Promise((resolve, reject) => {
    $.ajax({
      method: 'post',
      url: url,
      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");
      },
      success: function (res) {
        resolve({ data: res });
      },
      error: function (error) {
        reject(error);
      },
    });
  });
}
const newinConf = {
  width: '600',   //窗口的文档显示区的宽度。以像素计。
  height: '600',  //窗口文档显示区的高度。以像素计。
  left: '0',  //窗口的 x 坐标。以像素计。
  top: '0',    //窗口的 y 坐标。以像素计。
  openMode: "_blank"  //每次都是新窗口打开为_blank,打开同一窗口填写任意字符串
}
const newWindowLocationTcm = `width=800, height=600, left=${newinConf.left}, top=${newinConf.top},resizable=yes, scrollbars=yes`
const newWindowLocation = `width=${newinConf.width}, height=${newinConf.height}, left=${newinConf.left}, top=${newinConf.top},resizable=yes, scrollbars=yes`
const openNewWin = function (url, isTcm) {
  window.open(url, newinConf.openMode, isTcm ? newWindowLocationTcm : newWindowLocation)
}

//判断浏览器是否为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 throttle = function (fn, threshhold) {
  var timeout
  var start = new Date;
  var threshhold = threshhold || 160
  return function () {

    var context = this, args = arguments, curr = new Date() - 0

    clearTimeout(timeout)//总是干掉事件回调
    if (curr - start >= threshhold) {
      // console.log("now", curr, curr - start)//注意这里相减的结果，都差不多是160左右
      fn.apply(context, args) //只执行一部分方法，这些方法是在某个时间段内执行一次
      start = curr
    } else {
      //让方法在脱离事件后也能执行一次
      timeout = setTimeout(function () {
        fn.apply(context, args)
      }, threshhold);
    }
  }
}
const colorMap={
  warnColor:'#FFE8DD', //智能警示等tab颜色
  suggerColor:'#E3F0FF', //推荐提示tab颜色
  treatColor:'#E3FEFE',  //治疗等tab颜色
}
const titleConfig = {
  warning:{
    background: colorMap.warnColor,
    icon: iconWarning1,
    name:"智能警示"
  },
  symptomPush:{
    background: colorMap.suggerColor,
    icon: iconSymptomPush,
    name:"推荐症状"
  },
  diagPush:{
    background: colorMap.suggerColor,
    icon: iconDiagPush2,
    name:"智能诊断"
  },
  checkupPush:{
    background: colorMap.suggerColor,
    icon: iconCheckupPush,
    name:"推荐体格检查"
  },
  scalePush:{
    background: colorMap.suggerColor,
    icon: iconScalePush,
    name:"推荐量表"
  },
  lisPush:{
    background: colorMap.suggerColor,
    icon: iconLisPush,
    name:"推荐检验"
  },
  pacsPush:{
    background: colorMap.suggerColor,
    icon: iconPacsPush,
    name:"推荐检查"
  },
  drugPush:{
    background: colorMap.treatColor,
    icon: iconDrugPush,
    name:"推荐用药"
  },
  nursePush: {
    background: colorMap.treatColor,
    icon: iconNursePush,
    name: "推荐护理"
  },
  operationPush:{
    background: colorMap.treatColor,
    icon: iconOperationPush,
    name:"推荐手术及操作"
  },
  generaTreatPush:{
    background: colorMap.treatColor,
    icon: iconTreat,
    name:"一般治疗"
  },
  casewritingPush:{
    background: colorMap.warnColor,
    icon: iconCaseWrite,
    name:"病历书写规范提示"
  }
}
const titleConfigH = {
  warning:{
    background: "#FFE8DD",
    icon: iconWarning1,
    name:"智能警示",
    location:"left"
  },
  symptomPush:{
    background: "#EEF5FD",
    icon: iconSymptomPush,
    name:"推荐症状",
    location:"left"
  },
  diagPush:{
    background: "#FAECED",
    icon: intelligentDiagnosis,
    name:"智能诊断",
    location:"left"
  },
  checkupPush:{
    background: "#EEF5FD",
    icon: iconCheckupPush,
    name:"体格检查",
    location:"left"
  },
  scalePush:{
    background: "#EEF5FD",
    icon: iconScalePush,
    name:"推荐量表",
    location:"left"
  },
  lisPush:{
    background: "#ECF4FC",
    icon: iconLisPush,
    name:"推荐检验",
    location:"left"
  },
  pacsPush:{
    background: "#ECF4FC",
    icon: iconPacsPush,
    name:"推荐检查",
    location:"left"
  },
  generaTreatPush:{
    background: "#E3FEFE",
    icon: iconTreat,
    name:"一般治疗",
    location:"right"
  },
  drugPush:{
    background: "#E3FEFE",
    icon: iconDrugPush,
    name:"推荐用药",
    location:"right"
  },
  operationPush:{
    background: "#E3FEFE",
    icon: iconOperationPush,
    name:"手术/操作",
    location:"right"
  },
    nursePush: {
        background: "#E3FEFE",
        icon: iconNursePush,
        name: "推荐护理",
        location: "right"
    },
  vigilancePush:{
    background: "#FFE8DD",
    icon: iconWarning,
    name:"警惕",
    location:"left"
  },
  treat:{
    background: "#FFE8DD",
    icon: therapeuticSchedule,
    name:"治疗方案"
  },
  casewritingPush:{
    background: "#FFE8DD",
    icon: writingNorms,
    name:"病历书写规范提示",
    location:"left"
  }
}
const Toast = function (msg, duration,type) {
  duration = isNaN(duration) ? 3000 : duration;
  var m = document.createElement('div');
  if(type == 'warn'){
    m.innerHTML = '<div style="margin:auto"><img class="warn" style="margin-right:14px;float:left" src="./../images/icon-warning.png" /><span>'+msg+'</span></div>'
    m.style.cssText = "margin:auto;width:250px;vertical-align:middle;padding:25px 14px;height: 30px;color: #fff;line-height: 30px;text-align: center;border-radius: 8px;position: absolute;top: 0;left: 0;right:0;bottom:0;z-index: 999999;background: #333;font-size: 16px;";
  }else if(type == 'success'){
    m.innerHTML = '<div style="margin:auto;width:120px"><img class="warn" style="width:32px;margin-right:14px;float:left" src="./../images/icon-success.png" /><span>' + msg +'</span></div>'
    m.style.cssText = "margin:auto;width:120px;vertical-align:middle;padding:25px 14px;height: 30px;color: #fff;line-height: 30px;text-align: center;border-radius: 8px;position: absolute;top: 0;left: 0;right:0;bottom:0;z-index: 999999;background: #333;font-size: 16px;";
  }
  
  
  $('.warn').css('margin-top','10px')
  document.body.appendChild(m);
  setTimeout(function () {
    var d = 0.5;
    m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
    m.style.opacity = '0';
    setTimeout(function () { document.body.removeChild(m) }, d * 1000);
  }, duration);
}
module.exports = {
  config,
    get,
  post,
  getUrlArgObject,
  imageUrlPrefix,
  throttle,
  openNewWin,
  isIe8,
  titleConfig,
  titleConfigH,
  Toast
}
