require("../css/index.less");
const $ = require('jquery');
require('jquery-templates');
const md5 = require('js-md5');
require("./modal.js")
const {api} = require('./api.js')
const {post,pageMap,delCookie,setCookie,getCookie,focusMenuItem} = require('./utils.js');
let userInfo={};
$(function(){
  getMenu();
  getOwnDept();
  setInterval(() => {
      getTimeDetail()
  }, 1000);
  //菜单展开收起
  sureChangeWord()
  $(".main").css({
    height:$(window).height()-52+'px'
  })
  $(window).resize(function(){
    $(".main").css({
      height:$(window).height()-52+'px'
    })
  })
  $("body").on('focus',".modalAction input",function(){
    $(this).attr("type","password")
  })
  $(window).click(function(e){
    $(".userAction").css("display","none")
  })
  $("#changeWord").css("opacity",hasData('FUNC000002')?'1':'0.5').hover(function(){
    $(this).css("color","#777777")
  })
  // $("#contentIframe").attr("src",hasData('YH-KZT')?'console.html':hasData('YH-KZTKS')?'deptConsole.html':'console.html');
  
});
//判断有无某一权限
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 initMenu(data,userInfo){
  //菜单数据填充
  $("#menuTmpl").tmpl(data).appendTo(".menu ul");
  $("#miniMenuTmpl").tmpl(data).appendTo(".menu-mini ul");
  //用户数据填充
  $("#userName").text(userInfo.linkman);
  //初始菜单选中
  const firstM = $(".menu .page").eq(0);
  firstM.addClass("active");
  if(firstM.is(".YH-KZT")||firstM.is(".YH-KZTKS")){
  // if($(".menu .page").eq(0).is(".YH-KZT")){
    $(".container").addClass("console-cont");
  }
  //菜单收起展开
  $(".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();
  });
//收起菜单
  $(".slide-hide").click(function(){
    $(".menu,.copy-right").animate({"width":"60px"},function(){
      $(this).hide();
      $(".menu-mini").show();
    });
    $(".main").animate({"margin-left":"60px"});
  });
  //展开菜单
  $(".slide-show").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");
    if(code === 'YH-KZT'||code === 'YH-KZTKS'){
      // if(code === 'YH-KZT'){
      $(".container").addClass("console-cont");
    }else{
      $(".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);
  });
}

//获取科室列表
function getOwnDept(){
  // if(hasData('FUNC000058')){
      setCookie("deptList",JSON.stringify([]))
      post(api.getDept,{}).then((res)=>{
          let data = res.data;
          if(data.code == 0){
              let result = data.data
              setCookie("deptList",JSON.stringify(result))
          }
        })
  // }
}
function getMenu(){
  post(api.getMenu).then(function(res){
    if(res.data.code==='0'){
      const data = res.data.data;
      initMenu(data.menuWrappers,data.userLoginDTO);
      userInfo = data.userLoginDTO
      setCookie("hospital",data.basHospitalInfoDTO.name)
      setCookie("hospitalid",data.basHospitalInfoDTO.id)
      getAllCode(data.menuWrappers);
    }
  })
};
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)
      }
    }
  }
  // $("#contentIframe").attr("src",hasData('YH-KZT')?'console.html':hasData('YH-KZTKS')?'deptConsole.html':'console.html');
  if(hasData('YH-KZT',lis)){
    focusMenuItem("YH-KZT");
  }else if(hasData('YH-KZTKS',lis)){
    focusMenuItem("YH-KZTKS");
  }
  setCookie("codeLis",JSON.stringify(lis))
  setCookie("trdObj",JSON.stringify(trdObj))
}
function sureChangeWord(){
  $(document).on('click','.sureChange',function(){
    let oldword = $(".oldword").val().trim()
    let newword = $(".newword").val().trim()
    let sureword = $(".sureword").val().trim()
    if(!oldword){
      $(".modalAction .waring i").html('请输入原密码')
      return
    }else if(!newword){
      $(".modalAction .waring i").html('请输入新密码')
      return
    }else if(!sureword){
      $(".modalAction .waring i").html('请确认新密码')
      return
    }else if(newword != sureword){
      $(".modalAction .waring i").html('两次密码不一致')
      return
    }
    $(".modalAction .waring i").html('')
    changeWord(oldword,newword)
  })
}
function changeWord(oldword,newword){
  post(api.midifyPassword,{
    "modifyPassword": md5(newword),
    "password": md5(oldword)
  }).then(function(res){
    const data = res.data;
    if(data.code==='0'){
      window.location.href = './login.html'
    }else{
      $(".oldWaring").html(data.msg)
      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({
    title:"修改密码",
    type:"modal",
    width:'450',
    time:'1000',
    sureText:'保存',
    message:`
    <div class="modalAction">
      <p><span>原密码：</span><input type="text" placeholder="请输入原密码" class="oldword" autocomplete="off"><i class="oldWaring"></i></p>
      <p><span>新密码：</span><input type="text" placeholder="请输入新密码" class="newword" autocomplete="off"></p>
      <p><span>确认新密码：</span><input type="text" placeholder="请输入新密码" class="sureword" autocomplete="off"></p>
      <p class="waring"><span></span><i></i></p>
    </div>
  `});
  $(".userAction").hide();
})
//推出登录
$(".login-out").click(function(){
  delCookie('accessToken')
})

//时间获取
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)
}