require("../css/index.less");
const $ = require('jquery');
require('jquery-templates');
const md5 = require('js-md5');
require("./modal.js")
const okIcon = require("./../images/checkOk.png")
const WarningIcon = require("./../images/icon-Warning.png")
const warnIcon = require("./../images/warn.png")
const openEye = require("./../images/open-eye.png")
const closeEye = require("./../images/close-eye.png")
const adLogo = require("../images/adlogo.png")

const {
  api
} = require('./api.js')
const {
  post,
  pageMap,
  delCookie,
  setCookie,
  setLocal,
  getCookie,
  clearAllCookie,
  focusMenuItem,
  getUrlArgObject
} = require('./utils.js');
let userInfo = {};
let isPlacefile = getCookie('isPlacefile') || 1

let passwordComplexity = getCookie('passwordComplexity')
const hideLogo = getUrlArgObject("hideLg");
const otherLogo = getUrlArgObject("adLg");
const is3His = getUrlArgObject('is3His')
//token判断没有跳登录
const token = localStorage.getItem('accessToken');
const onAppeal = getCookie('checkAuth') && getCookie('checkAuth').indexOf('10')
let auditNumber;
if (!token || localStorage.getItem('toLogin') === '1') {
  window.location.href = '../login.html';
}
const modalDom = `
      <p class="tips"><img src=${WarningIcon} /><span>为确保账号安全，请及时修改初始密码</span></p>
      <div class="modalAction">
        <p><span class="label"><i>*</i>原密码：</span><input type="password" readonly placeholder="请输入原密码" class="oldword" id="oldWord" autocomplete="off"><img class="eye" src=${closeEye} /><p class="oldWaring warning"><img src=${warnIcon} /><b>原密码错误</b></p></p>
        <p><span class="label"><i>*</i>新密码：</span><input type="password" disabled readonly placeholder="请输入新密码" class="newword" id="newWord" autocomplete="off"><img class="eye" src=${closeEye} /><p class="newword warning"><img src=${warnIcon} /><b>密码最多12位</b></p></p>
        <p><span class="label"><i>*</i>确认新密码：</span><input type="password" disabled readonly placeholder="请确认新密码" class="sureword" id="sureWord" autocomplete="off"><img class="eye" src=${closeEye} /><p class="sureword warning"><img src=${warnIcon} /><b>两次密码输入不一致</b></p></p>
      </div>
    `;
const psdChecker = `<div class="psd-checkbox">
                      <p class="label">密码至少包含：</p>
                      <p class="big-letter"><i></i>1个大写字母</p>
                      <p class="small-letter"><i></i>1个小写字母</p>
                      <p class="special-letter"><i></i>1个特殊字符</p>
                      <p class="one-number"><i></i>1个数字</p>
                      <p class="eight-str"><i></i>8位字符</p>
                    </div>`;
$(function () {
  //无logo演示隐藏logo
  if (hideLogo) {
    $(".copy-right,.logo img").remove();
    $(".menu-mini .logo").text("");
  }
  const otherLogo = getUrlArgObject("adLg");
  if (otherLogo) {
    $(".logo img").attr("src", adLogo);
    $(".menu-mini .logo").text("艾登");
    $(".copy-right").remove();
  }
  hideDropdown();
  getOwnDept();
  setInterval(() => {
    getTimeDetail()
  }, 1000);
  sureChangeWord()
  const token = localStorage.getItem('accessToken');
  if (!token) {
    window.location.href = '../login.html';
  }
  if (passwordComplexity !== 'null' && token) {
    $.alerModal({
      quiteBtn: true,
      title: "修改密码",
      type: "modal",
      width: '470',
      time: '1000',
      sureText: '保存',
      message: modalDom
    });
    bindModalEvent();
  }
  //菜单展开收起
  $(".main").css({
    height: $(window).height() - 52 + 'px'
  })
  $(window).resize(function () {
    $(".main").css({
      height: $(window).height() - 52 + 'px'
    })
  })
  $(window).click(function (e) {
    $(".userAction").css("display", "none")
  })
  $("#changeWord").css("opacity", hasData('FUNC000002') ? '1' : '0.5').hover(function () {
    $(this).css("color", "#777777")
  })
  if (isPlacefile == 0) {
    $(this).find('.qiehuan i').html('切换病案质控')
    $('.subtitle').html('AI运行质控平台')
    getAuditNumber()
    getMenu()
  } else if (isPlacefile == 1) {
    $(this).find('.qiehuan i').html('切换运行质控')
    $('.subtitle').html('AI病案质控平台')
    getAuditNumber()
    getMenu()
  }
  $(".header .title .qiehuan").click(function () {
    let txt = $(this).find('i').html()
    if (txt == '切换运行质控') {
      $(this).find('i').html('切换病案质控')
      $('.subtitle').html('AI运行质控平台')
      setCookie("isPlacefile", 0)
    } else {
      $(this).find('i').html('切换运行质控')
      $('.subtitle').html('AI病案质控平台')
      setCookie("isPlacefile", 1)
    }
    $('#contentIframe').attr('src', $('#contentIframe').attr('src'));
    getAuditNumber()
    getMenu();
  })
  $(".header .title .qiehuan").mouseenter(function () {
    $(this).parent().find('img').attr('src', require('../images/qiehuan1.png'))
  })
  $(".header .title .qiehuan").mouseleave(function () {
    $(this).parent().find('img').attr('src', require('../images/qiehuan2.png'))
  })
});
//切换密码明文
function switchPwd(el) {
  if (!el.is(".open")) {
    el.attr("src", openEye).addClass("open");
    el.prev().attr("type", 'text');
  } else {
    el.attr("src", closeEye).removeClass("open");
    el.prev().attr("type", 'password');
  }
}

