require("../css/qcScore.less");
const $ = require('jquery');
require('jquery-templates');
require('./modal.js');
const {post,getUrlArgObject,setBoxHeight,getCookie} = require('./utils.js');
const {api} = require('./api.js');
window.document.title="质控评分-"+getUrlArgObject("name");

$(function(){
//本页全局变量
  let global_flawData = {};    //缺陷数据
  const global_id=getUrlArgObject("id");
  const global_age = getUrlArgObject("age");
  const global_code = getUrlArgObject("code");
  let global_activeTab=$(".sub-menu .page.active").attr("code");  //当前激活菜单项
  let global_modules ={};   //模板数据缓存
  let global_flaws=[];  //缺陷条目列表缓存
  let global_selectedFlaw = {};    //新增时选中的条目信息
  getAllModules();
  $(".add-flaw").click(function(){
    getQcCasesEntry();
  });
function initMenu(data){
  const menu=[{id:0,name:"缺陷总览",parentId: -1,sonMode: []},...(data||[])];
  //菜单数据填充
  $("#subMenuTmpl").tmpl(menu).appendTo("#subMenu");
  $("#miniMenuTmpl").tmpl(menu).appendTo(".menu-mini ul");
  //菜单收起展开
  $(".sub-menu .list-1").on("click",function(){
    $(".sub-menu .list-1 .slide-up").removeClass('slide-up');
    $(this).toggleClass('slide-up');
    $(this).find("ul").slideToggle();
  });
  $(".sub-menu .list-1 li").on("click",function(e){
    e.stopPropagation();
  });
//收起菜单
  $(".slide-show").click(function(){
    $(".sub-menu,.copy-right").animate({"width":"60px"},function(){
      $(this).hide();
      $(".menu-mini").show();
    });
    $(".tab-container").animate({"margin-left":"60px"});
  });
  //展开菜单
  $(".slide-hide").click(function(){
    $(".menu-mini").hide();
    $(".sub-menu,.copy-right").show().animate({"width":"220px"},function(){
    });
    $(".tab-container").animate({"margin-left":"220px"});
  });
  //右侧内容切换
  $(".page").on("click",function(){
    $(".info-item .cont,.flaw-item,td").removeClass("active");   //清空缺陷定位背景
    const title = $(this).attr("code");
    if(title==="缺陷总览"||title==="谈话告知书"||title==="知情同意书"){
      $(".flaw-table .page-item").hide();
      $(".flaw-table,.flaw-table .page-item[code="+title+"]").show();
    }else{
      $(".flaw-table").hide();
    }

    //选中样式
    $(".sub-menu .active,.menu-mini .active").removeClass('active');
    const mItems = $(".sub-menu .page[code="+title+"],.menu-mini .page[code="+title+"]");
    mItems.addClass("active");
    mItems.parents(".list-1").addClass("active");
    //显示对应内容
    const code=$(this).attr("code");
    global_activeTab=code;
    //initModuleData();
    $(".content-item,.flaw-item").hide();
    $(".content-item[code='"+code+"']").show();
    showFlawList();
  });
}
//判断有无某一权限
function hasData(data){
  let trdObj = JSON.parse(getCookie("trdObj"))
  let lis = trdObj[global_code]
  if(!lis){
    return false
  }
  if(lis.indexOf(data)>-1){//有权限
      return true
  }
  return false;
}
//获取病例明细
function getRecordDetail(){
  post(api.getRecordDetail,{'behospitalCode':global_id}).then(function(res){
    if(res.data.code==='0'){
      const data = res.data.data;
   
      const {beHospital,result,msg} = data;
      const info=Object.assign(beHospital,result);
      initMenu(JSON.parse(result.menuData));
      $(".sub-menu>ul>li:first-child.page,.menu-mini>ul>li:first-child.page").addClass("active");
     global_activeTab=$(".sub-menu .page.active").attr("code");
      initPatientInfo(info);
      initContent(result.pageData);
      initList(msg);
      initScoreItem(msg);
      global_flawData=msg;
      setBoxHeight();
    }
  });
}

//填充患者信息
function initPatientInfo(data){
  const obj=Object.assign({},data,{age:!global_age||global_age=="null"?"-":global_age});
  $("#infoTmpl").tmpl(obj).appendTo("#patientInfo");
}
//显示病例模块明细
function initContent(data){
  const obj = JSON.parse(data);
  let info=[];
  let hml='',moduleId='';
  formatSpecPage(obj["谈话告知书"],"谈话告知书");
  formatSpecPage(obj["知情同意书"],"知情同意书");
  for(let k in obj){
    if(k==="谈话告知书"||k==="知情同意书"){
      continue;
    }
    for(let i in obj[k]){
      info=formatInfoData(k,obj[k][i]);
      moduleId=info.mode_id;
      if(global_modules[moduleId]){
        hml=initModuleData(moduleId,obj[k]);
        $.tmpl(hml,info).appendTo("#contentInfo");
      }else{
        const icon=require("../images/empty1.png");
        const sid=moduleId?"("+moduleId+")":"";
        const code=k.replace(/[^\u4e00-\u9fa5|a-zA-Z0-9]+/g,'');
        const emptyStr=`<div class="empty">
            <img src="${icon}" alt="空"/>
            <p>暂无信息～</p>
        </div>`;
        if(!$(".content-item[code="+code+"] .empty").length){  //显示一条空提示即可
          hml='<div class="content-item" code="'+code+'">' +
            '<h2 class="title">'+k+sid+'</h2>'+emptyStr+'</div>';
          $.tmpl(hml,{}).appendTo("#contentInfo");
        }
      }
    }
  }
  $(".content-item[code="+global_activeTab+"]").show();
  //console.log(obj)
}

function formatInfoData(k,data){
  let obj = {},name="";
  for(let i in data){
    if(i!=="mode_id"){
      name=i.replace(/[^\u4e00-\u9fa5|a-zA-Z0-9]+/g,"").replace(/^[0-9]+/,"a");    //过滤key中存在的特殊符号，模板会渲染不出来且不报错
      obj[name]=data[i].replace(/\n/g,"<br/>")||"";
    }else{
      obj[i]=data[i].replace(/\n/g,"<br/>")||"";
    }
  }
  return Object.assign({title:k},obj);
}

//知情同意书、谈话告知书
  function formatSpecPage(data,title){
    $("#appointBookTmpl").tmpl({title,data}).appendTo(".flaw-table");
    $(".page-anchor").on("click",function(){
      const code=$(this).attr("code");
      const pCode=$(this).parents("tr").attr("code");
      //菜单同步状态
      $(".sub-menu .page[code="+pCode+"]").parents(".list-1").click();
      $(".sub-menu .page[code="+pCode+"],.menu-mini .page[code="+pCode+"").click();
      //缺陷定位
      $(".info-item .cont,.flaw-item,td").removeClass("active");
      const flawItem=$(".flaw-item .title a[code="+code+"]");
      if(!flawItem.length){
        $.alerModal({"message":'模块数据缺失~',type:"tip",time:'1000',isFather: true, fatherWrapper: $(".flaw-table", parent.document)});
        return;
      }
      $(".flaw-item .title a[code="+code+"]").click();
      const anch=$(".flaw-item .title a[code="+code+"]").attr("href");
      $('#contentInfo').scrollTop($(anch).offset().top-60);
    });
  }

function initList(data){
  //$("#flawTotalList").tmpl({title:"缺陷总览",data:data}).appendTo(".flaw-table");
  formatSpecPage(data,"缺陷总览");
  $(".flaw-table").show();
  $(".flaw-table .page-item[code="+global_activeTab+"]").show();
  $(".slide-up").off("click").on("click",function(){
    const name = $(this).text();
    $("tr[code='"+name+"']").slideToggle();
    $(this).toggleClass("down");
  });
}

//评分项数据填充
function initScoreItem(data){
  $("#flaws .flaw-box").html("");
  let hasAu = hasData('FUNC000013')
  let hasAu2 = hasData('FUNC000012')
  for(let k in data){
    $("#flawTmpl").tmpl(data[k]).appendTo("#flaws .flaw-box");
  }
  showFlawList();
  $(".flaw-item .oper a").click(function () {
    const i = $(".flaw-item[code="+global_activeTab+"]").index($(this).parents(".flaw-item"));
    const code=$(this).attr("code");
    const isEdit = $(this).is(".edit-flaw");
    if(!hasAu)return
    if(isEdit&&hasAu){
      showModal('0',code,i);
    }else if(!isEdit&&hasAu2){
      showModal('1',code,i);
    }
  })
  $(".edit-flaw").css({"opacity":hasAu?"1":"0.5",cursor:hasAu?"pointer":"unset"});
  $(".del-flaw").css({"opacity":hasAu2?"1":"0.5",cursor:hasAu2?"pointer":"unset"});
  $(".flaw-item .title a[href]").click(function(){
    const id = $(this).attr("href");
    const anchors=$(this).attr("anchors").split(",");
    let ans = anchors.map((it)=>{
      return "#anchor"+it;
    });
    $(".info-item .cont,.flaw-item,td").removeClass("active");
    $(ans.join(",")).addClass("active");
    $(this).parents(".flaw-item").addClass("active");
  });
}

//显示缺陷列表
function showFlawList(){
  const hml = $(".flaw-item[code="+global_activeTab+"]");
  if(hml.length){
    hml.show();
    $("#flaws .empty").hide();
  }else{
    $("#flaws .empty").length?$("#flaws .empty").show():$("#emptyTmpl").tmpl().appendTo("#flaws .flaw-box");
  }
}

//删除评分项
function delScore(id,info){
  const param={
    'behospitalCode':global_id,
    'optResultAlgVO':{
      'id':id
    }
  };
  post(api.delScore,param).then(function(res){
    if(res.data.code==='0'){
      $("#delModal").hide();
      updateFlaws(res.data.data);
      $("#anchor"+info.pageKeyList[0]).removeClass("active");
      $.alerModal({"message":"删除成功",type:"tip",time:'1000'});
    }
  });
}
//修改评分项
function editScore(info){
  const param={
    "behospitalCode": global_id,
    "optResultAlgVO": info
};
  post(api.editScore,param).then(function(res){
    if(res.data.code==='0'){
      $("#delModal").hide();
      updateFlaws(res.data.data);
      $.alerModal({"message":"修改成功",type:"tip",time:'1000'});
    }
  });
}
//添加评分项
function addScore(info){
  const optResultAlgVO = {
    "casesEntryId": info.casesEntryId,
    "casesId": info.casesId,
    "casesScore": info.caseScore,
    "code": info.code || "",
    "id": info.id || "",
    "info":info.info || "",
    "isReject": info.isReject,
    "msg": info.msg || "",
    "score": info.score
  }
  const param={
    "behospitalCode": global_id,
    "optResultAlgVO": optResultAlgVO
  };
  post(api.addScore,param).then(function(res){
    if(res.data.code==='0'){
      $("#delModal").hide();
      updateFlaws(res.data.data);
      $.alerModal({"message":"添加成功",type:"tip",time:'1000'});
    }
  });
}


//显示删除/修改弹窗
function showModal(flag,code,i){
  $("#delModal .modal-body").html("");
  $("#delModal").show();
  $(".info-item .cont,.flaw-item .title,td").removeClass("active");
  //事件解绑
  $("#delModal .confirm").off("click");
  $("#qcScore,#qcMsg").off("input");
  const flawsList = formatFlawKeys(global_flawData);
  const info = flawsList[global_activeTab]&&flawsList[global_activeTab][i];
  if(flag==='0'){   //修改
    $("#delModal .title").text("修改");
    $("#delModal .confirm").text("保存");
    $("#editTmpl").tmpl(info).appendTo("#delModal .modal-body");
    //分数输入验证
    $("#qcScore").on("input",function(){
      const val=$(this).val();
      if(/^[0-9]\d*$|^[0-9]\d*(.\d)?$/.test(val) && val <= 100){
        $(".edit-box .warning").hide();
      }else{
        $(".edit-box .warning .red").text("支持≥0且≤100的数字输入，最多保留小数点后1位~");
        $(".edit-box .warning").show();
      }
    });
    //提示信息输入验证
    $("#qcMsg").on("input",function(){
      const val=$(this).val();
      $(this).attr("title",val)
      if(val.trim()){
        $(".edit-box .warning").hide();
      }else{
        $(".edit-box .warning .red").text("提示信息不能为空~");
        $(".edit-box .warning").show();
      }
    });
    $("#delModal .confirm").click(function(){
      if($(".edit-box .warning").is(":visible")){
        return;
      }
      const obj = Object.assign({},info,{msg:$("#delModal #qcMsg").val(),score:$("#delModal #qcScore").val()});
      editScore(obj);
    });
  }else if(flag==='2'){   //新增
    $("#delModal .title").text("新增");
    $("#delModal .confirm").text("保存");
    $("#addFlawTmpl").tmpl().appendTo("#delModal .modal-body");
    $("#flawDropTmpl").tmpl({info:code}).appendTo("#delModal .modal-body ul");
    //分数输入验证
    $("#addQcScore").on("input",function(){
      const val=$(this).val();
      if(/^[0-9]\d*$|^[0-9]\d*(.\d)?$/.test(val) && val <= 100){
        $(".add-box .warning").hide();
      }else{
        $(".add-box .warning .red").text("支持≥0且≤100的数字输入，最多保留小数点后1位~");
        $(".add-box .warning").show();
      }
    });
    //提示信息输入验证
    $("#addQcMsg").on("input",function(){
      const val=$(this).val();
      $(this).attr("title",val)
      if(val.trim()){
        $(".add-box .warning").hide();
      }else{
        $(".add-box .warning .red").text("提示信息不能为空~");
        $(".add-box .warning").show();
      }
    });
    $("#delModal .confirm").click(function(){
      if(!$(".flaw-drop-input").attr("code")){
        $(".add-box .warning .red").text("请选择质控条目~");
        $(".add-box .warning").show();
        return;
      }
      const msg=$("#delModal #addQcMsg").val();
      const score=Number($("#delModal #addQcScore").val());
      // if($(".add-box .warning").is(":visible")||!msg.trim()||!score){
      //   return;
      // }
      // console.log($(".flaw-drop-input")[0],9999999)
      const obj = Object.assign({},global_selectedFlaw,{msg,score});
      addScore(obj);
    });
  }else{
    $("#delModal .title").text("删除评分");
    $("#delModal .confirm").text("确定");
    $("#delModal .modal-body").html('<p>确定要删除该评分记录吗？</p>');
    $("#delModal .confirm").click(function(){
      delScore(code,info);
    });
  }
}
//缺陷列表key值去掉特殊符号
function formatFlawKeys(data){
    const obj = {};
    for(let k in data){
      obj[k.replace(/[^\u4e00-\u9fa5|a-zA-Z0-9]+/g,'')]=data[k];
    }
    return obj;
  }
  //获取缺陷条目下拉列表
  function getQcCasesEntry(name){
  const id=$("#subMenu [code="+global_activeTab+"]").attr("mode");
    const param = {
      'behospitalCode':global_id,
      'entryName':name||"",
      'modeId':id
    };
    post(api.findQcCasesEntry,param).then(function(res){
      if(res.data.code==='0'){
        const data = res.data.data;
        if(name){
          global_flaws=data;
          $("#delModal .modal-body ul").html("");
          $("#flawDropTmpl").tmpl({info:data}).appendTo("#delModal .modal-body ul");
        }else{
          global_flaws=data;
          if($("#delModal").css("display") == "block"){
            $("#flawDropTmpl").tmpl({info:data}).appendTo("#delModal .modal-body ul");
            return
          }
          showModal('2',data);
        }
      }
    });
  }
//增加条目弹窗元素事件
  $("body").on("click",".add-box .flaw-drop-input",function(){
    $(".add-box .drop-box").addClass("show");
  });
  $("body").on("blur",".add-box .flaw-drop-input",function(){
    setTimeout(function(){
      $(".add-box .drop-box").removeClass("show");
    },300)
  });
  $("body").on("input",".add-box .flaw-drop-input",function(){
    $(this).attr({"code":"","title":$(this).val().trim()});
    getQcCasesEntry($(this).val().trim());
  });
  $("body").on("click",".add-box .drop-box li",function(){
    const n = $(this).attr("idx");
    const flaw=global_flaws[n];
    const {score,msg,entryName,casesEntryId}=flaw;
    global_selectedFlaw=flaw;
    $(".flaw-drop-input").val(entryName).attr({"code":casesEntryId,"title":entryName});
    $("#addQcMsg").val(msg).attr("title",msg);
    $("#addQcScore").val(score);
    $(".add-box .warning").hide();
    $(".add-box .drop-box").removeClass("show");
  });

//更新缺陷列表
  function updateFlaws(info){
  $("#patientInfo .level").text("质控等级："+info.level);
  $("#patientInfo .score").text("质控得分："+info.scoreRes);
  const param = {
    'behospitalCode':global_id,
    'paramStr':[
      "msg"
    ]
  };
    post(api.getRecordDetail,param).then(function(res){
      if(res.data.code==='0'){
        const data = res.data.data;
        const {msg} = data;
        initScoreItem(msg);
        global_flawData=msg;
      }
    });
  }

//获取病例模板
  function getInfoModule(moduleId){
    const param = {
      moduleId:moduleId
    };
    post(api.getInfoModule,param).then(function(res){
      if(res.data.code==='0'){
        const data = res.data.data;
        cachemoduleDatas(data);
        getRecordDetail();
      }
    });
  }

  //模板数据缓存
  function cachemoduleDatas(data){
    const moudle=data.moduleDetail;
    global_modules[data.modeName]=[];
    for(let i in moudle){
      global_modules[data.modeName].push(moudle[i]);
    }
  }

//初始化模板
  function initModuleData(mid,obj){
    const n = obj.length;
    const module=global_modules[mid].moduleDetail;
    const key = global_modules[mid].modeName.replace(/[^\u4e00-\u9fa5|a-zA-Z0-9]+/g,'');
    let hml = '<div class="content-item" code="'+key+'">' +
      '<h2 class="title">'+global_modules[mid].modeName+'('+mid+')</h2>'+
      (n>1?'<div class="container">':'<div class="container content-ht">');

    for(let i in module){
      hml=hml+'<div class="info-item">';
      for(let j=0;j<module[i].length;j++) {
        const detal = module[i][j].questionDTO;
        const {tagType} = detal;
        switch (tagType) {
          case 1:
            hml = hml + simpleStructure(detal,obj);
            break;
          case 4:
            hml = hml + combineStructure(detal);
            break;
          default:
            break;
        }
      }
      hml = hml+"</div>"
    }
    return hml+"</div></div>";
  }

  //基础类型结构生成
  function simpleStructure(data,obj){
    const {name, val,monoLine,addLine,position,bold,retract,id} = data;
    if(name==="手术记录表格-1"){
      const value = val.replace("【","").replace("】","");
      const diag = obj[0][value]?JSON.parse(obj[0][value]):"";
      let thml=`<div class="cont" style="width: 100%;" id="anchor${id}">`;
      thml+=$("#tableTmpl").tmpl({k:"手术信息",data:diag})[0].outerHTML+"</div>";
      return thml;
    }
    if(name==="出院诊断表格-1"){
      const value = val.replace("【","").replace("】","");
      const diag = obj[0][value]?JSON.parse(obj[0][value]):"";

      let thml=`<div class="cont" style="width: 100%;" id="anchor${id}">`;
      thml+=$("#tableTmpl").tmpl({k:"出院诊断",data:diag})[0].outerHTML+"</div>";
      return thml;
    }
    const posClass = position===1?'text-left':'';
    const boldClass = bold===1?'text-bold':'';
    const retractClass = retract===1?'text-indent':'';
    const lineHml = ('<p class="'+posClass+' '+boldClass+' '+retractClass+'">'+ extractVars(val)+'</p>');
    const txtHml = ('<p style="display: inline;vertical-align: middle;" class="'+posClass+' '+boldClass+' '+retractClass+'">'+ extractVars(val)+'</p>');

    let hml = addLine||monoLine?`<div class="cont ${posClass}" style="width: 100%;" id="anchor${id}">`:`<div class="cont" id="anchor${id}">`;
    hml=hml+`<span class="label">${name}</span>`+ (addLine?lineHml:txtHml)+ `</div>`;
    return hml;
  }

  //组合类型结构生成
  function combineStructure(data){
    const {name,questionMapping,id} = data;
    let hml='<div class="inner-table"><table>';
    const colNum = Math.ceil(questionMapping.length/2);
    let tdVal='';
    const regexp = /(【(.+?)】)/g;
    for(let i=0;i<questionMapping.length;){
      if(questionMapping[i+1]){
        tdVal="<td id='anchor"+questionMapping[i].id+"'>"+questionMapping[i].name+extractVars(questionMapping[i].val)+"</td><td id='anchor"+questionMapping[i+1].id+"'>"+questionMapping[i+1].name+extractVars(questionMapping[i+1].val)+"</td>";
      }else{
        tdVal="<td id='anchor"+questionMapping[i].id+"'>"+questionMapping[i].name+extractVars(questionMapping[i].val)+"</td><td></td>";
      }
      if(i==0){
        hml=hml+`<tr><td rowspan="${colNum}" id='anchor${id}'>${name}</td>${tdVal}`;
      }else{
        hml=hml+`<tr>${tdVal}`;
      }
      hml=hml+"</tr>";
      i=((i+2)>questionMapping.length?i+1:i+2)
    }
    hml=hml+"</table></div>";
    return hml;
  }

  //抽取变量
  function extractVars(org){
    const regexp = /(【(.+?)】)/g;
    const arr = org.split(regexp);
    //console.log(arr)
    let htl = '',val='';
    for(let i=0;i<arr.length;i++){
      val = arr[i].indexOf("【")!=-1?'':(arr[i-1]&&arr[i-1].indexOf("【")!=-1?"{{html "+arr[i]+"}}":arr[i]);
      htl=htl+val;
    }
    return htl;
  }
//获取所有模板
  function getAllModules(){
  const param={
    hospitalId:getUrlArgObject("hid"),
    modeId:''
  };
    post(api.getModuleById,param).then((res)=>{
      if(res.data.code==='0') {
        const data = res.data.data;
        global_modules=data;
        getRecordDetail();
        $("#loading").hide();
      }
    });
  }

});

