// case/pages/createCase/createCase.js
import {addCase,caseDetail,editCase,getOssSign} from "../../../api/api"
const dayjs = require("../../../utils/dayjs");
import {throttle} from "../../../utils/util"
import { FileUtil } from '../../../utils/fileutil'
const app=getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        active:0,
        wordLength:0,
        showSaveBtn:true,
        delIndex:'',
        navName:'创建病例',
        showDraft:false,
        showUseDraft:false,
        isUseDraft:false,
        medicalRecordId:'',
        dealIndex:0,
        showTime:false,
        showType:false,
        img_host:app.hostConfig().imghost,
        showTip:false,
        showDel:false,
        showAttention:false,
        fileList_basic:[],
        fileList_abstract:[],
        fileList_check:[],
        dpmas_list:[{fileList:[],treatTime:''}],
        disable_ziliao:false,
        disable_record:false,
        disable_check:false,
        columns:[
            { text: '四次及以上疗程化', value: 1 },
            { text: '早前期（INR≤1.5）', value: 2 }
        ],
        typeName:'',
        case:{
            name:'',
            uid:'',
            sex:null,
            age:'',
            admissionTime:'',
            caseType:'',
            baseImg:'',
            abstractStr:'',
            abstractImg:'',
            dpmas:[{
                'dpmasImg':'',
                'treatTime':''
            }],
            headTime:'',
            afterTime:'',
            headTb:'',
            afterTb:'',
            headAlt:'',
            afterAlt:'',
            headAlb:'',
            afterAlb:'',
            headAst:'',
            afterAst:'',
            headInr:'',
            afterInr:'',
            headDb:'',
            afterDb:'',
            headIb:'',
            afterIb:'',
            headPta:'',
            afterPta:'',
            headIl6:'',
            afterIl6:'',
            headTnf:'',
            afterTnf:'',
            checkImg:''
        },
        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('2023-01-01').getTime(),
        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;
        },
    },
    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();
      },
    goBack:throttle(function(){
        let {medicalRecordId}=this.data;
        if(!medicalRecordId && this.isHasValue()){
            this.setData({
                showDraft:true
            })
        }else{
            wx.navigateBack()
        }
      
    }),
    isHasValue(){
       let {name,uid,sex,age,admissionTime,caseType,abstractStr,headTime,afterTime,headTb,afterTb,headAlt,afterAlt,headAlb,afterAlb,headAst,afterAst,headInr,afterInr,headDb,afterDb,headIb,afterIb,headPta,afterPta,headIl6,afterIl6,headTnf,afterTnf}=this.data.case;
       let {fileList_basic,fileList_abstract,fileList_check,dpmas_list}=this.data;
       let hasTime=dpmas_list.some(item=>{ return item.fileList.length>0});
    
       let hasImg=dpmas_list.some(item=>{ return item.treatTime!=''});

       if(name || uid || sex || age || admissionTime || caseType || 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_abstract.length>0 || fileList_check.length>0 || hasTime || hasImg){
           return true
       }else{
           return false
       }
    },
    handleAddCase(){
         let {fileList_basic,fileList_abstract,fileList_check,dpmas_list}=this.data;
         let baseImg='';
         let abstractImg='';
         let checkImg='';
        if(this.validateBasic(true) && this.validateZiliao(true) && this.validateRecord(true) && this.validateCheck(true)){
            fileList_basic.forEach(item=>{
              if(baseImg){
                baseImg+="," +item.url
              }else{
                baseImg+=item.url; 
              }
            }) 
            fileList_abstract.forEach(item=>{
                if(abstractImg){
                    abstractImg+="," +item.url
                }else{
                 abstractImg+=item.url; 
                }
              }) 
              fileList_check.forEach(item=>{
                if(checkImg){
                    checkImg+="," +item.url
                }else{
                    checkImg+=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.baseImg':baseImg,
                 'case.abstractImg':abstractImg,
                 'case.checkImg':checkImg
             })
             let caseObj=this.data.case;
             let {admissionTime,headTime,afterTime}=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')
             })
          
            addCase({...caseObj}).then(res=>{
                wx.showToast({
                  title: '病例创建成功',
                  icon:'none'
                })
                // if(this.data.isUseDraft){
                    wx.setStorageSync('caseDraft','')
                // }
                wx.navigateBack();
            })
       }
     
    },
    handleEditCase(){
        let {fileList_basic,fileList_abstract,fileList_check,dpmas_list,medicalRecordId}=this.data;
        let baseImg='';
        let abstractImg='';
        let checkImg='';
        if(this.validateBasic(true) && this.validateZiliao(true) && this.validateRecord(true) && this.validateCheck(true)){
            fileList_basic.forEach(item=>{
                if(baseImg){
                  baseImg+="," +item.url
                }else{
                  baseImg+=item.url; 
                }
              }) 
              fileList_abstract.forEach(item=>{
                  if(abstractImg){
                      abstractImg+="," +item.url
                  }else{
                   abstractImg+=item.url; 
                  }
                }) 
                fileList_check.forEach(item=>{
                  if(checkImg){
                      checkImg+="," +item.url
                  }else{
                      checkImg+=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.baseImg':baseImg,
                   'case.abstractImg':abstractImg,
                   'case.checkImg':checkImg
               })
               let {admissionTime,headTime,afterTime}=this.data.case;
                this.setData({
                    'case.id':medicalRecordId
                })
               let caseObj=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')
               })
            editCase({...caseObj}).then(res=>{
                wx.showToast({
                  title: '病例修改成功',
                  icon:'none'
                })
                wx.navigateBack();
            })
        }
       
    },
    initAllvalue(res){
           let caseObj=this.data.case;
            for (const key in caseObj) {
                if(key=="admissionTime"){
                    this.setData({
                        ['case.'+key]:res[key]?dayjs(res[key]).format('YYYY-MM-DD'):''
                       })
                }else if(key=='caseType'){
                    let {columns}=this.data;
                    for (let i = 0; i < columns.length; i++) {
                        if(columns[i].value==res[key]){
                            this.setData({
                                ['case.'+key]:res[key],
                                'typeName': columns[i].text
                            })
                            break;
                        }
                        
                    }
                }else if(key=='baseImg'){
                    if(res[key]){
                        let imgList=res[key].split(',');
                        this.setData({
                            ['case.'+key]:res[key],
                            fileList_basic:imgList.map(item=>{
                                return {url:item}
                            })
                        }) 
                    }
                    
                }else if(key=='abstractImg'){
                    if(res[key]){
                        let imgList=res[key].split(',');
                        this.setData({
                            ['case.'+key]:res[key],
                            fileList_abstract:imgList.map(item=>{
                                return {url:item}
                            })
                        }) 
                    }   
                }else if(key=='checkImg'){
                    if(res[key]){
                        let imgList=res[key].split(',');
                    console.log(imgList)
                    this.setData({
                        ['case.'+key]:res[key],
                        fileList_check:imgList.map(item=>{
                            return {url:item}
                        })
                    }) 
                    }
                    
                }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 objTime="dpmas_list["+index+"].treatTime"
                        this.setData({
                           [objFile]:imgList.map(item1=>{
                            return {url:item1}
                        }),
                        [objTime]:item.treatTime?dayjs(item.treatTime).format('YYYY-MM-DD HH'):''
                        })
                        }
                        
                    })

                }else if(key=='headTime' || key=='afterTime'){
                  this.setData({
                    ['case.'+key]:res[key]?dayjs(res[key]).format('YYYY-MM-DD HH'):''
                  })
                }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=>{
            this.initAllvalue(res)
        })
    },
    onBeforeChange(event){
        let {index,callback}=event.detail;
        if(index==0){
            this.setData({
               active:0
            })
            callback(true);
        }else if(index==1){
          if(this.validateBasic()){
            callback(true);
            this.setData({
                active:1 
             })
          }else{
              this.setData({
                showAttention:true
              })
            callback(false)
          }
         }else if(index==2){
          if(this.validateBasic(false) && this.validateZiliao(false)){
            callback(true);
            this.setData({
                active:2
             })
          }else{
            this.setData({
                showAttention:true
              })
            callback(false)  
          }
         }else if(index==3){
           if(this.validateBasic(false) && this.validateZiliao(false) && this.validateRecord(false)){
            callback(true);
            this.setData({
                active:3
             })
           }else{
            this.setData({
                showAttention:true
              })
            callback(false)  
           }
         }
    },
    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(){
       this.setData({
           'case.dpmas':this.data.case.dpmas.concat([{
            'dpmasImg':'',
            'treatTime':'' 
        }]),
         'dpmas_list':this.data.dpmas_list.concat({fileList:[]})

       })
    },
    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();
          }
       
    },
    validateBasic(flag){
       let {name,uid,sex,age,admissionTime,caseType}=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){
            console.log(flag)
            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){
            flag && wx.showToast({
            title: '病例类型不能为空',
            icon:"none"
            })
            return false
        }
        if(fileList_basic.length==0){
            flag && wx.showToast({
            title: '请上传病案照片',
            icon:"none"
            })
            return false
        }
        return true
    },
    validateZiliao(flag){
     let {abstractStr}=this.data.case;
     let {fileList_abstract}=this.data;
      if( !abstractStr && fileList_abstract.length==0){
        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==1 && dpmas.length<4){
            flag && wx.showToast({
                title: 'DPMAS治疗不少于4次',
                icon:'none'
              })
              return false;
         };
         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 && wx.showToast({
                  title: '第'+(i+1)+'次治疗时间不能为空',
                  icon:'none'
                })
                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 && wx.showToast({
                title: '患者基本信息入院时间应该早于第一次治疗时间',
                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 && wx.showToast({
                    title: '第'+(i+1)+'次治疗时间应该早于第'+(i+2)+'次治疗时间',
                    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;
            }
             
         };

         return true
    },
    validateCheck(flag){
        let {headTime,afterTime,headTb,afterTb,headAlt,afterAlt,headInr,afterInr,headDb,afterDb,headIb,afterIb,headPta,afterPta,headIl6,afterIl6,headTnf,afterTnf,caseType,admissionTime,dpmas }=this.data.case;
        let {fileList_check}=this.data;
       if(!headTime){
        flag && wx.showToast({
            title: '治疗前检测时间不能为空',
            icon:"none"
            })
            return false
       };
       if(!afterTime){
        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 firstTime=dayjs(dpmas[0].treatTime).format('YYYY-MM-DD');
       
       let lastTime=dayjs(dpmas[dpmas.length-1].treatTime).format('YYYY-MM-DD')
       let admissionTime_new=dayjs(admissionTime).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(!headAlt || !afterAlt){
        flag && wx.showToast({
            title: '谷丙转氨酶未填写完整',
            icon:"none"
            })
            return false
       };
       if(!headInr || !afterInr){
        flag && wx.showToast({
            title: '国际标准化比值未填写完整',
            icon:"none"
            })
            return false
       }
    //    if(!headDb || !afterDb){
    //     flag && wx.showToast({
    //         title: '直接胆红素未填写完整',
    //         icon:"none"
    //         })
    //         return false
    //    }
    //    if(!headIb || !afterIb){
    //     flag && wx.showToast({
    //         title: '间接胆红素未填写完整',
    //         icon:"none"
    //         })
    //         return false
    //    }
    //    if(!headPta || !afterPta){
    //     flag && wx.showToast({
    //         title: '凝血酶原活动度未填写完整',
    //         icon:"none"
    //         })
    //         return false
    //    }
    //    if(!headIl6 || !afterIl6){
    //     flag && wx.showToast({
    //             title: '白介素6未填写完整',
    //             icon:"none"
    //             })
    //             return false
    //     }
        // if(!headTnf || !afterTnf){
        //     wx.showToast({
        //         title: '肿瘤坏死因子',
        //         icon:"none"
        //         })
        //     return false
        // }
        if(fileList_check.length==0){
            flag && wx.showToast({
                title: '请上传报告单',
                icon:"none"
                })
            return false
        }
        return true;
    },
    onChangeAbstract(event){
        let {value}=event.detail 
        this.setData({
            wordLength:value.length>500?500:value.length,
            'case.abstractStr':value.length>500?value.substring(0,500):value
        })
    },
    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_abstract,fileList_check,dpmas_list}=this.data;
        let baseImg='';
        let abstractImg='';
        let checkImg='';
        fileList_basic.forEach(item=>{
            if(baseImg){
              baseImg+="," +item.url
            }else{
              baseImg+=item.url; 
            }
          }) 
          fileList_abstract.forEach(item=>{
              if(abstractImg){
                  abstractImg+="," +item.url
              }else{
               abstractImg+=item.url; 
              }
            }) 
            fileList_check.forEach(item=>{
              if(checkImg){
                  checkImg+="," +item.url
              }else{
                  checkImg+=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.baseImg':baseImg,
               'case.abstractImg':abstractImg,
               'case.checkImg':checkImg
           })
           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=="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 HH:mm');
          
        }else if(time_str=="headTime"){
            key="headTime"
            time=dayjs(event.detail).format('YYYY-MM-DD HH')
        }else if(time_str=="afterTime"){
            key="afterTime";
            time=dayjs(event.detail).format('YYYY-MM-DD HH')
        }
        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 HH'),
            [obj]:time+ ":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=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
           }
        this.setData({
            ['case.'+key]:key=="age"?Number(e.detail.value):iptValue
          })
       }
       
       
     },
     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:'选择入院时间',
        })
     },
     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:'datetime',
            time_str:"dealTime",
            time_title:'选择治疗时间',
        })
     },
     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:'datetime',
            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:'datetime',
            time_str:"afterTime",
             time_title:'选择治疗后检测时间',
        })
     },
     onChange(event) {
        this.setData({
         'case.sex':Number(event.detail),
        });
      },
   
       deleteImg(event){
        const { fileList_basic,fileList_abstract,fileList_check,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=="abstract"){
            fileList_abstract.splice(index,1);
            this.setData({
                fileList_abstract:fileList_abstract
            })
        }else if(name=="check"){
            fileList_check.splice(index,1);
            this.setData({
                fileList_check:fileList_check
            })
        }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 = FileUtil.UUID()+'.'+imgUrl.match(/\.(\w+)$/)[1];

              //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) {
                        resolve(true)
                        let url = host + '/' + dir + filename;
                        // 上传完成需要更新 fileList
                        console.log('11111111111111');
                        console.log(url);
                        if(name=='basic'){
                            const { fileList_basic} = THIS.data;
                            fileList_basic.push({ url: url });
                            THIS.setData({ fileList_basic });
                        }else if(name=='abstract'){
                            const { fileList_abstract} = THIS.data;
                            fileList_abstract.push({ url: url });
                            THIS.setData({ fileList_abstract });
                        }else if(name=='check'){
                            const { fileList_check} = THIS.data;
                            fileList_check.push({ url: url });
                            THIS.setData({ fileList_check});
                        }else if(name.indexOf("record")!=-1){
                            let recordIndex=Number(name.split("record")[1]);
                            let obj="dpmas_list[" +recordIndex +"].fileList"
                            THIS.setData({
                               [obj]:THIS.data.dpmas_list[recordIndex].fileList.concat([{ url: url }])
                            })
                        }
                       
                      }else{
                        reject(false)
                      }
                    },
                    fail: err => {
                      console.log(err);
                    }
                  });
              })
            

        })
     
      },
      afterRead(event) {
       
        console.log( event.detail)
        const { file,name} = event.detail;
        console.log(file)
        wx.showLoading({
            title: '图片上传中',
            mask: true
          })
        var promiseFun = [];
        for (let i = 0; i < file.length; i++) {
          var cur_file = file[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();
        });
       
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        // wx.uploadFile({
        //   url: 'https://example.weixin.qq.com/upload', // 仅为示例，非真实的接口地址
        //   filePath: file.url,
        //   name: 'file',
        //   formData: { user: 'test' },
        //   success(res) {
        //     // 上传完成需要更新 fileList
        //     const { fileList = [] } = this.data;
        //     fileList.push({ ...file, url: res.data });
        //     this.setData({ fileList });
        //   },
        // });
      },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      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
              })
          }
      }
    },

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

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

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

    },

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

    },

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

    },

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

    },

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

    // }
})