function toast(msg) {
  const toast = `<div class="toast"><img src="${okIcon}" alt=""><p>${msg}</p></div>`;
  $(toast).appendTo($(".alertModal"));
}

function hideDropdown() { //关闭下拉
  $(document).off("click").on("click", function (e) {
    $("#contentIframe").contents().find(".toggleSlide ul").hide();
  })
}

//绑定输入框事件
function bindModalEvent() {
  $(".modalAction input").off("click").on("click", function () {
    $(this).removeAttr("readonly").focus()
  })
  $(".modalAction input").off("blur").on("blur", function () {
    $(this).attr("readonly", true)
  })
  $(".modalAction .eye").off("click").on("click", function () {
    switchPwd($(this))
  })

  $("#oldWord").off("input").on("input", function () {
    switchToPsd($(this));
    const text = $(this).val();
    $(".oldWaring.warning,.newword.warning").hide();
    verifyPsdPart();
    if (text.trim()) {
      $("#newWord").attr("disabled", false);
    }
    if (!$(".modalAction .warning:visible").length) {
      $(".alertModal .sureChange").addClass("active");
    }
  });
  let gl_psdOk = false;
  $("#newWord").off("input").on("input", function () {
    switchToPsd($(this));
    let text = $(this).val();
    const checker = $(".alertModal .psd-checkbox");
    if (/[\u4e00-\u9fa5]/g.test(text)) {
      $(this).val(text.replace(/[\u4e00-\u9fa5]/g, ''));
    }
    text = $(this).val();
    $(".newword.warning,.sureword.warning").hide();
    if (text.trim()) { //显示密码验证标签
      if (checker.length) {
        checker.show()
      } else {
        $(psdChecker).appendTo($(".alertModal"));
      }
      let psdsOk = verifyPsdPart();
      gl_psdOk = verifyPsd(text);
      if (gl_psdOk) {
        $("#sureWord").attr("disabled", false);
      }
      if (psdsOk && gl_psdOk && $("#sureWord").val().trim()) {
        $(".modalAction .warning").hide();
        //保存按钮启用
        $(".alertModal .sureChange").addClass("active");
      } else {
        $(".alertModal .sureChange").removeClass("active");
      }
    } else {
      checker.hide()
    }
  })
  $("#sureWord").off("input").on("input", function () {
    switchToPsd($(this));
    const text = $(this).val();
    $(".sureword.warning").hide();
    if (/[\u4e00-\u9fa5]/g.test(text)) {
      $(this).val(text.replace(/[\u4e00-\u9fa5]/g, ''));
    }
    if (text.trim()) {
      let psdsOk = verifyPsdPart();
      //const psdOk = verifyPsd(text);
      if (gl_psdOk && psdsOk) {
        $(".modalAction .warning").hide();
        //保存按钮启用
        $(".alertModal .sureChange").addClass("active");
      } else {
        $(".alertModal .sureChange").removeClass("active");
      }
    }
  })
}

function switchToPsd(dom) {
  if (!dom.val()) {
    dom.attr("readonly", true)
    setTimeout(function () {
      dom.removeAttr("readonly").focus()
    })
  }
}

