// case/pages/createCase/createCase.js
import {addCase,caseDetail,editCase,getOssSign,ocrImg,getMobileModel} from "../../../api/api"
const dayjs = require("../../../utils/dayjs");
import {throttle} from "../../../utils/util"
import { FileUtil } from '../../../utils/fileutil'
import {diagnoseOption,patientSickOption,ganneiOption,ganwaiOption,moshiOption,hospitalOption,kangningOption,il6Unit,doseUnit,tnfUnit} from "../../utils/data"
import Toast from '@vant/weapp/toast/toast';

const app=getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        value:[],
        ocrChecked:false,
        tagList:[],
        ocrType:'',
        showOcr:false,
        kangningOption:kangningOption,
        diagnoseOption:diagnoseOption,
        patientSickOption:patientSickOption,
        ganneiOption:ganneiOption,
        ganwaiOption:ganwaiOption,
        il6Unit:il6Unit,
        doseUnit:doseUnit,
        tnfUnit:tnfUnit,
        moshiOption:moshiOption,
        hospitalOption:hospitalOption,
        editorHeight:'calc(100vh - 600rpx)',
        editorHeight2:'calc(100vh - 1100rpx)!important',
        paintFrom:'basic',
        paintSrc:'',
        showPaint:false,
        active:0,
        wordLength:0,
        showSaveBtn:true,
        delIndex:'',
        navName:'创建病例',
        showDraft:false,
        showUseDraft:false,
        isUseDraft:false,
        cursorText:{
            before:'',
            after:''
        },
        medicalRecordId:'',
        dealIndex:0,
        showTime:false,
        showType:false,
        img_host:app.hostConfig().imghost,
        showTip:false,
        showDel:false,
        showAttention:false,
        fileList_basic:[],
        fileList_bio:[],
        fileList_coa:[],
        fileList_inf:[],
        dpmas_list:[{fileList:[],treatTime:'',temp_list:[]}],
        disable_ziliao:false,
        disable_record:false,
        disable_check:false,
        disable_back:false,
        columns:[
            { text: 'DPMAS及联合模式', value: 1 },
            { text: 'CA280及联合模式', value: 2 }
        ],
        typeName:'',
        case:{
            name:'',
            uid:'',
            sex:null,
            age:'',
            treatmentNum:'',
            admissionTime:'',
            caseType:[],
            mainDiagnose:{
                select:[],
                otherValue:'',
                mainDiagnoseImg:''
            },
            diseaseCause:{
                select:[],
                otherValue:''
            },
            seductionReason:{      //基本信息结束
               inside:{
                 select:[],
                 otherValue:''
               },
               outside:{
                select:[],
                otherValue:''
              },
            },
            abstractStr:'',//临床资料结束
            dpmas:[{
                'treatTime':'',
                  'content':{             
                    "mode":{ // 模式
                        "select":"",
                        "otherValue":"",
                   },
                   "plasma":{ // 血浆
                        "handle":"",
                        "replace":""
                    },
                    "dose":{ // 抗凝剂量
                        "select":[],
                        "heparin":{ // 肝素
                                "firstDose":"",//首剂
                                "firstDoseUnit":'1',
                                "append":"",//追加
                                "appendUnit":'1',
                        },
                        "lowHeparin":{ // 低分子肝素
                                "value":""
                        },
                        "citricAcid":{ // 枸橼酸
                                "bloodFlowRate":"",//血液流速
                                "citricAcidFlowRate":"",//枸橼酸钠流速
                                "calciumAgent":{ // 钙剂
                                        "select":"",
                                          "value":"",
                                }
                        },
                        "nafamostat":{ // 甲磺酸萘莫司他
                                "value":""
                        },
                        "other":{ // 其他
                                "name":"",
                                "dose":""
                        }
                     }
                    
                },
                dpmasImg:''
            }],
            headTime:'',
            afterTime:'',
            lastTime:'',
            headTb:'',
            afterTb:'',
            lastTb:'',
            headDb:'',
            afterDb:'',
            il6Unit:'2',
            tnfUnit:'1',
            lastDb:'',
            headIb:'',
            afterIb:'',
            lastIb:'',
            headAlt:'',
            afterAlt:'',
            lastAlt:'',
            headAst:'',
            afterAst:'',
            lastAst:'',
            headAlb:'',
            afterAlb:'',
            lastAlb:'',
            headPta:'',
            afterPta:'',
            lastPta:'',
            headInr:'',
            afterInr:'',
            lastInr:'',
            headCrp:'',
            afterCrp:'',
            lastCrp:'',
            headIl6:'',
            afterIl6:'',
            lastIl6:'',
            headTnf:'',
            afterTnf:'',
            lastTnf:'',
            checkImg:'',
            bioImg:'',
            coaImg:'',
            infImg:'',
            dischargeTime:'',
            day:'',
            dischargeSituation:'',
            dischargeStatus:''
        },
        time_type:'date',
        time_str:"hospitalTime",
        time_title:'选择入院时间',
        minHeight:{minHeight: 100},
        currentDate: new Date().getTime(),
        maxDate:new Date().getTime(),//new Date().getTime(),
        minDate:new Date('2024-10-01').getTime(),
        editorCtx:null,
        editorCtxDischarge:null,
        formatter(type, value) {
          if (type === 'year') {
            return `${value}年`;
          }
          if (type === 'month') {
            return `${value}月`;
          };
          if(type === 'day'){
            return `${value}日`;
          }
          if(type === 'hour'){
            return `${value}时`;
          }
          if(type === 'minute'){
            return `${value}分`;
          }
          return value;
        },
      
    },
    onChangeOcrCheck(event){
        let {tagList}=this.data;
        this.setData({
            ocrChecked:event.detail,
          });
          let {ocrChecked}=this.data;
      if(ocrChecked){
         tagList.forEach((item,index)=>{
            let key='tagList['+index+'].checked';
            this.setData({
                [key]:true
                });
         })
      }else{
        tagList.forEach((item,index)=>{
            let key='tagList['+index+'].checked';
            this.setData({
                [key]:false
                });
         })
      }
    },
    afterReadOcr(event){
        const { file,name} = event.detail;
    //     this.uploadImg(file.url,'').then(res=>{
    //         console.log(res)
    //                     let link='https://dev-wx.igandan.com/croper/croper.htm?imgUrl='+res+'&name='+name;
    //         wx.navigateTo({
    //           url: '/case/pages/webSign/webSign?src='+encodeURIComponent(link),
    //     })
    // })

        wx.getFileSystemManager().readFile({
            filePath:file.url,
           encoding:'base64',
          success:res=>{
            // wx.showLoading({
            //     title: '正在识别中...',
            //     mask: true
            //   })
            this.ocrImgText(res.data,name)
          }
   })
    },
    toggleWord(event){
        let index=Number(event.target.dataset.index);
        let {tagList}=this.data;
     
        let checked=!tagList[index].checked;
        let key='tagList['+index+'].checked';
        console.log(checked);
        this.setData({
        [key]:checked
        });
    },
    blurDischargeSituation(e){
        const { value, cursor } = e.detail;
        const textBeforeCursor = value.substring(0, cursor); // 光标前的文本
        const textAfterCursor = value.substring(cursor); // 光标后的文本
        this.setData({
            cursorText:{
                before:textBeforeCursor,
                after:textAfterCursor
            }
        })
        console.log('Text before cursor:', textBeforeCursor);
        console.log('Text after cursor:', textAfterCursor);
    },
    confirmOcr(){
        let {tagList,ocrType,cursorText}=this.data;
        let txt='';
        tagList.forEach(item=>{
            if(item.checked){
                if(txt){
                    txt+=item.words;
                }else{
                    txt+=item.words
                }
            }
            
        })
         if(ocrType=="dischargeSituation"){
                // let {cursorText}=this.data;
                // this.setData({
                //     ['case.'+ocrType]:cursorText.before+txt+cursorText.after,
                // })
                this.data.editorCtxDischarge.insertText({
                    text:txt,
                   
                });
            }else{
                this.data.editorCtx.insertText({
                    text:txt,
                   
                });
                       
            }
            this.setData({
                showOcr:false
            })     
    },
    ocrImgText(mageBase64,name){
        this.setData({
            ocrChecked:false
        })
        wx.showLoading({
                title: '正在识别中...',
                mask: true
              })
        ocrImg({
            imageBase64:mageBase64
        }).then(res=>{
            wx.hideLoading();
            //let txt=''
            let list=res.wordsResult;
            
            if(list.length>0){ 
            
                let arr=list.map(item=>{
                  
                   return {
                    checked:false,
                    words:item.words
                   }
                  
                })
                this.setData({
                    tagList:arr,
                    ocrType:name,
                    showOcr:true
                })
               
            };
            
           
            
        })
    },
    closeOcr(){
      this.setData({
          showOcr:false
      })
    },
    onEditorReady() {
        const that = this
        wx.createSelectorQuery().select('#editor').context(function (res) {
            that.setData({
                editorCtx:res.context
            })
            let html=''

    //       let html =
    // "<p>【主诉】：</p><br/><p>【现病史】：</p><br/><p>【既往史】：</p><br/><br/>";
       let str=that.data.case.abstractStr;

       if(str){
           html=str
       };
          that.data.editorCtx.setContents({
             html:html
          })
          that.data.editorCtx.blur()
         
        }).exec()
      },
      onEditorReadyDischarge() {
        const that = this
        wx.createSelectorQuery().select('#editor2').context(function (res) {
            that.setData({
                editorCtxDischarge:res.context
            })
       
       let str=that.data.case.dischargeSituation;
        let html='';
       if(str){
           html=str;
           that.data.editorCtxDischarge.setContents({
            html:html
         });
         that.data.editorCtxDischarge.blur()
       };
         
        }).exec()
      },
    onChangeCheck(event){
        console.log(event);
        let type=event.target.dataset.type;
        let clear=event.target.dataset.clear;
        let arr=event.detail;
        this.setData({
           [type]:event.detail
       });
       if(type.indexOf('dose')>-1){
          if(arr.indexOf('1')==-1){
            this.setData({
                [clear+'.heparin.firstDose']:'',
                [clear+'.heparin.append']:''
            })
          };
          if(arr.indexOf('2')==-1){
            this.setData({
                [clear+'.lowHeparin.value']:'',
            })
          }
          if(arr.indexOf('3')==-1){
            this.setData({
                [clear+'.citricAcid.bloodFlowRate']:'',
                [clear+'.citricAcid.citricAcidFlowRate']:'',
                [clear+'.citricAcid.calciumAgent.value']:'',
                [clear+'.citricAcid.calciumAgent.select']:'',
                
            })
          }
          if(arr.indexOf('4')==-1){
            this.setData({
                [clear+'.nafamostat.value']:'',
            })
          }
          if(arr.indexOf('-1')==-1){
            this.setData({
                [clear+'.other.name']:'',
                [clear+'.other.dose']:'',
            })
          }
       }else{
        if(clear && arr.indexOf('-1')==-1){
            this.setData({
                [clear]:''
            })
        }
       
       }
    },
    deepClone(source) {
        if (typeof source !== 'object' || source == null) {
          return source;
        }
        const target = Array.isArray(source) ? [] : {};
        for (const key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            if (typeof source[key] === 'object' && source[key] !== null) {
              target[key] = this.deepClone(source[key]);
            } else {
              target[key] = source[key];
            }
          }
        }
        return target;
      },
    formatString(obj){
            let newObj=this.deepClone(obj);
             for (const key in newObj) {
               if(key=='mainDiagnose' || key=='diseaseCause'){
                // for (const j in newObj[key]){
                //     let item=newObj[key][j];
                //     if(typeof item=='object'){
                //         newObj[key][j]=JSON.stringify(item)
                //     }
                    
                // }
                newObj[key]=JSON.stringify(newObj[key])
              }

              if(key=="seductionReason"){
                //     for (const j in newObj.seductionReason.inside){
                //         let item=newObj.seductionReason.inside[j];
                //         if(typeof item=='object'){
                //             newObj.seductionReason.inside[j]=JSON.stringify(item)
                //         }
                        
                //     }
                //     newObj.seductionReason.inside=JSON.stringify( newObj.seductionReason.inside);
                //     for (const i in newObj.seductionReason.outside){
                //         let item=newObj.seductionReason.outside[i];
                //         if(typeof item=='object'){
                //             newObj.seductionReason.outside[i]=JSON.stringify(item)
                //         }
                        
                //     }
                //    newObj.seductionReason.outside=JSON.stringify(newObj.seductionReason.outside);
                newObj.seductionReason=JSON.stringify(newObj.seductionReason);
                
              }    
              if(key=="dpmas"){
                for (let index = 0; index < newObj.dpmas.length; index++) {
                    const element = (newObj.dpmas)[index];
                //     console.log(element.content.mode)
              
                // element.content.mode=JSON.stringify(element.content.mode);
                // element.content.plasma=JSON.stringify(element.content.plasma)
              
                // element.content.dose.select=JSON.stringify(element.content.dose.select);
                // element.content.dose.heparin=JSON.stringify(element.content.dose.heparin);
                // element.content.dose.lowHeparin=JSON.stringify(element.content.dose.lowHeparin);
                // element.content.dose.citricAcid.calciumAgent=JSON.stringify(element.content.dose.citricAcid.calciumAgent);
                // element.content.dose.citricAcid=JSON.stringify( element.content.dose.citricAcid)
                // element.content.dose.nafamostat=JSON.stringify( element.content.dose.nafamostat)
                // element.content.dose.other=JSON.stringify( element.content.dose.other)
                // element.content.dose=JSON.stringify( element.content.dose)
                element.content=JSON.stringify(element.content)
               

            }
        }
     }
      return newObj
    },
    formatJson(obj){
        for (const key in obj) {
            if(key=="mainDiagnose" || key=="diseaseCause" ||key=="caseType"){
                obj[key]=JSON.parse(obj[key]);
                //obj[key].select=JSON.parse(obj[key].select)
            };
           
            if(key=="seductionReason"){
                obj.seductionReason=JSON.parse(obj.seductionReason);
                // obj.seductionReason.inside=JSON.parse(obj.seductionReason.inside);
                // obj.seductionReason.inside.slect=JSON.parse(obj.seductionReason.inside.select);
                // obj.seductionReason.outside=JSON.parse(obj.seductionReason.outside);
                // obj.seductionReason.outside.slect=JSON.parse(obj.seductionReason.outside.select);
            };
            if(key=="dpmas"){
                for (let index = 0; index < obj.dpmas.length; index++) {
                    const element = obj.dpmas[index];
                    element.content=JSON.parse(element.content);
                    // element.content.mode=JSON.parse(element.content.mode);
                    // element.content.mode.select=JSON.parse(element.content.mode.select);
                    // element.content.plasma=JSON.parse(element.content.plasma);
                    // element.content.dose=JSON.parse(element.content.dose);
                    // element.content.dose.select=JSON.parse(element.content.dose.select);
                    // element.content.dose.heparin=JSON.parse(element.content.dose.heparin);
                    // element.content.dose.lowHeparin=JSON.parse(element.content.dose.lowHeparin);
                    // element.content.dose.citricAcid=JSON.parse(element.content.dose.citricAcid);
                    // element.content.dose.citricAcid.calciumAgent=JSON.parse(element.content.dose.citricAcid.calciumAgent);
                    // element.content.dose.nafamostat=JSON.parse(element.content.dose.citrnafamostaticAcid);
                    // element.content.dose.other=JSON.parse(element.content.dose.other);
                    
                    
                }
            }
           
                
         
        }
        return obj
    },
    onChangeOther(event){
        let {detail,currentTarget}=event;
        let type=currentTarget.dataset.type
            this.setData({
                [type]:detail.value
            })
    },
    toggleCheck(event){
       console.log(event);
    },
    save:throttle(function(){
      this.data.medicalRecordId?this.handleEditCase():this.handleAddCase();
    }),
    saveBasic(){
      
      if(this.validateBasic(true)){
          this.setData({
              active:1
          })      
      } 
      !this.data.medicalRecordId && this.saveDraft();
    },
    saveAbstract(){
        if(this.validateZiliao(true)){
            this.setData({
                active:2
            })
        } 
        !this.data.medicalRecordId && this.saveDraft();
      },
      saveRecord(){
        if(this.validateRecord(true)){
            this.setData({
                active:3
            })
        } 
        !this.data.medicalRecordId && this.saveDraft();
      },
      saveCheck(){
        if(this.validateCheck(true)){
            this.setData({
                active:4
            })
        } 
        !this.data.medicalRecordId && this.saveDraft();
      },
    goBack:throttle(function(){
        let {medicalRecordId}=this.data;
        if(!medicalRecordId && this.isHasValue()){
            this.setData({
                showDraft:true
            })
        }else{
            wx.navigateBack()
        }
      
    }),
    hasRecordValue(){
            let {dpmas}=this.data.case;
            for (let i = 0; i < dpmas.length; i++) {
                let item=dpmas[i].content;
                if(item){
                    if(item.mode.select){
                        return true
                    };
                    if(item.mode.otherValue){
                      return true
                    }
                    if(item.plasma.handle){
                      return true
                   }
                   if(item.plasma.replace){
                     return true
                   }
                   if(item.dose.select.length>0){
                     return true
                   }
                   if(item.dose.heparin.firstDose || item.dose.heparin.append){
                     return true
                   }
                   if(item.dose.lowHeparin.value){
                     return true
                   }
                   let qys=item.dose.citricAcid;
                   if(qys.bloodFlowRate || qys.citricAcidFlowRate || qys.calciumAgent.select || qys.calciumAgent.value){
                     return true
                   }
                   if(item.dose.nafamostat.value){
                       return true
                   };
                   if(item.dose.other.name || item.dose.other.dose){
                       return true
                   }
                }
               
                
            }
         return false
    },
    isHasValue(){
       let {name,uid,sex,age,admissionTime,caseType,mainDiagnose,diseaseCause,seductionReason,abstractStr,headTime,afterTime,headTb,afterTb,headAlt,afterAlt,headAlb,afterAlb,headAst,afterAst,headInr,afterInr,headDb,afterDb,headIb,afterIb,headPta,afterPta,headIl6,afterIl6,headTnf,afterTnf,dpmas}=this.data.case;
       let {fileList_basic,fileList_bio,fileList_coa,fileList_inf,dpmas_list,dischargeTime,day,dischargeStatus,dischargeSituation}=this.data;
       let hasTime=dpmas_list.some(item=>{ return item.fileList.length>0});      
    
       let hasImg=dpmas_list.some(item=>{ return item.treatTime!=''});
       let hasRec=false;
       if(!hasTime && !hasImg){
        hasRec= this.hasRecordValue();
       }

       if(name || uid || sex || age || admissionTime || caseType.length>0 || mainDiagnose.select.length>0 ||  mainDiagnose.otherValue || diseaseCause.select.length>0 || diseaseCause.otherValue || seductionReason.inside.select.length>0 || seductionReason.inside.otherValue || seductionReason.outside.select.length>0 || seductionReason.outside.otherValue  || abstractStr || headTime || afterTime || headTb || afterTb || headAlt || afterAlt || headAlb || afterAlb || headAst || afterAst || headInr || afterInr || headDb || afterDb || headIb || afterIb || headPta || afterPta || headIl6 || afterIl6 || headTnf || afterTnf || fileList_basic.length>0  || fileList_bio.length>0 || fileList_coa.length>0 || fileList_inf.length>0 || hasTime || hasImg || dischargeTime || day || dischargeStatus || dischargeSituation || hasRec){
           return true
       }else{
           return false
       }
    },
    handleAddCase(){
         let {fileList_basic,fileList_bio,dpmas_list,fileList_coa,fileList_inf}=this.data;
         let baseImg='';
         let bioImg='';
         let coaImg='';
         let infImg='';
        if(this.validateBasic(true) && this.validateZiliao(true) && this.validateRecord(true) && this.validateCheck(true) && this.validateBack(true)){
            fileList_basic.forEach(item=>{
              if(baseImg){
                baseImg+="," +item.url
              }else{
                baseImg+=item.url; 
              }
            }) 
   
            fileList_bio.forEach(item=>{
                if(bioImg){
                    bioImg+="," +item.url
                }else{
                    bioImg+=item.url; 
                }
              });
              fileList_coa.forEach(item=>{
                if(coaImg){
                    coaImg+="," +item.url
                }else{
                    coaImg+=item.url; 
                }
              });
              fileList_inf.forEach(item=>{
                if(infImg){
                    infImg+="," +item.url
                }else{
                    infImg+=item.url; 
                }
              });
              dpmas_list.forEach((item,index)=>{
                let imgStr='';
                let itemArr=item.fileList;
                itemArr.forEach((cell)=>{
                    if(imgStr){
                        imgStr+="," +cell.url
                    }else{
                        imgStr+=cell.url; 
                    }
                }) 
                let cur='case.dpmas['+index+'].dpmasImg'
                this.setData({
                    [cur]:imgStr
                })
              })
             this.setData({
                 'case.mainDiagnose.mainDiagnoseImg':baseImg,
                 'case.bioImg':bioImg,
                 'case.coaImg':coaImg,
                 'case.infImg':infImg
             })
             let caseObj=this.formatString(this.data.case);
             caseObj.caseType=JSON.stringify(this.data.case.caseType);
             let {admissionTime,headTime,afterTime,lastTime,dischargeTime}=this.data.case;
             Object.assign(caseObj,{
                 admissionTime:dayjs(admissionTime).format('YYYY-MM-DD HH:mm:ss'),
                 headTime:dayjs(headTime).format('YYYY-MM-DD HH:mm:ss'),
                 afterTime:dayjs(afterTime).format('YYYY-MM-DD HH:mm:ss'),
                 lastTime:lastTime?dayjs(lastTime).format('YYYY-MM-DD HH:mm:ss'):'',
                 dischargeTime:dayjs(dischargeTime).format('YYYY-MM-DD HH:mm:ss')
             })
            addCase({...caseObj}).then(res=>{
                wx.showToast({
                  title: '病例创建成功',
                  icon:'none'
                })
                // if(this.data.isUseDraft){
                    wx.setStorageSync('caseDraft','')
                // }
                wx.navigateBack();
            })
       }
     
    },
    handleEditCase(){
        let {fileList_basic,fileList_bio,dpmas_list,fileList_coa,fileList_inf,medicalRecordId}=this.data;
         let baseImg='';
         let bioImg='';
         let coaImg='';
         let infImg='';
        if(this.validateBasic(true) && this.validateZiliao(true) && this.validateRecord(true) && this.validateCheck(true) && this.validateBack(true)){
            fileList_basic.forEach(item=>{
                if(baseImg){
                  baseImg+="," +item.url
                }else{
                  baseImg+=item.url; 
                }
              }) 
          
              fileList_bio.forEach(item=>{
                if(bioImg){
                    bioImg+="," +item.url
                }else{
                    bioImg+=item.url; 
                }
              });
              fileList_coa.forEach(item=>{
                if(coaImg){
                    coaImg+="," +item.url
                }else{
                    coaImg+=item.url; 
                }
              });
              fileList_inf.forEach(item=>{
                if(infImg){
                    infImg+="," +item.url
                }else{
                    infImg+=item.url; 
                }
              });
                dpmas_list.forEach((item,index)=>{
                  let imgStr='';
                  let itemArr=item.fileList;
                  itemArr.forEach((cell)=>{
                      if(imgStr){
                          imgStr+="," +cell.url
                      }else{
                          imgStr+=cell.url; 
                      }
                  }) 
                  let cur='case.dpmas['+index+'].dpmasImg'
                  this.setData({
                      [cur]:imgStr
                  })
                })
               this.setData({
                   'case.mainDiagnose.mainDiagnoseImg':baseImg,
                   'case.bioImg':bioImg,
                   'case.coaImg':coaImg,
                   'case.infImg':infImg
               })
               let {admissionTime,headTime,afterTime,lastTime,dischargeTime}=this.data.case;
                this.setData({
                    'case.id':medicalRecordId
                })
               let caseObj=this.formatString(this.data.case);
               caseObj.caseType=JSON.stringify(this.data.case.caseType);
               Object.assign(caseObj,{
                   admissionTime:dayjs(admissionTime).format('YYYY-MM-DD HH:mm:ss'),
                   headTime:dayjs(headTime).format('YYYY-MM-DD HH:mm:ss'),
                   afterTime:dayjs(afterTime).format('YYYY-MM-DD HH:mm:ss'),
                   lastTime:lastTime?dayjs(lastTime).format('YYYY-MM-DD HH:mm:ss'):"",
                   dischargeTime:dayjs(dischargeTime).format('YYYY-MM-DD HH:mm:ss')
               })
            editCase({...caseObj}).then(res=>{
                wx.showToast({
                  title: '病例修改成功',
                  icon:'none'
                })
                wx.navigateBack();
            })
        }
       
    },
    initAllvalue(res){
           let caseObj=this.data.case;
           console.log(caseObj);
            for (const key in caseObj) {
                if(key=="admissionTime" || key=="dischargeTime"){
                    this.setData({
                        ['case.'+key]:res[key]?dayjs(res[key]).format('YYYY-MM-DD'):''
                       })
                }else if(key=="caseType"){
                   if(typeof res[key]=="string"){
                    this.setData({
                        ['case.'+key]:JSON.parse(res[key])
                    }) 
                   }else{
                    this.setData({
                        ['case.'+key]:res[key]
                    }) 
                   }
                }else if(key=='mainDiagnose'){
                    this.setData({
                        'case.mainDiagnose':res[key]
                    })
                    if(res[key].mainDiagnoseImg){
                        let imgList=res[key].mainDiagnoseImg.split(',');
                        let arr=imgList.map(item=>{
                            return {url:item,type:'image',isImage: true}
                        })
                        this.setData({
                            'fileList_basic':arr 
                        })
                    }
                   
                }else if(key=='bioImg'){
                    if(res[key]){
                        let imgList=res[key].split(',');
                    console.log(imgList)
                    this.setData({
                        ['case.'+key]:res[key],
                        fileList_bio:imgList.map(item=>{
                            return {url:item,type:'image',isImage: true}
                        })
                    }) 
                    }
                    
                }else if(key=='coaImg'){
                    if(res[key]){
                        let imgList=res[key].split(',');
                    this.setData({
                        ['case.'+key]:res[key],
                        fileList_coa:imgList.map(item=>{
                            return {url:item,type:'image',isImage: true}
                        })
                    }) 
                    }
                    
                }else if(key=='infImg'){
                   console.log(22333)
                    if(res[key]){
                        let imgList=res[key].split(',');
                    console.log(imgList)
                    this.setData({
                        ['case.'+key]:res[key],
                        fileList_inf:imgList.map(item=>{
                            return {url:item,type:'image',isImage: true}
                        })
                    }) 
                    }
                    
                }else if(key=='dpmas'){
                   let arr=res[key];
                    this.setData({
                        ['case.'+key]:arr
                    }) 
                    arr.forEach((item,index)=>{
                        if(item.dpmasImg){
                        let imgList=item.dpmasImg.split(',');
                        
                        let objFile="dpmas_list["+index+"].fileList";
                        let tempFile="dpmas_list["+index+"].temp_list"
                        let objTime="dpmas_list["+index+"].treatTime"
                        let newArr=imgList.map(item1=>{
                            return {url:item1,type:'image',isImage: true}
                        });
                        this.setData({
                           [objFile]:newArr,
                           [tempFile]:newArr,
                        [objTime]:item.treatTime?dayjs(item.treatTime).format('YYYY-MM-DD'):''
                        })
                        }
                        
                    })

                }else if(key=='headTime' || key=='afterTime' || key=="lastTime"){
                  this.setData({
                    ['case.'+key]:res[key]?dayjs(res[key]).format('YYYY-MM-DD'):''
                  })
                }else if(key=='abstractStr'){
                    this.setData({
                        wordLength:res[key].length,
                        ['case.'+key]:res[key]
                    }) 
                    
                }else{
                    this.setData({
                        ['case.'+key]:res[key]
                    }) 
                }
               
              }
    },
    handleCaseDetail(){
        let { medicalRecordId}=this.data;
        caseDetail(medicalRecordId).then(res=>{
            let result=this.formatJson(res);
            console.log(result);
            this.initAllvalue(result)
        })
    },
    onBeforeChange(event){
        let {index,callback}=event.detail;
        if(index==0){
            this.setData({
               active:0
            })
            callback(true);
        }else if(index==1){
         if(this.validateBasic(true)){
            callback(true);
            this.setData({
                active:1 
             })
             
          }else{
            //   this.setData({
            //     showAttention:true
            //   })
            callback(false)
          }
         }else if(index==2){
           if(this.validateBasic(true) && this.validateZiliao(true)){
            callback(true);
            this.setData({
                active:2
             })
          }else{
            // this.setData({
            //     showAttention:true
            //   })
            callback(false)  
          }
         }else if(index==3){
            if(this.validateBasic(true) && this.validateZiliao(true) && this.validateRecord(true)){
            callback(true);
            this.setData({
                active:3
             })
           }else{
            // this.setData({
            //     showAttention:true
            //   })
            callback(false)  
           }
         }else if(index==4){
            if(this.validateBasic(true) && this.validateZiliao(true) && this.validateRecord(true) && this.validateCheck(true)){
            callback(true);
            this.setData({
                active:4
             })
             }else{
            // this.setData({
            //    showAttention:true
            //   })
            callback(false)  
           }
         }else if(index==5){
            callback(true);
            this.setData({
                active:5
             })
         }
    },
    confirmDelRecord(event){
        let {index}=event.currentTarget.dataset;
       this.setData({
        showDel:true,
        delIndex:index
       })
    },
    delRecord(){
    let {dpmas}=this.data.case;
    let {dpmas_list}=this.data;
    let index=this.data.delIndex;
    dpmas.splice(index,1);
      dpmas_list.splice(index,1);
      this.setData({
        'case.dpmas':dpmas,
         dpmas_list:dpmas_list
      })

    },
    addRecord(){
        let obj={
            'treatTime':'',
              'content':{             
                "mode":{ // 模式
                    "select":"",
                    "otherValue":"",
               },
               "plasma":{ // 血浆
                    "handle":"",
                    "replace":""
                },
                "dose":{ // 抗凝剂量
                    "select":[],
                    "heparin":{ // 肝素
                            "firstDose":"",//首剂
                            "firstDoseUnit":'1',
                            "append":"",//追加
                            "appendUnit":'1',
                    },
                    "lowHeparin":{ // 低分子肝素
                            "value":""
                    },
                    "citricAcid":{ // 枸橼酸
                            "bloodFlowRate":"",//血液流速
                            "citricAcidFlowRate":"",//枸橼酸钠流速
                            "calciumAgent":{ // 钙剂
                                    "select":"",
                                      "value":"",
                            }
                    },
                    "nafamostat":{ // 甲磺酸萘莫司他
                            "value":""
                    },
                    "other":{ // 其他
                            "name":"",
                            "dose":""
                    }
                 }
                
            },
            dpmasImg:''
        };
       this.setData({
           'case.dpmas':this.data.case.dpmas.concat([obj]),
           'dpmas_list':this.data.dpmas_list.concat([{fileList:[],treatTime:''}])

       })
    },
    onClickDisabled(event){
        let {index}=event.detail;
          if(index==1){
             this.validateBasic(false);
          }else if(index==2){
            this.validateBasic();
            this.validateZiliao();
          }else if(index==3){
            this.validateBasic();
            this.validateZiliao();
            this.validateRecord();
          }else if(index==4){
            this.validateBasic();
            this.validateZiliao();
            this.validateRecord();
            this.validateCheck();
          }
       
    },
    validateBasic(flag){
       let {name,uid,sex,age,admissionTime,caseType,mainDiagnose,diseaseCause,seductionReason,treatmentNum}=this.data.case;
       let {fileList_basic}=this.data;
        if(!name){
            flag && wx.showToast({
                title: '患者姓名不能为空',
                icon:"none"
            })
            return false
        }
        if(!uid){
            flag && wx.showToast({
            title: '患者ID号不能为空',
            icon:"none"
            })
            return false
        }
        if(!sex){
          
            flag && wx.showToast({
            title: '性别不能为空',
            icon:"none"
            })
            return false
        }
        if(!age){
            flag && wx.showToast({
            title: '年龄不能为空',
            icon:"none"
            })
            return false
        }
        if(!admissionTime){
            flag && wx.showToast({
            title: '入院时间不能为空',
            icon:"none"
            })
            return false
        }
        if(caseType.length==0){
            flag && wx.showToast({
            title: '请选择治疗类型',
            icon:"none"
            })
            return false
        };
        if(treatmentNum<1){
            flag && wx.showToast({
                title: '治疗次数不小于1次',
                icon:"none"
                })
                return false
        }
        if(treatmentNum>9999){
            flag && wx.showToast({
                title: '治疗次数不能超过9999次',
                icon:"none"
                })
                return false
        }
        if(mainDiagnose.select.length==0){
            flag && wx.showToast({
                title: '请选择主要诊断类型',
                icon:"none"
                })
                return false
        }
        if(mainDiagnose.select.includes('-1') && !mainDiagnose.otherValue){
            flag && wx.showToast({
                title: '主要诊断其他不能为空',
                icon:"none"
                })
                return false
        }
        if(fileList_basic.length==0){
            flag && wx.showToast({
            title: '请上传出院诊断照片',
            icon:"none"
            })
            return false
        }
        //console.log(this.data.case)
        if(diseaseCause.select.length==0){
            flag && wx.showToast({
                title: '请选择患者病因类型',
                icon:"none"
                })
                return false
        }
        if(diseaseCause.select.includes('-1') && !diseaseCause.otherValue){
            flag && wx.showToast({
                title: '患者病因其他不能为空',
                icon:"none"
                })
                return false
        }

        let {dpmas}=this.data.case;
        let {dpmas_list}=this.data;
    
           let obj={
            'treatTime':'',
              'content':{             
                "mode":{ // 模式
                    "select":"",
                    "otherValue":"",
               },
               "plasma":{ // 血浆
                    "handle":"",
                    "replace":""
                },
                "dose":{ // 抗凝剂量
                    "select":[],
                    "heparin":{ // 肝素
                            "firstDose":"",//首剂
                            "firstDoseUnit":'1',
                            "append":"",//追加
                            "appendUnit":'1',
                    },
                    "lowHeparin":{ // 低分子肝素
                            "value":""
                    },
                    "citricAcid":{ // 枸橼酸
                            "bloodFlowRate":"",//血液流速
                            "citricAcidFlowRate":"",//枸橼酸钠流速
                            "calciumAgent":{ // 钙剂
                                    "select":"",
                                      "value":"",
                            }
                    },
                    "nafamostat":{ // 甲磺酸萘莫司他
                            "value":""
                    },
                    "other":{ // 其他
                            "name":"",
                            "dose":""
                    }
                 }
                
            },
            dpmasImg:''
        };
        if(caseType.length==1 && caseType[0]==1){
          if(dpmas.length<=1){
              this.setData({
                  'case.dpmas':dpmas.concat([obj]),
                  'dpmas_list':dpmas_list.concat([{fileList:[],treatTime:'',temp_list:[]}])
       
              })
          }
        }
      
        // if(seductionReason.inside.select.length==0){
        //     flag && wx.showToast({
        //         title: '请选择诱因肝内类型',
        //         icon:"none"
        //         })
        //         return false
        // }
        // if(seductionReason && seductionReason.inside && seductionReason.inside.select && seductionReason.inside.select.indexOf('-1')!=-1 && !seductionReason.inside.otherValue){
        //     flag && wx.showToast({
        //         title: '请选择诱因肝内其他不能为空',
        //         icon:"none"
        //         })
        //         return false
        // }
        // if(seductionReason.outside.select.length==0){
        //     flag && wx.showToast({
        //         title: '请选择诱因肝外类型',
        //         icon:"none"
        //         })
        //         return false
        // }
        // if(seductionReason && seductionReason.outside && seductionReason.outside.select && seductionReason.outside.select.indexOf('-1')!=-1 && !seductionReason.outside.otherValue){
        //     flag && wx.showToast({
        //         title: '请选择诱因肝外其他不能为空',
        //         icon:"none"
        //         })
        //         return false
        // }
        return true
    },
    validateZiliao(flag){
     let {abstractStr}=this.data.case;
     let html ="<p><br></p>";
      if(!abstractStr || abstractStr==html){
        flag && wx.showToast({
            title: '病历摘要不能为空',
            icon:"none"
            })
        return false
      }
  
      return true
    },
    validateRecord(flag){
        let {dpmas,admissionTime,caseType}=this.data.case;
        let {dpmas_list}=this.data;
        
      
        //  if(caseType==2 && dpmas.length<1){
        //     flag && wx.showToast({
        //         title: 'DPMAS治疗不少于1次',
        //         icon:'none'
        //       })
        //       return false;
        //  }
         for (let i = 0; i < dpmas.length; i++) {
            if(!dpmas[i].treatTime){
                flag && Toast({
                    message: '第'+(i+1)+'次治疗时间不能为空', 
                })
                return false;
            }
         };
         let time1=dayjs(admissionTime).format('YYYY-MM-DD');
         let time2=dayjs(dpmas[0].treatTime).format('YYYY-MM-DD');

         if(dayjs(time1).diff(dayjs(time2))>0){
            flag && Toast({
                message: '患者基本信息入院时间应该不晚于第一次治疗时间',
                icon:'none'
              })
              return false;
         }
         for (let i = 0; i < dpmas.length-1; i++) {
             if(dayjs(dpmas[i].treatTime).diff(dayjs(dpmas[i+1].treatTime))>=0){
                flag && Toast({
                    message: '第'+(i+1)+'次治疗时间应该早于第'+(i+2)+'次治疗时间',
                    icon:'none'
                  })
                  return false;
             }
             
         };   
       for (let i = 0;i < dpmas.length; i++) {
           let item=dpmas[i].content;
          if(!item.mode.select){
            flag && wx.showToast({
                title: '请选择第'+(i+1)+'次治疗模式',
                icon:'none'
              })
              return false;
          };
          if(item.mode.select==-1 && !item.mode.otherValue){
            flag && wx.showToast({
                title: '第'+(i+1)+'次治疗模式其他不能为空',
                icon:'none'
              })
              return false;
          }
          if(!item.plasma.handle){
            flag && wx.showToast({
                title: '第'+(i+1)+'次治疗血浆吸附处理量不能为空',
                icon:'none'
              })
              return false;
          }
          if(!item.plasma.replace){
            flag && wx.showToast({
                title: '第'+(i+1)+'次治疗血浆置换量不能为空',
                icon:'none'
              })
              return false;
          }
          
        //   if(item.dose.select.length>0){
            
        //     if(item.dose.select.includes('1')){
        //         if(!item.dose.heparin.firstDose){
        //           flag && wx.showToast({
        //               title: '第'+(i+1)+'次治疗抗凝剂量中肝素首剂不能为空',
        //               icon:'none'
        //             })
        //             return false;
        //         }
        //         if(!item.dose.heparin.append){
        //           flag && wx.showToast({
        //               title: '第'+(i+1)+'次治疗抗凝剂量中肝素追加不能为空',
        //               icon:'none'
        //             })
        //             return false;
        //         }
        //     }
  
        //     if(item.dose.select.includes('2')){
        //       if(!item.dose.lowHeparin.value){
        //           flag && wx.showToast({
        //               title: '第'+(i+1)+'次治疗抗凝剂量中低分子肝素不能为空',
        //               icon:'none'
        //             })
        //             return false;
        //         }
        //     }
        //     if(item.dose.select.includes('3')){
        //       if(!item.dose.citricAcid.bloodFlowRate){
        //           flag && wx.showToast({
        //               title: '第'+(i+1)+'次治疗枸橼酸中血液流速不能为空',
        //               icon:'none'
        //             })
        //             return false;
        //         }
        //         if(!item.dose.citricAcid.citricAcidFlowRate){
        //           flag && wx.showToast({
        //               title: '第'+(i+1)+'次治疗枸橼酸钠流速不能为空',
        //               icon:'none'
        //             })
        //             return false;
        //         }
        //         if(!item.dose.citricAcid.calciumAgent.select){
        //           flag && wx.showToast({
        //               title: '请选择第'+(i+1)+'次治疗枸橼酸中钙剂选项',
        //               icon:'none'
        //             })
        //             return false;
        //         }
        //         if(!item.dose.citricAcid.calciumAgent.value){
        //           flag && wx.showToast({
        //               title: '第'+(i+1)+'次治疗枸橼酸中钙剂剂量不能为空',
        //               icon:'none'
        //             })
        //             return false;
        //         }
                
        //     }
        //     if(item.dose.select.includes('4')){
        //       if(!item.dose.nafamostat.value){
        //           flag && wx.showToast({
        //               title: '第'+(i+1)+'次治疗抗凝剂量中甲磺酸萘莫司他不能为空',
        //               icon:'none'
        //             })
        //             return false;
        //         }
        //     }
        //     if(item.dose.select.includes('-1')){
        //       if(!item.dose.other.name){
        //           flag && wx.showToast({
        //               title: '第'+(i+1)+'次治疗抗凝剂量中其他名称不能为空',
        //               icon:'none'
        //             })
        //             return false;
        //         }
        //         if(!item.dose.other.dose){
        //           flag && wx.showToast({
        //               title: '第'+(i+1)+'次治疗抗凝剂量中其他剂量不能为空',
        //               icon:'none'
        //             })
        //             return false;
        //         }
        //     }
         // }
         
       }
         for (let index = 0; index <dpmas_list.length; index++) {
            if(dpmas_list[index].fileList.length==0){
                flag && wx.showToast({
                    title: '第'+(index+1)+'次治疗需要上传治疗照片',
                    icon:'none'
                  })
                  return false;
            } 
         };
         if(caseType.length==1 && caseType[0]==1){
             if(dpmas.length<=1){
                flag && wx.showToast({
                    title: '病例治疗类型为DPMAS或DPMAS联合模式时，需提交至少2次人工肝治疗记录',
                    icon:'none'
                  })
                  return false;
             }
         
         };

         return true
    },
    validateCheck(flag){
        let {headTime,afterTime,lastTime,headTb,afterTb,lastTb,headAlt,afterAlt,lastAlt,headAst,afterAst,lastAst,headInr,afterInr,lastInr,headAlb,afterAlb,lastAlb,admissionTime,dpmas}=this.data.case;
        let {fileList_bio,fileList_coa,fileList_inf}=this.data;
        if(!headTime){
        flag && wx.showToast({
            title: '首次治疗前检测时间不能为空',
            icon:"none"
            })
            return false
       };
       if(!afterTime){
        flag && wx.showToast({
            title: '首次治疗后检测时间不能为空',
            icon:"none"
            })
            return false
       };
       if(!lastTime && dpmas.length>1){
        flag && wx.showToast({
            title: '最后一次治疗后检测时间不能为空',
            icon:"none"
            })
            return false
       };
       let headTime_new=dayjs(headTime).format('YYYY-MM-DD');
       let afterTime_new=dayjs(afterTime).format('YYYY-MM-DD');
       let lastTime_new=dayjs(lastTime).format('YYYY-MM-DD');
       let firstTime=dayjs(dpmas[0].treatTime).format('YYYY-MM-DD');//第一次治疗时间
       
       let lastTreatTime=dayjs(dpmas[dpmas.length-1].treatTime).format('YYYY-MM-DD')//最后一次治疗时间
       
       let admissionTime_new=dayjs(admissionTime).format('YYYY-MM-DD'); //住院时间
       if(dayjs(admissionTime_new).diff(dayjs(headTime_new))>0){
        flag && Toast({
            message: '患者基本信息入院时间应该不晚于首次人工肝治疗前检测时间',
            icon:'none'
          })
          return false;
     };
     if(dayjs(headTime_new).diff(dayjs(firstTime))>0){
        flag && Toast({
            message: '首次人工肝治疗前检测时间应该不晚于第一次治疗时间',
            icon:'none'
          })
          return false;
     };
     if(dayjs(firstTime).diff(dayjs(afterTime_new))>0){
        flag && Toast({
            message: '第一次治疗时间应该不晚于首次人工肝治疗后检测时间',
            icon:'none'
          })
          return false;
     };
     //新加判断
     if(dayjs(headTime_new).diff(dayjs(afterTime_new))>0){
        flag && Toast({
            message: '首次人工肝治疗时前检测时间应该不晚于首次人工肝治疗后检测时间',
            icon:'none'
          })
          return false;
     }

     if(lastTime){
        if(dayjs(afterTime_new).diff(dayjs(lastTime_new))>=0){
            flag && Toast({
                message: '首次人工肝治疗后检测时间应该早于最后一次人工肝治疗后检测时间',
                icon:'none'
              })
              return false;
         }
     }
     
     if(dpmas.length>1){
        let secondTreatTime=dayjs(dpmas[1].treatTime).format('YYYY-MM-DD')
        if(dayjs(afterTime_new).diff(dayjs(secondTreatTime))>0){
            flag && Toast({
                message: '首次人工肝治疗后检测时间应该不晚于第二次治疗时间',
                icon:'none'
              })
              return false;
         }
         if(dayjs(lastTreatTime).diff(dayjs(lastTime_new))>0){
            flag && Toast({
                message: '最后一次治疗时间应该不晚于最后一次人工肝治疗后检测时间',
                icon:'none'
              })
              return false;
         }
     }
    //  let time1=dayjs(admissionTime).format('YYYY-MM-DD');
    //  let time2=dayjs(dpmas[0].treatTime).format('YYYY-MM-DD');

  
    //    if(caseType==2){
    //     if(!(dayjs(headTime_new).diff(dayjs(admissionTime_new))>=0 && dayjs(headTime_new).diff(dayjs(firstTime))<=0)){
    //         flag && wx.showToast({
    //             title: '治疗前检测时间应该在入院时间与第一次治疗时间之间',
    //             icon:"none"
    //             })
    //             return false
    //       }
    //       if(dpmas.length<2){
    //           if(!(dayjs(afterTime_new).diff(dayjs(firstTime))>=0)){
    //             flag && wx.showToast({
    //                 title: '治疗后检测时间应该在第一次之后',
    //                 icon:"none"
    //                 })
    //                 return false
    //           }

    //      }else{
    //         let secondTime=dayjs(dpmas[1].treatTime).format('YYYY-MM-DD')
    //         if(!(dayjs(afterTime_new).diff(dayjs(firstTime))>=0 && dayjs(afterTime_new).diff(dayjs(secondTime))<=0)){
    //             flag && wx.showToast({
    //                 title: '治疗后检测时间应该在第一次与第二次治疗时间之间',
    //                 icon:"none"
    //                 })
    //                 return false
    //           };
    //     }
         
         
    //    };
    //    if(caseType==1){
    //         if(!(dayjs(headTime_new).diff(dayjs(admissionTime_new))>=0 && dayjs(headTime_new).diff(dayjs(firstTime))<=0)){
    //             flag && wx.showToast({
    //                 title: '治疗前检测时间应该在入院时间与第一次治疗时间之间',
    //                 icon:"none"
    //                 })
    //                 return false
    //         }
    //         if(!(dayjs(afterTime_new).diff(dayjs(lastTime)>=0))){
    //             flag && wx.showToast({
    //                 title: '治疗后检测时间应该最后一次治疗时间之后',
    //                 icon:"none"
    //                 })
    //                 return false
    //           }
    //    }
       if(!headTb || !afterTb){
        flag && wx.showToast({
            title: '总胆红素首次治疗前后未填写完整',
            icon:"none"
            })
            return false
       };
       if(dpmas.length>1){
        if(!lastTb){
            flag && wx.showToast({
                title: '总胆红素最后一次治疗后不能为空',
                icon:"none"
                })
            return false
        }
      }
       if(!headAlt || !afterAlt){
        flag && wx.showToast({
            title: '丙氨酸氨基转移酶首次治疗前后未填写完整',
            icon:"none"
            })
            return false
       };
       if(dpmas.length>1){
        if(!lastAlt){
            flag && wx.showToast({
                title: '丙氨酸氨基转移酶最后一次治疗后不能为空',
                icon:"none"
                })
            return false
        }
      }
       if(!headAst || !afterAst){
        flag && wx.showToast({
            title: '天门冬氨酸氨基转移酶首次治疗前后未填写完整',
            icon:"none"
            })
            return false
       };
       if(dpmas.length>1){
        if(!lastAst){
            flag && wx.showToast({
                title: '天门冬氨酸氨基转移酶最后一次治疗后不能为空',
                icon:"none"
                })
            return false
        }
      }
       if(!headAlb || !afterAlb){
        flag && wx.showToast({
            title: '白蛋白首次治疗前后未填写完整',
            icon:"none"
            })
            return false
       };
      
       if(dpmas.length>1){
        if(!lastAlb){
            flag && wx.showToast({
                title: '白蛋白最后一次治疗后不能为空',
                icon:"none"
                })
            return false
        }
      }
      if(fileList_bio.length==0){
        flag && wx.showToast({
            title: '请上传生化检测报告单',
            icon:"none"
            })
        return false
    }
       if(!headInr || !afterInr){
        flag && wx.showToast({
            title: '国际标准化比值首次治疗前后未填写完整',
            icon:"none"
            })
            return false
       }
       if(dpmas.length>1){
        if(!lastInr){
            flag && wx.showToast({
                title: '国际标准化比值最后一次治疗后不能为空',
                icon:"none"
                })
            return false
        }
      }
      if(fileList_coa.length==0){
        flag && wx.showToast({
            title: '请上传凝血功能检测报告单',
            icon:"none"
            })
        return false
     }
        return true;
    },
    validateBack(flag){
        let {dischargeTime,day,dischargeStatus,dischargeSituation,dpmas,lastTime,afterTime}=this.data.case;
        let dischargeTime_new=dayjs(dischargeTime).format('YYYY-MM-DD');
       
        let lastTreatTime=dayjs(dpmas[dpmas.length-1].treatTime).format('YYYY-MM-DD')//最后一次治疗时间
         if(!dischargeTime){
            flag && wx.showToast({
                title: '请选择出院时间',
                icon:"none"
                })
                return false
        }
        if(dpmas.length==1){
            let afterTime_new=dayjs(afterTime).format('YYYY-MM-DD');
            if(dayjs(afterTime_new).diff(dayjs(dischargeTime_new))>0){
              flag && Toast({
                  message: '首次人工肝治疗后检测时间应该不晚于出院时间',
                  icon:'none'
                })
                return false;
           }
           }
       
        
         if(dpmas.length>1){
            if(dayjs(lastTreatTime).diff(dayjs(dischargeTime_new))>0){
                flag && Toast({
                    message: '最后一次治疗时间应该不晚于出院时间',
                    icon:'none'
                  })
                  return false;
             }
            let lastTime_new=dayjs(lastTime).format('YYYY-MM-DD');
            if(dayjs(lastTime_new).diff(dayjs(dischargeTime_new))>0){
                flag && Toast({
                    message: '最后一次人工肝治疗后检测时间应该不晚于出院时间',
                    icon:'none'
                  })
                  return false;
             }
         }
        if(!day){
            flag && wx.showToast({
                title: '请输入住院天数',
                icon:"none"
                })
                return false
        }
        if(!dischargeSituation){
            flag && wx.showToast({
                title: '请输入出院情况',
                icon:"none"
                })
                return false
        }
        if(!dischargeStatus){
            flag && wx.showToast({
                title: '请输入出院状态',
                icon:"none"
                })
                return false
        }
        return true
    },

    openType(){
        if(!this.data.showSaveBtn)return;
        this.setData({
            showType:true,
        })
    },
    onCancelType(){
        this.setData({
            showType:false,
        })
    },
    onConfirmType(event){
        let {value,text}=event.detail.value;
        this.setData({
            showType:false,
            'typeName':text,
            'case.caseType':value
        })
    },
    saveDraft(){
        let {fileList_basic,fileList_bio,dpmas_list,fileList_coa,fileList_inf}=this.data;
        let baseImg='';
        let bioImg='';
        let coaImg='';
        let infImg='';
        fileList_basic.forEach(item=>{
            if(baseImg){
              baseImg+="," +item.url
            }else{
              baseImg+=item.url; 
            }
          }) 
            fileList_bio.forEach(item=>{
              if(bioImg){
                bioImg+="," +item.url
              }else{
                bioImg+=item.url; 
              }
            });
            fileList_coa.forEach(item=>{
                if(coaImg){
                    coaImg+="," +item.url
                }else{
                    coaImg+=item.url; 
                }
              });
              fileList_inf.forEach(item=>{
                if(infImg){
                    infImg+="," +item.url
                }else{
                    infImg+=item.url; 
                }
              });
            dpmas_list.forEach((item,index)=>{
              let imgStr='';
              let itemArr=item.fileList;
              itemArr.forEach((cell)=>{
                  if(imgStr){
                      imgStr+="," +cell.url
                  }else{
                      imgStr+=cell.url; 
                  }
              }) 
              let cur='case.dpmas['+index+'].dpmasImg'
              this.setData({
                  [cur]:imgStr
              })
            })
           this.setData({
               'case.mainDiagnose.mainDiagnoseImg':baseImg,
               'case.infImg':infImg,
               'case.coaImg':coaImg,
               'case.bioImg':bioImg
           })
           let caseObj=this.data.case;
           let {admissionTime,headTime,afterTime}=this.data.case;
           Object.assign(caseObj,{
               admissionTime:admissionTime?dayjs(admissionTime).format('YYYY-MM-DD HH:mm:ss'):'',
               headTime:headTime?dayjs(headTime).format('YYYY-MM-DD HH:mm:ss'):'',
               afterTime:afterTime?dayjs(afterTime).format('YYYY-MM-DD HH:mm:ss'):''
           })
        //    wx.setStorageSync("draftTime",dayjs(new Date().getTime()).format('YYYY-MM-DD'));
           wx.setStorageSync('caseDraft',JSON.stringify({...caseObj}))

    },
    onConfirmUseDraft(){
        let caseDraft=wx.getStorageSync('caseDraft');
            if(caseDraft){
                this.initAllvalue(JSON.parse(caseDraft))
        }
        this.setData({
            showUseDraft:false,
            isUseDraft:true
        })

    },
    onCancelUseDraft(){
        this.setData({
            showUseDraft:false
        });

    },
    onConfirmDraft(){
        this.saveDraft()
        this.setData({
            showDraft:false
        });
        
        wx.navigateBack()
    },
    onCancelDraft(){
        this.setData({
            showDraft:false
        })
        wx.navigateBack()
    },
    onConfirmAttention(){
     this.setData({
         showAttention:false
     })
    },
    onConfirmTip(){
        this.setData({
            showTip:false
        })
       },
    onConfirmDel(){
        this.setData({
            showDel:false
        })
        this.delRecord();
       },
       onCancelDel(){
        this.setData({
            showDel:false
        })
       },
   cancelDate(){
    this.setData({
        showTime:false,
    });
   },
   onInput(event) {
        this.setData({
        currentDate: event.detail,
        });
  },
    confirmDate(event) {
        let {time_str,dealIndex}=this.data;
        let key='';
        let time='';
        if(time_str=="hospitalTime"){
            key='admissionTime'
            time=dayjs(event.detail).format('YYYY-MM-DD')
        }else if(time_str=="dischargeTime"){
            key='dischargeTime'
            time=dayjs(event.detail).format('YYYY-MM-DD')
        }else if(time_str=="dealTime"){
            key="dealTime"
            let year=dayjs(event.detail).format('YYYY')
            // if(year!=2024){
            //     this.setData({
            //         showTip:true,
            //         showTime:false
            //     })
            //     return false
            // }
            time=dayjs(event.detail).format('YYYY-MM-DD');
          
        }else if(time_str=="headTime"){
            key="headTime"
            time=dayjs(event.detail).format('YYYY-MM-DD')
        }else if(time_str=="afterTime"){
            key="afterTime";
            time=dayjs(event.detail).format('YYYY-MM-DD')
        }else if(time_str=="lastTime"){
            key="lastTime";
            time=dayjs(event.detail).format('YYYY-MM-DD')
        }
        if(key=="dealTime"){
            const obj = "case.dpmas[" + dealIndex + "].treatTime"
            const oterobj="dpmas_list[" + dealIndex + "].treatTime"
          this.setData({
            showTime:false,
            currentDate: event.detail,
            [oterobj]:dayjs(time).format('YYYY-MM-DD'),
            [obj]:time+ " 00:00:00"
          })
          //console.log(this.data.case.dpmas)
        }else{
            this.setData({
                currentDate: event.detail,
                showTime:false,
                ['case.'+key]: time,
            });
        }
       
       
      },
    handleIpt(e){
        let key = e.target.dataset.id; 
        let type=e.target.dataset.type;
       if(key=='name'){
           let value=e.detail.value;
           let newVal=String(value).toUpperCase();
           this.setData({
            ['case.'+key]:newVal
          })
       }else{
            let iptValue='';
            let tempValue=e.detail.value;
           if( type=='number'){
               console.log(this.countDecimals(tempValue));
            iptValue=this.countDecimals(tempValue)>3?Number(tempValue).toFixed(3):tempValue
           }else{
            iptValue=tempValue
           }
           if(key=='age' || key=="day" || key=="treatmentNum"){
               if(e.detail.value!=''){
                   this.setData({
                    ['case.'+key]:Number(e.detail.value)
                   })
               }else{
                this.setData({
                    ['case.'+key]:null
                   })
               }
           }else{
            this.setData({
                ['case.'+key]:iptValue
              })
           }
        
       }
       
       
     },
     onChangeEditor(event){
       // console.log(event);
        this.setData({
            'case.abstractStr':event.detail.html
        })
     },
     onChangeEditorDischarge(event){
        // console.log(event);
         this.setData({
             'case.dischargeSituation':event.detail.html
         })
      },
      dischargeFocus(event){
        //event.preventDefault();
        // setTimeout(()=>{
        //     wx.pageScrollTo({
        //         scrollTop: 99999
        //       })
        // })
      },
     countDecimals(num) {
        // 将数值转换为字符串
        const str = String(num);
        // 匹配小数点及其后面的数字
        const match = str.match(/\.(\d+)/);
        // 返回小数位数
        return match ? match[1].length : 0;
      },
     openTime(){
        if(!this.data.showSaveBtn)return;
         const caseInfo=this.data.case;
        this.setData({
            showTime:true,
            currentDate:caseInfo.admissionTime?new Date(caseInfo.admissionTime).getTime():new Date().getTime(),
            time_type:'date',
            time_str:"hospitalTime",
             time_title:'选择入院时间',
        })
     },
     openDischargeTime(){
        if(!this.data.showSaveBtn)return;
        const caseInfo=this.data.case;
        this.setData({
           showTime:true,
           currentDate:caseInfo.dischargeTime?new Date(caseInfo.dischargeTime).getTime():new Date().getTime(),
           time_type:'date',
           time_str:"dischargeTime",
            time_title:'选择出院时间',
       })
     },
     openDealTime(event){
        if(!this.data.showSaveBtn)return;
        const caseInfo=this.data.case;
         let {index}=event.currentTarget.dataset;
         console.log( caseInfo.dpmas )
         console.log(caseInfo.dpmas[index].treatTime)
        this.setData({
            showTime:true,
            currentDate:caseInfo.dpmas[index].treatTime?new Date(dayjs(caseInfo.dpmas[index].treatTime).format("YYYY-MM-DD HH:mm:ss")).getTime():new Date().getTime(),
            dealIndex:index,
            time_type:'date',
            time_str:"dealTime",
            time_title:'选择治疗时间',
           // maxDate:new Date(dayjs().add(10,'year').toString()).getTime()
        })
     },
     openHeadTime(){
        if(!this.data.showSaveBtn)return;
        const caseInfo=this.data.case;
        this.setData({
            showTime:true,
            currentDate:caseInfo.headTime?new Date(dayjs(caseInfo.headTime).format("YYYY-MM-DD HH:mm:ss")).getTime():new Date().getTime(),
            time_type:'date',
            time_str:"headTime",
             time_title:'选择时间',
        })
     },
     openAfterTime(){
        if(!this.data.showSaveBtn)return;
        const caseInfo=this.data.case;
        this.setData({
            showTime:true,
            currentDate:caseInfo.afterTime?new Date(dayjs(caseInfo.afterTime).format("YYYY-MM-DD HH:mm:ss")).getTime():new Date().getTime(),
            time_type:'date',
            time_str:"afterTime",
             time_title:'选择时间',
        })
     },
     openLastTime(){
        if(!this.data.showSaveBtn)return;
        const caseInfo=this.data.case;
        this.setData({
            showTime:true,
            currentDate:caseInfo.lastTime?new Date(dayjs(caseInfo.lastTime).format("YYYY-MM-DD HH:mm:ss")).getTime():new Date().getTime(),
            time_type:'date',
            time_str:"lastTime",
             time_title:'选择时间',
        })
     },
     onChangeRadio(event) {
         console.log(event)
        let type=event.target.dataset.type;
        let clear=event.target.dataset.clear;
        this.setData({
         [type]:event.detail
        });
        if(clear){
            if(event.detail=="-1"){
                this.setData({
                    [clear]:''
                   });
            }
        }
       // console.log(this.data.case.content);
      },
   
       deleteImg(event){
        const { fileList_basic,fileList_bio,fileList_coa,fileList_inf,dpmas_list} = this.data;
        const {name,index} = event.detail;
       
        if(name=='basic'){
            fileList_basic.splice(index,1);
            this.setData({
                fileList_basic:fileList_basic
            })
        }else if(name=="bio"){
            fileList_bio.splice(index,1);
            this.setData({
                fileList_bio:fileList_bio
            })
        }else if(name=="inf"){
            fileList_inf.splice(index,1);
            this.setData({
                fileList_inf:fileList_inf
            })
        }else if(name=="coa"){
            fileList_coa.splice(index,1);
            this.setData({
                fileList_coa:fileList_coa
            })
        }else if(name.indexOf("record")!=-1){
            let recordIndex=Number(name.split("record")[1]);
            dpmas_list[recordIndex].fileList.splice(index,1);
            let obj="dpmas_list["+ recordIndex +"].fileList"
            this.setData({
                [obj]:dpmas_list[recordIndex].fileList
            })
        }
       },
      uploadImg(file,name){
        let THIS = this;
    return new Promise((resolve, reject) => {
        getOssSign(1).then(resdata=>{
            let { accessid, dir,policy,signature,host} = resdata;
              let imgUrl = file;
              //let index = imgUrl.lastIndexOf("/");
              let filename = dayjs().format('YYYYMMDDHHmmss')+FileUtil.UUID()+'.'+THIS.getImageFormat(imgUrl);

              //imgUrl.substring(index + 1, imgUrl.length);
            
                wx.uploadFile({
                    url: host, // 仅为示例，非真实的接口地址
                    filePath:  file,
                    name: 'file',
                    formData: {
                      OSSAccessKeyId: accessid,
                      policy,
                      key: dir + filename,
                      signature
                    },
                    success(res) {
                       
                      if (res.statusCode === 204 ) {
                          if(name){
                            wx.showToast({
                                title: '图片上传成功',
                                icon: "none"
                            })
                          }
                             
                        //resolve(true)
                        let url = host + dir + filename;
                        // 上传完成需要更新 fileList
                      
                        console.log(url);
                        console.log('name:'+name)
                        if(name=='basic'){
                            const { fileList_basic} = THIS.data;
                            fileList_basic.push({ url: url,type:'image',isImage:true });
                            THIS.setData({ fileList_basic });
                        }else if(name=='bio'){
                            const { fileList_bio} = THIS.data;
                            fileList_bio.push({ url: url,type:'image',isImage: true });
                            THIS.setData({ fileList_bio});
                        }else if(name=='coa'){
                            const { fileList_coa} = THIS.data;
                            fileList_coa.push({ url: url,type:'image',isImage: true});
                            THIS.setData({ fileList_coa});
                        }else if(name=='inf'){
                            const { fileList_inf} = THIS.data;
                            fileList_inf.push({ url: url,type:'image',isImage: true });
                            THIS.setData({ fileList_inf});
                        }else if(name.indexOf("record")!=-1){
                            let {dpmas_list}=THIS.data;
                            let recordIndex=Number(name.split("record")[1]);
                            console.log("recordIndex:"+recordIndex);
                            let objArr="dpmas_list[" +recordIndex +"]"
                            let obj="dpmas_list[" +recordIndex +"].fileList";
                            let tempObj="dpmas_list[" +recordIndex +"].temp_list"
                            try {
                                if(!(dpmas_list[recordIndex])){
                                    THIS.setData({
                                        [objArr]:{fileList:[],treatTime:'',temp_list:[]}
                                    }) 
                                }
                            } catch (error) {
                                
                            }
                            THIS.setData({
                               [obj]:THIS.data.dpmas_list[recordIndex].fileList.concat([{ url: url,type:'image',isImage: true}])
                            })
                        }else{
                            console.log(444)
                            resolve(url)
                        }
                       
                      }else{
                        reject(false)
                      }
                    },
                    fail: err => {
                      console.log(err);
                    }
                  });
              })
            

        })
     
      },
      getImageFormat(imageUrl){
          console.log(imageUrl)
        var parts = imageUrl.split('.');
        return parts[parts.length - 1];
      },
      afterhandlePaint(e){ 
          
          this.setData({
              showPaint:false
          })
          const {imgSrc,name}=e.detail
        console.log(e);
        this.uploadImg(imgSrc,name)
      },
      afterRead(event) {
        console.log( event.detail)
        const { file,name} = event.detail;
        this.setData({
            paintSrc:file.url,
            paintFrom:name,
            showPaint:true
        })
        console.log(file)
        // let fileArr=[file]
        // wx.showLoading({
        //     title: '图片上传中',
        //     mask: true
        //   })
        // var promiseFun = [];
        // for (let i = 0; i < fileArr.length; i++) {
        //   var cur_file = fileArr[i].url;
        //   promiseFun.push(
        //     this.uploadImg(cur_file,name)
        //   )
        // };
        // Promise.all(promiseFun).then((res) => {
        //     wx.showToast({
        //         title: '图片上传成功',
        //         icon: "none"
        //       })
        //       console.log(res.length+"张上传成功");
        //   wx.hideLoading();

        // }).catch(error=>{
        //     wx.showToast({
        //         title: '图片上传失败',
        //         icon: "none"
        //       })
        //     console.log(error)
        //     wx.hideLoading();
        // });
      },
      getModal(){
        const deviceInfo = wx.getDeviceInfo();
        const accountInfo = wx.getAccountInfoSync();
console.log(accountInfo); // 输出当前小程序的版本号
        console.log(deviceInfo);
        getMobileModel({
            mod:'型号：'+deviceInfo.brand +' 设备型号：'+deviceInfo.model+' 操作系统：'+deviceInfo.system +' 线上小程序版本号:' +accountInfo.miniProgram.version
        }).then(res=>{

        })
      },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if(options.imgUrl){
            console.log(options.imgUrl)
        }
        //let a=this.formatString(this.data.case);
        //console.log(a)
        //console.log(this.formatJson(a));
      if(options.medicalRecordId){
          if(options.status==0 || options.status==1){
            this.setData({
                medicalRecordId:options.medicalRecordId,
                navName:'查看病例',
                showSaveBtn:false,
              })
          }else{
            this.setData({
                showSaveBtn:true,
                medicalRecordId:options.medicalRecordId,
                navName:'病例详情'
              })
          }
          this.handleCaseDetail();
      }else{
          let caseDraft=wx.getStorageSync('caseDraft');
          this.setData({
            showSaveBtn:true,
          })
          if(caseDraft){
            this.setData({
                showUseDraft:true
              })
          }
      }
     
    //   console.log(this.data.case)
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getModal();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    // onShareAppMessage() {

    // }
})