require("../css/editableDetail.less");
const $ = require('jquery');
require('jquery-templates');
require('./modal.js');
const {post,getUrlArgObject} = require('./utils.js');
const {api,editApi} = require('./api.js');

$(function(){
//本页全局变量
  let global_wholeData={};
  let global_recId = '';
  let global_modules ={};   //模板数据缓存
  getAllModules();
  //window.document.title=(showCheckBtns?"质控核查-":"质控评分-")+getUrlArgObject("name");

//获取病例明细
function getRecordDetail(){
  post(editApi.getDataEdit).then(function(res){
    if(res.data.code==='0'){
      const data = res.data.data;
      const { wholeData,modeId,recId } = data;
      global_recId=recId;
      initContent(modeId,wholeData);
    }else{
        $.alerModal({"message":res.data.msg||'获取数据失败',type:"tip",time:'1000'});
    }
  }).catch((error)=>{
      $.alerModal({"message":error,type:"tip",time:'1000'});
  });
}

//保存事件注册
    function saveDataEvent(){
      $("#saveBtn").off('click').on("click",function(){
          saveData();
      })
    }

    //保存数据
    function saveData(){
        const datasDom = $(".cont div[contenteditable=\"true\"]");
        let valName = '',obj={};
        for(let i=0;i<datasDom.length;i++){
            valName = $(datasDom[i]).attr("valname");
            obj[valName]=$(datasDom[i]).text();
        }
        global_wholeData = Object.assign({},global_wholeData,obj);
        let param = {wholeData:JSON.stringify(global_wholeData),hospitalId:getUrlArgObject("hid"),recId:global_recId};
        console.log(11,obj,global_wholeData);
        post(editApi.saveDataEdit,param).then((res)=>{
          if(res.data.code==='0'){
              $.alerModal({"message":"保存成功",type:"tip",time:'1000',win:true});
          }else{
              $.alerModal({"message":res.data.msg||"保存失败",type:"tip",time:'1000'});
          }
        }).catch((error)=>{
            $.alerModal({"message":error,type:"tip",time:'1000'});
        })
    }

//显示病例模块明细
function initContent(moduleId,data){
  const obj = JSON.parse(data);
  global_wholeData=obj;
  let info=[];
  let hml='';
  //formatSpecPage(obj["谈话告知书"],"谈话告知书");
  //formatSpecPage(obj["知情同意书"],"知情同意书");
  info=formatInfoData(obj);
  if(global_modules[moduleId]){
    hml=initModuleData(moduleId,obj);
  }else{
    info={};
    hml=`<div class="empty">
        <img src="${icon}" alt="空"/>
        <p>暂无信息～</p>
    </div>`;
  }
  $(".empty").remove();
  $.tmpl(hml,info).appendTo("#contentInfo");
  saveDataEvent();
  //console.log(obj)
}

function formatInfoData(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({},obj);
}

//初始化模板
  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">');

      
      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){
    //console.log(data,obj,7878787)
    const {name, val,monoLine,addLine,position,bold,retract,id} = data;
    const noEdits = `'医师签名','时间','出院计划','修正诊断','4.治疗监测计划','姓名','家庭住址','出生日期','性别','工作单位','身份证号','民族','年龄','联系人(关系)','职业','婚姻状况','出生地','入院日期','记录日期','病史陈述者','电话','户口地址','目前使用的药物','成瘾药物','3.诊疗计划','1.需求评估','2.预期目标'`;
    let nameStr = name.replace("：","").replace(":","");
    const editable = noEdits.indexOf(nameStr)===-1;console.log(11,name)
    const posClass = position===1?'text-left':'';
    const boldClass = bold===1?'text-bold':'';
    const retractClass = retract===1?'text-indent':'';
    const valName = extractVars(val);
    const valT = valName.replace(/[{{html |}}]/g,"")
    const lineHml = (`<div contenteditable="${editable?true:false}" valname="`+valT+`" class="'+posClass+' '+boldClass+' '+retractClass+'">${extractVars(val)}</div>`);
    const txtHml = (`<div contenteditable="${editable?true:false}" valname="`+valT+`" class="fl ${posClass} ${boldClass} ${retractClass}">${ extractVars(val)}</div>`);

    let hml = addLine||monoLine?`<div class="cont clearfix ${posClass}" style="width: 100%;" id="anchor${id}">`:`<div class="cont" id="anchor${id}">`;
    hml=hml+`<span class="label ${addLine?'':'fl'}">${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);
    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;
    }
    //console.log(11,org,arr,htl)
    return htl;
  }
//获取所有模板
  function getAllModules(){
    const param={
      hospitalId:getUrlArgObject("hid")||1,
      modeId:''
    };
    post(api.getModuleById,param).then((res)=>{
      if(res.data.code==='0') {
        const data = res.data.data;
        global_modules=data;
        getRecordDetail();
        $("#loading").hide();
      }
    });
  }
});

