require("../css/appealUserPage.less");
const $ = require('jquery');
require('jquery-templates');
require('./modal.js');
const { post, getUrlArgObject, setBoxHeight, getCookie, getLocal, initScroll } = require('./utils.js');
const { api, ywCheckApi } = require('./api.js');
let checkOk = require('./../images/checkOk.png')
const adLogo = require("../images/adlogo.png")
if (localStorage.getItem('toLogin') === '1') {
  window.location.href = '../login.html';
}
$(function () {
  const hideLogo = getUrlArgObject("hideLg");
  if (hideLogo) {
    $(".sub-menu .logo img,.copy-right").remove();
    $(".menu-mini .logo").text("");
  }
  const otherLogo = getUrlArgObject("adLg");
  if (otherLogo) {
    $(".logo img").attr("src", adLogo);
    $(".menu-mini .logo").text("艾登");
    $(".copy-right").remove();
  }
  //本页全局变量
  let global_flawData = {};    //缺陷数据
  let global_flawDataPay = {};    //缺陷数据
  const global_id = getUrlArgObject("id");
  const global_hid = getUrlArgObject("hid");
  const casesName = getUrlArgObject("casesName");
  let global_check;
  let global_check_home, global_check_show;
  let global_entryName, global_casesEntryId
  const global_code = getUrlArgObject("code");
  let global_activeTab = $(".sub-menu .page.active").attr("code");  //当前激活菜单项
  let global_modules = {};   //模板数据缓存
  let global_flaws = [];  //缺陷条目列表缓存
  let global_selectedFlaw = {};    //新增时选中的条目信息
  let global_checkers = [];    //审核人列表
  getAllModules();

  const form = getUrlArgObject("form") || 0;
  window.document.title = "质控申诉-" + getUrlArgObject("name");
  //新增申诉点击事件

  $(".add-flaw").click(function () {
    showModal('2');
  });

  function showAppealDetailEvent() {
    //申诉状态点击事件
    $(".flaw-item").off("click").on("click", ".title .btn", function () {
      showModal("1", $(this).attr("data_id"), $(this).attr("data_type"), $(this).attr("data_casesEntryId"), $(this).attr("data_qcresultDetailId"));
    });
  }

  function initMenu(data) {
    const menu = [{ id: 0, name: "缺陷总览", parentId: -1, sonMode: [] }, ...(data || [])];
    //菜单数据填充
    $("#subMenuTmpl").tmpl(menu).appendTo("#subMenu");
    $("#miniMenuTmpl").tmpl(menu).appendTo(".menu-mini ul");
    //菜单收起展开
    $(document).on("click", ".sub-menu .list-1", 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 === "知情同意书" || title === '医嘱信息' || title === '检验信息' || title === '检查信息' || title === '护理信息' || title === '其他信息') {
        if (title === "缺陷总览") {
          getRecordDetailUpdate()
        }
        $(".flaw-table .page-item").hide();
        $(".flaw-table,.flaw-table .page-item[code=" + title + "]").show();
        $(".flaw-table").show();
      } else {
        $(".flaw-table").hide();
      }
      iframeShow(title)
      //选中样式
      $(".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;
      getQcCasesEntry();
      //initModuleData();
      $(".content-item,.flaw-item").hide();
      $(".content-item[code='" + code + "']").show();
      showFlawList();
      $("#contentInfo").scrollTop(0)
    });
    // initScroll("subMenu","Y",2)
  }
  function iframeShow(title) {
    if (title === '医嘱信息') {
      $("#pacsIframeIn,#assistIframeIn,#pacsDetailIframeIn,#contentNursing").css("display", "none")
      $("#contentIframeIn").css({ display: 'block' }).attr("src", 'advice.html').contents().find(".adviceWrp").height(window.innerHeight - $("#patientInfo").height() - 20 + 'px')
      $(window).resize(function () {
        $("#contentIframeIn").contents().find(".adviceWrp").height(window.innerHeight - $("#patientInfo").height() - 20 + 'px')
      });
    } else if (title === '检验信息') {
      $("#contentIframeIn,#assistIframeIn,#pacsDetailIframeIn,#contentNursing,#contentOther").css("display", "none")
      $("#pacsIframeIn").css({ display: 'block' }).attr("src", 'pacs.html').contents().find(".pacsWrp").height(window.innerHeight - $("#patientInfo").height() - 20 + 'px')
      $(window).resize(function () {
        $("#pacsIframeIn").contents().find(".pacsWrp").height(window.innerHeight - $("#patientInfo").height() - 20 + 'px')
      });
    } else if (title === '检查信息') {
      $("#contentIframeIn,#pacsIframeIn,#pacsDetailIframeIn,#contentNursing,#contentOther").css("display", "none")
      $("#assistIframeIn").css({ display: 'block' }).attr("src", 'assist.html').contents().find(".assistWrp").height(window.innerHeight - $("#patientInfo").height() - 20 + 'px')
      $(window).resize(function () {
        $("#assistIframeIn").contents().find(".assistWrp").height(window.innerHeight - $("#patientInfo").height() - 20 + 'px')
      });
    } else if (title === '护理信息') {
      $("#pacsIframeIn,#assistIframeIn,#pacsDetailIframeIn,#contentIframeIn,#contentOther").css("display", "none")
      $("#contentNursing").css({ display: 'block' }).attr("src", 'nursing.html').contents().find(".nursingWrp").height(window.innerHeight - $("#patientInfo").height() - 20 + 'px')
      $(window).resize(function () {
        $("#contentNursing").contents().find(".nursingWrp").height(window.innerHeight - $("#patientInfo").height() - 20 + 'px')
      });
    } else if (title === '其他信息') {
      $("#pacsIframeIn,#assistIframeIn,#pacsDetailIframeIn,#contentIframeIn,#contentNursing").css("display", "none")
      $("#contentOther").css({ display: 'block' }).attr("src", 'other.html').contents().find(".otherWrp").height(window.innerHeight - $("#patientInfo").height() - 20 + 'px')
      $(window).resize(function () {
        $("#contentOther").contents().find(".otherWrp").height(window.innerHeight - $("#patientInfo").height() - 20 + 'px')
      });
    } else {
      $("#contentIframeIn,#pacsIframeIn,#pacsDetailIframeIn,#assistIframeIn,#contentNursing,#contentOther").css({ display: 'none' })
    }
  }

  //获取病例明细
  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, checkStatus, drgs, mrStatus, checkShow } = data;
        global_check = checkStatus
        global_check_home = mrStatus
        global_check_show = checkShow;
        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");
        if (form == 44 && casesName != '缺陷总览') {
          //选中样式
          $(".sub-menu .active,.menu-mini .active").removeClass('active');
          const mItems = $(".sub-menu .page[code=" + casesName + "],.menu-mini .page[code=" + casesName + "]");
          mItems.addClass("active");
          mItems.parents(".list-1").addClass("active");
          mItems.parents(".list-1").addClass("slide-up");
          mItems.parents("ul").show()
          //  //显示对应内容

          //initModuleData();
          global_activeTab = $(".sub-menu .page.active").attr("code");
          getQcCasesEntry();
          showFlawList();
          $("#contentInfo").scrollTop(0)
        } else {
          $(".subMenu >li:first-child.page,.menu-mini>ul>li:first-child.page").addClass("active");
          global_activeTab = $(".sub-menu .page.active").attr("code");
        }
        $(".operation").show()
        initPatientInfo(info);
        initContent(result.pageData);
        initList(msg);
        initScoreItem(msg);
        global_flawData = msg;
        global_flawDataPay = drgs;
        setBoxHeight();
        changePay()
      }
    });
  }
  function getRecordDetailUpdate() {
    post(api.getRecordDetail, { 'behospitalCode': global_id }).then(function (res) {
      if (res.data.code === '0') {
        const data = res.data.data;
        const { beHospital, result, msg, checkStatus, drgs } = data;
        // global_check = checkStatus
        // const info=Object.assign(beHospital,result);
        // initMenu(JSON.parse(result.menuData));
        // $(".subMenu >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, null, 1);
        initScoreItem(msg);
        global_flawData = msg;
        global_flawDataPay = drgs;
        // setBoxHeight();
        // changePay()
      }
    });
  }
  function changePay() {
    $(document).on('click', ".titleSpecial span", function () {
      let type = $(this).attr("data-type")
      if (type == 1) {
        initList(global_flawDataPay, type);
      } else {
        initList(global_flawData, type);
      }
    })
  }
  //填充患者信息
  function initPatientInfo(data) {
    const obj = Object.assign({}, data, { checkState: global_check, checkStateHome: global_check_home });
    $("#infoTmpl").tmpl(obj).appendTo("#patientInfo");
    /*$(".check").on("click", function(){
      checkQc()
    })*/
    $(".ywCheck").on("click", function () {
      checkYwQc()
    })
  }
  //显示病例模块明细
  function initContent(data) {
    const obj = JSON.parse(data);
    let info = [];
    let hml = '', moduleId = '';
    formatSpecPage(obj["谈话告知书"], "谈话告知书");
    formatSpecPage(obj["知情同意书"], "知情同意书");
    // formatSpecPage(obj["医嘱信息"],"医嘱信息");
    $(".content-box").show();
    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, type) {
    $(".page-item[code='缺陷总览']").remove()
    $("#appointBookTmpl").tmpl({ title, data }).appendTo(".flaw-table");
    setBoxHeight();
    $(".page-anchor").on("click", function () {
      const code = $(this).attr("code");
      const pCode = $(this).parents("tr").attr("code").replace(/[^\u4e00-\u9fa5|a-zA-Z0-9]+/g, '');
      //菜单同步状态
      $(".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");
      if ($(anch)[0]) {
        $('#contentInfo').scrollTop($(anch).offset().top - 60);
      }
    });

    if (global_activeTab == "缺陷总览") {
      $(".check").css("display", "none")
    } else {
      $(".check").css("display", "block")
    }

    if (type && type == 1) {
      $(".titleNo").css({
        'background-color': '#00A1FF',
        'color': '#fff',
        'border-color': '#00A1FF'
      })
      $(".titlePay").css({
        'background-color': '#fff',
        'border': '1px solid #777',
        'border-right': 0,
        'color': '#777'
      })
      setBoxHeight()
    } else if (type && type == 2) {
      $(".titleNo").css({
        'background-color': '#fff',
        'border': '1px solid #777',
        'border-left': 0,
        'color': '#777'
      })
      $(".titlePay").css({
        'background-color': '#00A1FF',
        'color': '#fff',
        'border-color': '#00A1FF'
      })
      setBoxHeight()
    }
  }

  function initList(data, type, num) {
    //$("#flawTotalList").tmpl({title:"缺陷总览",data:data}).appendTo(".flaw-table");
    formatSpecPage(data, "缺陷总览", type);
    // $(".flaw-table").show();
    // $(".flaw-table .page-item[code=" + global_activeTab + "]").show();
    if (form == 44 && casesName != '缺陷总览') {
      $(".flaw-table").hide();
      $(".flaw-table .page-item[code=" + global_activeTab + "]").show();
    } else {
      $(".flaw-table").show();
      $(".flaw-table .page-item[code=" + global_activeTab + "]").show();
    }
    if (num) {
      $(".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("");
    for (let k in data) {
      $("#flawTmpl").tmpl(data[k]).appendTo("#flaws .flaw-box");
    }
    if (form == 44) {
      $(".add-flaw").hide()
      $(".edit-flaw").hide()
    }
    showFlawList();
    $(".flaw-item .oper a").unbind("click").click(function () {
      const i = $(".flaw-item[code=" + global_activeTab + "]").index($(this).parents(".flaw-item"));
      const code = $(this).attr("code");
      showModal('0', code, i);  //申诉

      //审核人下拉渲染
      $("#delModal .checker-drop-box ul").html("");
      $("#flawDropTmpl").tmpl({ info: global_checkers }).appendTo("#delModal .checker-drop-box ul");
    })
    $(".flaw-item .title a[href]").unbind("click").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");
    }
    showAppealDetailEvent();
  }

  //申诉
  function appealItem(info) {
    const param = {
      "behospitalCode": global_id,
      ...info
    };
    post(api.addAppealInfo, param).then(function (res) {
      if (res.data.code === '0') {
        $("#delModal").hide();
        updateFlaws(res.data.data);
        $.alerModal({ "message": "申诉成功", type: "tip", time: '1000', win: true });
      } else {
        $.alerModal({ "message": res.data.msg || '申诉失败,请重试~', type: "tip", time: '1000', isFather: true, win: 'warn', fatherWrapper: $("#mainBox", parent.document) });

      }
    }).catch(() => {
      $.alerModal({ "message": res.data.msg || '申诉失败,请重试~', type: "tip", time: '1000', isFather: true, win: 'default', fatherWrapper: $("#mainBox", parent.document) });

    });
  }
  //新增申诉
  function addScore(info) {
    let param = {};
    console.log(info);
    if (info.type === '1') {
      param = {
        "appealExplain": info.appealExec,
        "appealOperationType": info.type,
        "appealType": 1,
        "behospitalCode": global_id,
        "casesEntryId": info.casesEntryId,
        "casesEntryMsg": info.msg,
        "casesEntryName": info.entryName,
        "checkId": info.userId,
        "modeId": $("#subMenu [code=" + global_activeTab + "]").attr("mode"),
        "modeName": global_activeTab,
        "remark": info.explainInfo,
        "value": info.score,
        "casesScore": info.caseScore,
        "msg": info.msg,
        "isReject": info.isReject,
        "qcresultDetaiValue": info.score,
      };
    } else {
      param = {
        "appealExplain": info.appealExec,
        "appealOperationType": info.type,
        "appealType": 1,
        "behospitalCode": global_id,
        "checkId": info.userId,
        "modeName": global_activeTab,
        "remark": info.explainInfo,
      };
    }
    post(api.addAppealInfo, param).then(function (res) {
      if (res.data.code === '0') {
        $("#delModal").hide();
        //updateFlaws(res.data.data);
        $.alerModal({ "message": "申诉成功", type: "tip", win: true, time: '1000' });
      } else {
        $.alerModal({ "message": res.data.msg || '申诉失败,请重试~', type: "tip", win: 'warn', time: '1000' });

      }
    }).catch(() => {
      $.alerModal({ "message": res.data.msg || '申诉失败,请重试~', type: "tip", win: 'default', time: '1000' });

    });
  }

  function getAppealDetail(id, flg, casesEntryId, qcresultDetailId) {
    const param = {
      behospitalCode: global_id,
      casesEntryId: casesEntryId,
      hospitalId: global_hid,
      qcresultDetailId: qcresultDetailId,
      id: +id
    };
    post(api.getApprovedView, param).then((res) => {
      const info = res.data.data || {};
      const appealInfo = info.appealExamineRecordDTOList;
      $("#appealStatusTmpl").tmpl(appealInfo).appendTo("#delModal .modal-body");
      /*if (flg === '1') {
        $(".check-item").hide();
        $(".reject-item").show();
      } else if (flg === '2') {
        $(".check-item").show();
      }*/
    })
  }

  //申诉弹窗
  function showModal(flag, code, i, id, qcresultDetailId) {
    global_entryName = ''
    global_casesEntryId = '';
    $("#delModal .modal-body").html("");
    $("#delModal").show();
    //事件解绑
    $("#delModal .confirm").off("click");
    $("#addQcScore,#addQcMsg,#addQcInfo").off("input");
    $("#delModal .confirm").show();
    $('.modal-body').scrollTop(100);
    if (flag === '0') {   //申诉
      getCheckUser(); //获取审核人列表
      getQcCasesEntry()
      const flawsList = formatFlawKeys(global_flawData);
      const info = JSON.parse(JSON.stringify(flawsList[global_activeTab])) && JSON.parse(JSON.stringify(flawsList[global_activeTab][i]))
      let defectContent
      if (info.isDeleted == 'Y') {
        info.appealOperationType = 3
      } else {
        if (info.appealOperationType == 1) {
          if (info.exampleStatus == 2) {
            info.appealOperationType = 0
          } else {
            info.appealOperationType = 1
          }
        } else if (info.appealOperationType == 3) {
          info.appealOperationType = 0
        }
      }
      if (info.pageKeyList[0]) {
        defectContent = $("#anchor" + info.pageKeyList[0] + " p").html()
      }
      $("#delModal .title").text("申诉");
      $("#delModal .modal-box").css("margin-top", "-215px");
      $("#editTmpl").tmpl(info).appendTo("#delModal .modal-body");
      $("#flawDropTmpl").tmpl({ info: global_checkers }).appendTo("#delModal .modal-body ul");
      $("#qcInfo").off("input");
      //申诉说明输入验证
      const num = 500;
      $("#qcInfo").on("input", function () {
        const val = $(this).val().trim();
        $(this).attr("title", val)
        if (!val) {
          $(".edit-box .warning .red").text("申诉说明不能为空~");
          $(".edit-box .warning").show();
        } else if (val.length > num) {
          $(".edit-box .warning .red").text("申诉说明不能超过" + num + "个字~");
          $(".edit-box .warning").show();
        } else {
          $(".edit-box .warning").hide();
          return;
        }
      });

      $("#delModal .confirm").unbind("click").click(function () {
        // if ($(".edit-box .warning").is(":visible")) {
        //   return;
        // }
        const userId = $(".checker-drop-input").attr("code");
        const appealExec = $("#delModal #qcInfo").val().trim();   //申诉说明
        if (!userId) {
          $(".edit-box .warning .red").text("请选择审核人~");
          $(".edit-box .warning").show();
          return;
        }
        if (appealExec.length === 0) {
          $(".edit-box .warning .red").text("申诉说明不能为空~");
          $(".edit-box .warning").show();
          return;
        }
        if (appealExec.length > 500) {
          $(".edit-box .warning .red").text("申诉说明不能超过500个字~");
          $(".edit-box .warning").show();
          return;
        }
        const obj = {
          appealExplain: $("#delModal #qcInfo").val(),
          appealOperationType: info.appealOperationType ? info.appealOperationType : 0,
          appealType: 1,
          checkId: $(".checker-drop-input").attr("code") == "输血/血制品病程记录" ? '输血血制品病程记录' : $(".checker-drop-input").attr("code"),
          modeId: info.modelId,
          modeName: info.modelName,
          qcresultDetailId: info.id,
          workFlowNodeId: 1,
          casesScore: info.casesScore,
          casesEntryId: info.casesEntryId,
          isReject: info.isReject,
          qcresultDetaiValue: info.score,
          qcresultDetailMsg: info.msg,
          defectContent: defectContent,
          casesEntryMsg: info.standardMsg,
          value: info.score,
          remark: info.explainInfo,
        };
        appealItem(obj);
      });
    } else if (flag === '1') {   //查看
      $("#delModal .title").text("查看");
      $("#delModal .confirm").hide();
      $("#delModal .modal-box").css("margin-top", '-245px');
      //0申诉1驳回2审核
      //新增项模板
      getAppealDetail(code, i, id, qcresultDetailId);
    } else if (flag === '2') {   //新增
      getCheckUser(); //获取审核人列表
      getQcCasesEntry()
      $("#delModal .title").text("申诉新增");
      $("#delModal .modal-box").css("margin-top", "-281px");
      //新增项模板
      $("#addFlawTmpl").tmpl().appendTo("#delModal .modal-body");
      //缺陷项下拉模板
      $("#flawDropTmpl").tmpl({ info: global_flaws }).appendTo("#delModal .flaw-drop-box ul");
      //审核人模板
      $("#delModal .checker-drop-box ul").html("");
      $("#flawDropTmpl").tmpl({ info: global_checkers }).appendTo("#delModal .checker-drop-box ul");
      //事件绑定
      flawDropEvent(".add-box .flaw-drop-input", getQcCasesEntry, selectFlaw);
      //分数输入验证
      $("#addQcScore").on("input", function () {
        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();
          return;
        }
      });
      //提示信息输入验证
      $("#addQcMsg").on("input", function () {
        const val = $(this).val().trim();
        $(this).attr("title", val)
        if (val.trim()) {
          $(".add-box .warning").hide();
        } else {
          $(".add-box .warning .red").text("提示信息不能为空~");
          $(".add-box .warning").show();
          return;
        }
      });
      //备注输入验证
      $("#addQcInfo").on("input", function () {
        const val = $(this).val().trim();
        $(this).attr("title", val)
        if (val.length > 125) {
          $(".add-box .warning .red").text("备注不能超过125个字~");
          $(".add-box .warning").show();
        } else {
          $(".add-box .warning").hide();
          return;
        }
      });
      //申诉说明输入验证
      $("#addQcEx").on("input", function () {
        const val = $(this).val().trim();
        if (val.trim().length === 0) {
          $(".add-box .warning .red").text("申诉说明不能为空~");
          $(".add-box .warning").show();
        } else if (val.length > 500) {
          $(".add-box .warning .red").text("申诉说明不能超过500个字~");
          $(".add-box .warning").show();
        } else {
          $(".add-box .warning").hide();
          return;
        }
      });
      //新增申诉提交事件
      $("#delModal .confirm").unbind("click").click(function () {
        const type = $("input[name=operType]:checked").val();
        const msg = $("#delModal #addQcMsg").val();
        const score = Number($("#delModal #addQcScore").val());
        const explainInfo = $("#delModal #addQcInfo").val();
        const appealExec = $("#delModal #addQcEx").val().trim();   //申诉说明
        const userId = $(".checker-drop-input").attr("code");
        // if ($(".edit-box .warning").is(":visible")) {
        //   return;
        // }
        if (!userId) {
          $(".add-box .warning .red").text("请选择审核人~");
          $(".add-box .warning").show();
          $('.modal-body').scrollTop(100);
          return;
        }
        //必填验证
        if (type === '1') {     //新增已有时
          if (!$(".flaw-drop-input").attr("code")) {
            $(".add-box .warning .red").text("请选择质控条目~");
            $(".add-box .warning").show();
            $('.modal-body').scrollTop(100)
            return;
          }
          if ((!score) && $("#delModal #addQcScore").val() != '0') {
            $(".add-box .warning .red").text("分值不能为空~");
            $(".add-box .warning").show();
            $('.modal-body').scrollTop(100)
            return;
          }
        }
        if (appealExec.length === 0) {
          $(".add-box .warning .red").text("申诉说明不能为空~");
          $(".add-box .warning").show();
          $('.modal-body').scrollTop(100)
          return;
        }
        if (appealExec.length > 500) {
          $(".add-box .warning .red").text("申诉说明不能超过500个字~");
          $(".add-box .warning").show();
          return;
        }
        const obj = Object.assign({}, global_selectedFlaw, { msg, score, appealExec, type, explainInfo, userId });
        addScore(obj);
      });
    }
  }
  $(document).on("click", "input[name=operType]", (e) => {
    $(".add-box .warning").hide();
  });
  //缺陷列表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 getCheckUser() {
    const param = {};
    post(api.getReviewer, param).then(function (res) {
      if (res.data.code === '0') {
        const data = res.data.data;
        global_checkers = data;
        $("#delModal .checker-drop-box ul").html("");
        $("#flawDropTmpl").tmpl({ info: data }).appendTo("#delModal .checker-drop-box ul");
        userDropEvent(".checker-drop-input", selectChecker);
      }
    });
  }
  //获取缺陷条目下拉列表
  function getQcCasesEntry() {
    const name = ($(".flaw-drop-input").val() || "").trim();
    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;
        //if(name){
        $("#delModal .flaw-drop-box ul").html("");
        $("#flawDropTmpl").tmpl({ info: data }).appendTo("#delModal .flaw-drop-box ul");
        //}
        /*$("#delModal .flaw-drop-box ul").html("");
        $("#flawDropTmpl").tmpl({info:data}).appendTo("#delModal .flaw-drop-box ul");
        /*}else{
        glal_flaws=data;
        showModal('2',data);
        }*/
      }
    });
  }
  //审核人下拉事件
  function userDropEvent(domSelector, selectEvent) {
    // $("body").on("click", domSelector, function (e) {
    //   e.stopPropagation()
    //   $(domSelector).parents(".drop-box").toggleClass("show");
    // });
    $("body").on("click", ".checker-drop-box li", function () {
      $(".add-box .warning").hide();
      const n = $(this).attr("idx");
      selectEvent(domSelector, n);
      $(domSelector).parents(".drop-box").find(".warning").hide();
      $(domSelector).parents(".drop-box").removeClass("show");
    });
  }
  $(document).on("click", ".checker-drop-input", (e) => {
    e.stopPropagation()
    const showList = $("#delModal .checker-drop-box ul").css("display")
    if (showList == "none" || !showList) {
      $("#delModal .checker-drop-box ul").css("display", "block")
    } else {
      $("#delModal .checker-drop-box ul").css("display", "none")
    }

  });
  $(document).on("click", ".infoItem", (e) => {
    e.stopPropagation()
    $("#delModal .checker-drop-box ul").css("display", "none")
  });
  $(document).on("click", function () {
    $("#delModal .checker-drop-box ul").css("display", "none")

  })
  //增加条目弹窗元素事件
  function flawDropEvent(domSelector, getData, selectEvent) {
    $("body").off("click,blur,input");
    $("body").on("click", domSelector, function () {
      $(domSelector).parents(".drop-box").addClass("show");
    });
    $("body").on("blur", domSelector, function () {
      setTimeout(function () {
        $(domSelector).parents(".drop-box").removeClass("show");
      }, 300)
    });
    $("body").on("input", domSelector, function () {
      $(this).attr({ "code": "", "title": $(this).val().trim() });
      getData($(this).val().trim());
    });
    $("body").on("click", ".flaw-drop-box li", function () {
      $(".add-box .warning").hide();
      const n = $(this).attr("idx");
      selectEvent(domSelector, n);
      $(domSelector).parents(".drop-box").find(".warning").hide();
      $(domSelector).parents(".drop-box").removeClass("show");
    });
    //单选事件
    $(".add-box input[type=radio]").on("click", function () {
      if ($(this).val() === '1') {
        $(".exist-item").show();
      } else {
        $(".exist-item").hide();
      }
    });
  }

  //条目下拉选中
  function selectFlaw(domSelector, n) {
    const flaw = global_flaws[n] || {};
    const { score, msg, entryName, casesEntryId } = flaw;
    global_selectedFlaw = flaw;
    global_entryName = entryName
    global_casesEntryId = casesEntryId
    $(domSelector).val(entryName).attr({ "code": casesEntryId, "title": entryName });
    $("#addQcMsg").val(msg).attr("title", msg);
    $("#addQcScore").val(score);
  }
  $(document).on("blur", ".flaw-drop-input", (e) => {
    $('.flaw-drop-input').val(global_entryName).attr({ "code": global_casesEntryId, "title": global_entryName });
  });
  $(".flaw-drop-input").blur(function () {
    console.log(111);
    $("input").css("background-color", "#D6D6FF");
  })
  //审核人下拉选中
  function selectChecker(domSelector, n) {
    const flaw = global_checkers[n];
    const { id, userName } = flaw;
    $(domSelector).text(userName).attr({ "code": id, "title": userName });
  }

  //更新缺陷列表
  function updateFlaws() {
    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-hts">');


    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;
    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();
      }
    });
  }
  function checkYwQc() {
    const param = {
      behospitalCode: getUrlArgObject("id"),
      hospitalId: getUrlArgObject("hid"),
    };
    post(ywCheckApi.recordCheck, param).then((res) => {
      if (res.data.code === '0') {
        global_check = 1
        $(".ywCheck").text("重新核查")
        $.alerModal({ "message": "核查成功", type: "tip", time: '1000', win: true });
      } else {
        $.alerModal({ "message": res.data.msg || "核查失败", type: "tip", time: '1000', isFather: false });
      }
    });
  }

});