//验证新密码规则
function verifyPsd(text) {
  let pass = true;
  if (/(?=.*?[A-Z])/.test(text)) { //至少一个大写字母
    $(".big-letter").addClass("active");
  } else {
    $(".big-letter").removeClass("active");
    pass = false;
  }
  if (/(?=.*?[a-z])/.test(text)) { //至少一个大写字母
    $(".small-letter").addClass("active");
  } else {
    $(".small-letter").removeClass("active");
    pass = false;
  }
  if (/(?=.*?[0-9])/.test(text)) { //至少一个数字
    $(".one-number").addClass("active");
  } else {
    $(".one-number").removeClass("active");
    pass = false;
  }
  if (/(?=.*?[#?!@$，,%^&*-])/.test(text)) { //至少一个特殊字符
    $(".special-letter").addClass("active");
  } else {
    $(".special-letter").removeClass("active");
    pass = false;
  }
  if (text.length > 7) { //至少8个字符
    $(".eight-str").addClass("active");
  } else {
    $(".eight-str").removeClass("active");
    pass = false;
  }
  if (text.length > 12) {
    $(".newword.warning b").text("密码最多12位");
    $(".newword.warning").show();
    pass = false;
  } else {
    $(".newword.warning").hide();
  }
  //const regex = new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@~^·$、，,\.!#%*?&])[A-Za-z\\d$@#$\.~、,，·!%*?&]{8,12}');
  /*if(regex.test(text)){
    return true
  }*/
  return pass;
}

function verifyPsdPart() { //验证各密码关系规则
  const oldP = $("#oldWord").val();
  const newP = $("#newWord").val();
  const confirmP = $("#sureWord").val();
  let pass = true;
  if (oldP && newP && (oldP.trim() === newP.trim())) {
    $(".newword.warning b").text("原密码和新密码不能相同");
    $(".newword.warning").show();
    pass = false;
  }
  if (newP.length > 12) {
    $(".newword.warning b").text("密码最多12位");
    $(".newword.warning").show();
    pass = false;
  }
  if (confirmP.trim() && (newP.trim() !== confirmP.trim())) {
    $(".sureword.warning b").text("两次密码输入不一致");
    $(".sureword.warning").show();
    pass = false;
  }
  return pass;
}

//判断有无某一权限
function hasData(data, list) {
  if (list && list.length > 0) {
    if (list.indexOf(data) > -1) { //有权限
      return true
    }
    return false;
  }
  let lis = JSON.parse(getCookie("codeLis")) || []
  if (lis.indexOf(data) > -1) { //有权限
    return true
  }
  return false;
}

function userActionHide(e) {
  $(".userAction").css("display", "none")
}
window.userActionHide = userActionHide
//获取待审核数量
function getAuditNumber() {
  isPlacefile = getCookie('isPlacefile') || 1
  return post(api.getAuditNumber, {
    analyzeType:isPlacefile
  }).then(res => {
    if (res.data.code == '0') {
      auditNumber = res.data.data > 99 ? '99+' : res.data.data
    } else {
      const token = localStorage.getItem('accessToken');
      if (!token && window.location.href.indexOf('login') == -1) {
        //alert('无token判断，跳回登录')
      } else {
        $.alerModal({ "message": res.data.msg, type: "tip", time: '1000', isFather: true, fatherWrapper: $("#mainBox", parent.document) });
      }
    }
  }).catch((e) => {

  })
}
function initMenu(data, userInfo) {
  //菜单数据填充
  $(".menu ul").html("");
  $(".menu-mini ul").html("");
  $("#menuTmpl").tmpl(data).appendTo(".menu ul");
  $("#miniMenuTmpl").tmpl(data).appendTo(".menu-mini ul");
  //用户数据填充
  $("#userName").text(userInfo.linkman);
  //菜单收起展开
  $(".menu .list-1").on("click", function () {
    if ($(this).is(".list-1-show")) {
      $(this).removeClass("list-1-show")
      $(this).find("ul").slideToggle();
      return;
    }

    $(".menu .list-1-show ul").slideUp();
    $(".menu .list-1").removeClass("list-1-show");
    const ulShow = $(this).find("ul").css("display")
    if (ulShow == "none") {
      $(this).addClass("list-1-show")
    }
    $(this).find("ul").slideToggle();
    // setTimeout(function(){
    //   initScroll("menuList","Y",2)
    // },300)
  });
  //收起菜单
  $(".slide-hide").off("click").click(function () {
    $(".menu,.copy-right").animate({
      "width": "60px"
    }, function () {
      $(this).hide();
      $(".menu-mini").show();
    });
    $(".main").animate({
      "margin-left": "60px"
    });
  });
  //展开菜单
  $(".slide-show").off("click").click(function () {
    $(".menu-mini").hide();
    $(".menu,.copy-right").show().animate({
      "width": "205px"
    }, function () { });
    $(".main").animate({
      "margin-left": "205px"
    });
  });

  $(".menu .list-1 li").on("click", function (e) {
    e.stopPropagation();
  });
  //右侧页面切换
  $(".page").on("click", function () {
    $(".menu .active,.menu-mini .active").removeClass('active');
    const code = $(this).attr("code");
    // const code2=$(this).attr("code2");
    if (code === 'YH-KZT' || code === 'YH-KZTKS') {
      // if(code === 'YH-KZT'){
      $(".container").addClass("console-cont");
      $('.qiehuan').css("display", "inline-block")
    } else {
      $('.qiehuan').css("display", "none")
      $(".container").removeClass("console-cont");
    }
    const mItems = $(".menu .page[code=" + code + "],.menu-mini .page[code=" + code + "]");
    mItems.addClass("active");
    mItems.parents(".list-1").addClass("active");
    let url = './' + pageMap[code];
    if (code === 'YH-BLZK-ZKPFGR') {
      url += `?doctorName=${userInfo.linkman}`
    }
    $("#contentIframe").attr("src", url);
    setTimeout(() => {
      bindMenu()
    }, 500);

  });
  // initScroll("menuList","Y",2)
}

//获取科室列表
function getOwnDept() {
  // if(hasData('FUNC000058')){
  setLocal("deptList", JSON.stringify([]))
  //setCookie("deptList", JSON.stringify([]))
  post(api.getDept, {}).then((res) => {
    let data = res.data;
    if (data.code == 0) {
      let result = data.data
	  setLocal("deptList", JSON.stringify(result))
	  //setCookie("deptList", JSON.stringify(result))
    }
  })
  // }
}

function getMenu() {
  // console.log(api.getMenu)
  isPlacefile = getCookie('isPlacefile') || 1
  post(api.getMenu).then(function (res) {
    if (res.data.code === '0') {
      const data = res.data.data;
      for (let i = 0; i < data.menuWrappers.length; i++) {

        for (let j = 0; j < data.menuWrappers[i].subMenuList.length; j++) {
          if (isPlacefile === '0' && is3His && (data.menuWrappers[i].subMenuList[j].code === 'YH-ZKK-BASYHGLYSZB_XQ' || data.menuWrappers[i].subMenuList[j].code === 'YH-KSZR-BASYHGLYSZB_XQ')) {
            data.menuWrappers[i].subMenuList.splice(j, 1);
            continue;
          }
        }
        data.menuWrappers[i].isPlacefile = isPlacefile
      }
      for (let i = 0; i < data.menuWrappers.length; i++) {
        if (data.menuWrappers[i].code === 'YH-SSXX') {
          data.menuWrappers[i].num = auditNumber
          data.menuWrappers[i].onAppeal = onAppeal
          for (let j = 0; j < data.menuWrappers[i].subMenuList.length; j++) {
            if (data.menuWrappers[i].subMenuList[j].code === 'YH-SSXX-SSSH') {
              data.menuWrappers[i].subMenuList[j].num = auditNumber
            }
          }
        }
      }
      
      initMenu(data.menuWrappers, data.userLoginDTO);
      userInfo = data.userLoginDTO
      setCookie("hospital", data.basHospitalInfoDTO.name)
      setCookie("hospitalid", data.basHospitalInfoDTO.id)
      getAllCode(data.menuWrappers);
      for (let i = 0; i < data.menuWrappers.length; i++) {
        if (isPlacefile === '0' && data.menuWrappers[i].code === 'YH-ZKHC') {
          $(".menuList .YH-ZKHC").hide()
          $(".menu-mini .YH-ZKHC").hide()
          
        }
      }
    }
  })
};

function getAllCode(data) {
  let lis = [],
    personCodeLis = [],
    deptCodeLis = [],
    trdObj = {}
  for (let i = 0; i < data.length; i++) {
    let tmpSon = data[i]
    lis.push(tmpSon.code)
    if (tmpSon.subMenuList.length > 0) { //三层
      for (let j = 0; j < tmpSon.subMenuList.length; j++) { //第二层循环
        let tmpGrandSon = tmpSon.subMenuList[j]
        let sonLis = []
        lis.push(tmpGrandSon.code)
        for (let m = 0; m < tmpGrandSon.sysUserPermissionDTOList.length; m++) {
          let tmpData = tmpGrandSon.sysUserPermissionDTOList[m]
          lis.push(tmpData.code)
          sonLis.push(tmpData.code)
        }
        trdObj[tmpGrandSon.code] = sonLis
      }
    } else { //两层
      for (let n = 0; n < tmpSon.sysUserPermissionDTOList.length; n++) {
        let tmpData = tmpSon.sysUserPermissionDTOList[n]
        lis.push(tmpData.code)
      }
    }
  }
  //初始菜单选中
  if (hasData('YH-KZT', lis)) {
    focusMenuItem("YH-KZT");
  } else if (hasData('YH-KZTKS', lis)) {
    focusMenuItem("YH-KZTKS");
  }
  setCookie("codeLis", JSON.stringify(lis))
  setLocal("trdObj", JSON.stringify(trdObj))
}

function sureChangeWord() {
  $(document).on('click', '.sureChange.active', function () {
    let oldword = $(".oldword").val().trim()
    let newword = $(".newword").val().trim()
    $(".modalAction .waring i").html('')
    changeWord(oldword, newword)
  })
}

function changeWord(oldword, newword) {
  post(api.midifyPassword, {
    "modifyPassword": newword,
    "password": oldword
  }).then(function (res) {
    const data = res.data;
    if (data.code === '0') {
      setCookie('behosDateStart', '')
      setCookie('behosDateEnd', '')
      toast("密码修改成功，请重新登录");
      setTimeout(() => {
        window.location.href = './login.html'
      }, 1000);
    } else {
      $(".oldWaring b").text(data.msg);
      $(".oldWaring").show();
      $(".alertModal .sureChange").removeClass("active");
      return
    }
  });
}
//用户信息下拉事件
$(".login").click(function (e) {
  e.stopPropagation()
  $(".userAction").slideToggle();
})
//点击修改密码
$("#changeWord").click(function (e) {
  if (!hasData('FUNC000002')) {
    return
  }
  e.stopPropagation()
  const status = $(".modalAction").css("display")
  $.alerModal({
    quiteBtn: true,
    title: "修改密码",
    type: "modal",
    width: '470',
    time: '1000',
    sureText: '保存',
    message: modalDom
  });
  if (passwordComplexity === 'null') {
    $(".alertModal .tips").hide();
  }
  bindModalEvent();
  $(".userAction").hide();
})
//推出登录
$(".login-out").click(function () {
  setCookie('behosDateStart', '')
  localStorage.removeItem('accessToken')
  setCookie('behosDateEnd', '')
  const otherLogoPm = otherLogo ? '?adLg=1' : '';
  const hideLogoPm = hideLogo ? '?hideLg=1' : '';
  window.location.href = 'login.html' + otherLogoPm + hideLogoPm;
})

//时间获取
function getTimeDetail() {
  const d = new Date();
  const days = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
  let sec = d.getSeconds()
  let min = d.getMinutes()
  let hour = d.getHours()
  let str = `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日 / ${days[d.getDay()]} / ${hour > 9 ? hour : '0' + hour}:${min > 9 ? min : '0' + min}:${sec > 9 ? sec : '0' + sec}`
  $(".dateDetail").html(str)
}

// 左侧菜单滚动到页面顶部
function bindMenu() {
  $("#contentIframe").contents().find('.partTitle a').eq(0).click(function () {
    $(".menuList").scrollTop(0)
  })
}

window.addEventListener('message', e => {
  //console.trace("token已清除index", e)
  let data = e.data || '{}';
  if (typeof data == 'string') {
    data = JSON.parse(data)
  }
  if (data.iframemessage) {
    localStorage.removeItem('accessToken')
    $.alerModal({
      gobackBtn: true,
      // quiteBtn: true,
      title: "提示",
      type: "modal",
      width: '470',
      time: 1000,
      cancalText: '我知道了',
      isFather: true,
      fatherWrapper: $("#mainBox", parent.document),
      sureBtn: false,
      message: data.data || '登录过期',
      callback: function () {
        clearAllCookie()
        window.location.href = 'login.html'
      }
    });
  }
});
