import {DonMessage} from '@/axios/message.js'
const $message = new DonMessage()
import {
  queryCMByPatientBaseId,
  queryPatientDetail
} from "@/request/cm.js";
import { shapeArr,constipationHandleArr,diarrheaDict,intakeLevel,timeOptions,mouthUlcerArr } from 'aegle-sp-components/src/data/validate.js'
import { cloneDeep } from 'lodash';
import { getSelectLabel } from 'aegle-sp-components/src/utils/index.js'

export default {
  data() {
    return {
      shapeArr,
      constipationHandleArr,
      diarrheaDict,
      intakeLevel,
      mouthUlcerArr,
    }
  },
	computed: {
    painText() {
      let text = []
      for(let k in this.noComform){
        if(this.noComform[k]) text.push(k)
      }
      return text
    },
		//常规提醒项目最大数量
    maxLength(){
      let num = 0;
      this.diseaseArrCopy.forEach(item => {
        if(!item.first) num +=1;
      })
      return num
    },
		cancerSecond() {
      if(this.disease == '其他') {
        this.cancerObj.diseases = '其他'
        return []
      }
      const arr = this.cancerArr.filter(item => {
        return item.id == this.disease
      })
      this.cancerObj.diseases = arr.length ? arr[0].desc : '';
      return arr.length ? arr[0].cdict : []
    }
	},
  methods: {
    //患者信息，用于选择为死亡时，更新vuex里面的状态，更新其他地方需要根据患者状态改变展示的地方
    async getPatientInfo(id,callback){
      const res = await queryPatientDetail(id);
      if(res.code == 0) {
        const patientInfo = {
          seeDoctorId: res?.data?.patientBaseExtend?.seeDoctorId || '',
          allergiesExclusion: res.data.patientBaseExtend.allergiesExclusion,
          ...res.data.patientBase,
          patientAllergenList: res.data.patientAllergenList || [],
          patientContagionList: res.data.patientContagionList || [],
          starLevel: res.data.patientBaseExtend.starLevel || 0,
          caseManageId: res.data.patientBaseExtend.caseManagerId,
          patientStatus: res?.data?.patientBaseExtend?.patientStatus
        };
        callback ? callback(patientInfo) : null
      } else {
        this.$message.error(res.msg);
      }
    },
    //患者基本信息
    async queryPatientInfo(id,type) {
      const { data, code, msg } = await queryCMByPatientBaseId(id)
      // const {data,code,msg} = await queryPatientDetail(id)
      if(code == 0){
        this.baseInfo = {
          emrTumour: data.emrTumour,//分期
          outpatientDiag: data.outpatientDiag || '', //诊断
          phone: data.patientPhone,
          currentStatus: data.currentStatus
        }
        if(type == 1) {
          this.protocols = data?.protocols || '';
          this.patientPhone = data?.patientPhone || '';
        }
      } else {
        $message.error(msg)
      }
    },
    // isExistence(type,patientId,oldType){
    //   const obj = {
    //     '病案首页': 'A009',
    //     '出院记录': 'A0010',
    //     '随访记录': 'A005'
    //   }
    //   let tabsName =obj[type]
    //   let cachedData = cloneDeep(this.cachedData)
    //   let tagNavList = cachedData[patientId].subNav.tagLists
    //   let key;
    //   for (let prop of tagNavList) {
    //     if (prop.value == tabsName) key = true;
    //   }
    //   if(!key) {
    //     // 添加随访管理模块
    //     let obj = {label: type,value: tabsName,closable: true,oldType: oldType || ''};
    //     tagNavList = [...tagNavList, obj];
    //     // 缓存当前的这个页签
    //   } else {
    //     tagNavList = tagNavList.map(item => {
    //       if(item.value == tabsName){
    //         item.oldType = oldType || ''
    //       }
    //       return item
    //     })
    //     // cachedData[patientId].subNav.curTab = tabsName;
    //   }
    //   cachedData[patientId].subNav = {
    //     tagLists: tagNavList,
    //     curTab: tabsName,
    //   };
    //   this.saveSecTabs(cachedData);
    // },
    //住院文件查看
    // viewOtherFile(e) {
    //   const cachedData = cloneDeep(this.cachedData)
    //   let tabsName = e == '病案首页' ? 'A009' : 'A0010'
    //   let tagNavList = cachedData[this.id].subNav.tagLists
    //   let key;
    //   for (let prop of tagNavList) {
    //     if (prop.value == "A005") key = true;
    //   }
    //   if(!key) {
    //     // 添加随访管理模块
    //     let obj = {label: e,value: tabsName,closable: true,};
    //     tagNavList = [...tagNavList, obj];
    //     // 缓存当前的这个页签
    //     cachedData[this.id].subNav = {
    //       tagLists: tagNavList,
    //       curTab: tabsName,
    //     };
    //   } else {
    //     cachedData[this.id].subNav.curTab = tabsName;
    //   }
    //   this.saveSecTabs(cachedData)
    // },
    //选项切换清空数据
    clearItem(type,value) {
      if(!value || value == 2){
        const arr = ['decreasedAppetite','constipation','discomfortOther','mouthUlcer','diarrhea','rash']
        if(arr.includes(type)){
          for(let k in this[type + 'DTO']){
            this[type + 'DTO'][k] = ''
          }
        }
        if((type == 'pain') || type == 'discomfort'){
          this.painDTO = [{
            painLocation: '', //疼痛位置
            painNature: '', //疼痛性质
            score: 0,       //评分
            sleep: '',      //是否影响睡眠 0：否  1：是
            anodyne: '',        //止痛药 0：否  1：是
            drugDose:''    //药物剂量
          }]
          this.painPanel = "0"
        }
        if(type == 'discomfort'){
          for(let k in this.noComform) {
            this.noComform[k] = ''
          }
          arr.forEach(item => {
            for(let k in this[item + 'DTO']){
              this[item + 'DTO'][k] = ''
            }
          })
        }
        if(type == 'reminder'){
          this.diseases = ''
          this.diseaseTimes = ''
          this.diseaseArrCopy = []
        }
      }
    },
    setCancer(e) {
      this.diseases = e?.diseases;
      this.diseaseTimes = e?.diseaseTimes;
      this.diseaseArrCopy = cloneDeep(e?.arr)
    },
    //查看时获得下拉选中的label
    getSelectLabel(v,arr,key,name) {
        return getSelectLabel(v,arr,key,name)
    },
		//添加疼痛选项
    addPainItem() {
      if(this.painDTO.length >4) return;
      this.painDTO.push({
        painLocation: '', //疼痛位置
        painNature: '', //疼痛性质
        score: 0,       //评分
        sleep: '',      //是否影响睡眠 0：否  1：是
        anodyne: '',        //止痛药 0：否  1：是
        drugDose:''    //药物剂量
      })
      this.painPanel = String(this.painDTO.length - 1)
    },
    tabsRemove(e) {
      this.painDTO.splice(e,1)
      this.painPanel = String(this.painDTO.length - 1)
    },
		//疼痛数据变化
		changePainData(index,e){
      this.painDTO[index] = {
        ...e
      }
    },
    //取消确认
    cancelFollow(callback,type) {
      const h = this.$createElement;
      this.$msgbox({
        title: type ? "离开确认" : "取消确认",
        message: h(
          "div",
          {
            style: {
              lineHeight: "26px",
              fontFamily: "font-family: PingFangSC, PingFangSC-Regular;",
            },
          },
          [
            h("span", { style: { display: 'inline-block',width: '100%',fontSize: "14px",color: "rgba(0,0,0,.8)" } }, `是否确认${type ? '离开' : '取消'}?`),
            h(
              "span",
              { style: { color: "#E92626", fontSize: "12px" } },
              [h("i", {style: {color: "#E92626", fontSize: "14px",marginRight: '5px'},class: 'el-icon-warning-outline'}),`现在${type ? '离开' : '取消'}将不保存您书写的任何信息`]
            ),
          ]
        ),
        customClass: 'self-com-dialog died-dialog',
        showCancelButton: true,
        confirmButtonText: "是",
        cancelButtonText: "否",
        closeOnClickModal: false,
        closeOnPressEscape: false,
        showClose: false,
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            callback()
          }
          done();
        },
      }).then((res) => {
        console.log(res);
      });
    },
    //死亡确认
    //死亡确认
    diedSure(callback) {
      const h = this.$createElement;
      this.$msgbox({
        title: "死亡确认",
        message: h(
          "div",
          {
            style: {
              lineHeight: "26px",
              fontFamily: "font-family: PingFangSC, PingFangSC-Regular;",
            },
          },
          [
            h("span", { style: { display: 'inline-block',width: '100%',fontSize: "14px",color: "rgba(0,0,0,.8)" } }, "是否确认该患者已死亡？"),
            h(
              "span",
              { style: { color: "#E92626", fontSize: "12px" } },
              [h("i", {style: {color: "#E92626", fontSize: "14px",marginRight: '5px'},class: 'el-icon-warning-outline'}),"确认后已创建的随访不可编辑，也不可再创建新随访"]
            ),
          ]
        ),
        customClass: 'self-com-dialog died-dialog',
        showCancelButton: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        closeOnPressEscape: false,
        showClose: false,
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            callback()
            // this.sendTempFollow(2,true)
          }
          done();
        },
      }).then((res) => {
        console.log(res);
      });
    },
    getFloat(e,type){
      if(type == 'bodyWeightChangeNum'){
        let tmpVal = e.replace(/[^\d\.]/g, '').replace(/^0{2,}/g,'0');
        let reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/;
        if(!reg.test(tmpVal)){
          tmpVal = tmpVal + "";
          tmpVal = tmpVal.substring(0, tmpVal.indexOf(".") + 3);
          let n = (tmpVal.split('.')).length - 1;
          if(n > 1) {
            tmpVal = tmpVal.substring(0, tmpVal.indexOf("."));
          }
        }
        this.decreasedAppetiteDTO.bodyWeightChangeNum = tmpVal
      }
    },
    setSelectColor(currentStatus) {
      let name = ''
      if (currentStatus == '新辅助治疗') {
        name = 'radiotherapy1'
      } else if (currentStatus == '辅助治疗') {
        name = 'chemotherapy1'
      } else if (currentStatus === '辅助治疗后观察随访') {
        name = 'chemotherapy'
      } else if (currentStatus === '围手术期') {
        name = 'postoperative'
      } else if (currentStatus === '新辅助治疗后观察随访') {
        name = 'radiotherapy'
      } else if (
        currentStatus === '一线治疗' ||
        currentStatus === '二线治疗' ||
        currentStatus === '三线治疗'
      ) {
        name = 'preoperative'
      } else if (currentStatus === '最佳支持治疗') {
        name = 'radioGreen'
      } else if(currentStatus === '暂无'){
        name = 'therapeutic'
      }
      return name
    },
  }
}