// index.js
 const app = getApp()
 import {caseList,getExpertSign,getProjectStatus,getBankInfo,getfangxinSite,limitCount,getDeal} from "../../api/api"
import {throttle} from "../../utils/util"
import {createStoreBindings} from "mobx-miniprogram-bindings"
import {store} from '../../store/store.js'
Page({
  data: {
    showDelDraft:false,
    authMessage:'',
    showAuth:false,
    editId:'',
    showDraft:true,
    reason:'',
    isLogin:false,
    status_title:'病例状态',
    casetype_title:'治疗类型',
    draftTime:'',
    caseDraft:{},
    hasDraft:false,
    showEntryTip:false,
    showEntryTip_second:false,
    statusList: [
      { text: '待提交', value: -1,select:false },
      { text: '待审核', value: 0,select:false },
      { text: '待修改', value: 2,select:false },
      { text: '已通过', value: 1,select:false },
    ],
    typeList:[{
        text:'DPMAS及联合模式',
        value:1,
        select:false,
    },{
        text:'CA280及联合模式',
        value:2,
        select:false,
    }],
    select_status:false,
    select_type:false,
    lock:false,
    showCheck:false,
    showAgree:false,
    isTriggered:false,
    list:[],
    showCancel:true,
    caseType:'',
    status:'',
    sortItemList:[{
        column:0,
        isAsc:true
    }],
    name:'',
    pageNum:1,
    pageSize:10,
    img_host:app.hostConfig().imghost
  },
  handleGetDeal(){
    getDeal().then(res=>{   
        this.setData({
            authMessage:res,
            showAuth:true
        })
    })
},
  getAuthStatus(){
    getProjectStatus().then(res=>{
        getBankInfo().then(result=>{
            if(result){
                getExpertSign().then(response=>{
                    if(response.taskStatus==2){
                        this.handleGetDeal()
                    }
                })
            }else{
                this.handleGetDeal()
            }
        }) 
    })
  },
  handleGetProjectStatus(){
    getProjectStatus().then(res=>{
        limitCount({
            type:4
        }).then(result=>{            
            if(result<20){
                this.handleGetSign() 
            }else{
                wx.showToast({
                  title: '每人参与病例征集不得超过20例',
                  icon:'none'
                })
            }
            
        })
    }).catch((error)=>{
        if(error.code==30007){
            wx.showToast({
                title: '您未登录',
                icon:'none',
                duration:4000
              })
            app.method.navigateTo({
              url: '/case/pages/mobileLogin/mobileLogin',
            })
         }
    })
},
 onConfirmAuth(){
    this.setData({
        showAuth:false
    });
    app.method.navigateTo({
        url: '/case/pages/bankCard/bankCard',
      })    
  },
  onCancleAuth(){
    this.setData({
        showAuth:false
    });
  },
  onConfirmDelDraft(){
    wx.setStorageSync('caseDraft', '');
    this.setData({
        showDelDraft:false,
        hasDraft:false,
        showDraft:false
    });
  },
  onCancelDelDraft(){
    this.setData({
        showDelDraft:false,
    })
  },
  onCloseSwipe(event){
    const { position, instance } = event.detail;
    switch (position) {
      case 'left':
      case 'cell':
        instance.close();
        break;
      case 'right':
       this.setData({
           showDelDraft:true
       })
        break;
    }
  },
  goDetail:throttle(function(event){
      let {id,status,reason}=event.currentTarget.dataset;
      if(status==2){
         this.setData({
            reason,
            editId:id,
            showCheck:true
         })
      }else{
        app.method.navigateTo({
            url: '/case/pages/createCase/createCase?medicalRecordId='+id+"&status="+status,
          })
      }
    
  }),
  goCreate:throttle(function(){
    this.handleGetProjectStatus();
  
    // app.method.navigateTo({
    //     url: '/case/pages/createCase/createCase',
    //   })
   
  }),
  goAgreement:throttle(function(event){
    app.method.navigateTo({
      url:"/case/pages/privacy/privacy"
    })
  }),
  getSite(){
    getfangxinSite().then(res=>{
        app.method.navigateTo({
            url:'/case/pages/webSign/webSign?src='+encodeURIComponent(res.linkUrl)
        })
    })
},
getBank(){
    getBankInfo().then(res=>{
     if(!res){
        this.handleGetDeal();
    //     this.setData({
    //         showAgree:true
    //   })
        //  wx.showToast({
        //    title: '请先绑定信息',
        //    icon:"none",
        //    duration:3000
           
        //  })
        //  app.method.navigateTo({
        //   url: '/case/pages/bankCard/bankCard',
        // })    
     }else{
           this.setData({
                showAgree:true
          })
     }
    
 })
},
  handleGetSign(){
    getExpertSign().then(res=>{
        if(res && res.taskStatus==1){
            app.method.navigateTo({
                url: '/case/pages/createCase/createCase',
              })
        }else{
            // this.setData({
            //     showAuth:true
            // })
            this.getBank();
        }  
    }).catch(error=>{
      
         if(error.code==30007){
            wx.showToast({
                title: '您未登录',
                icon:'none',
                duration:4000
              })
            app.method.navigateTo({
              url: '/case/pages/mobileLogin/mobileLogin',
            })
         }
    })
  },
  handleCaseList(){
      let { caseType,pageNum,pageSize,searchCount,status,name}=this.data;

    caseList({
        caseType,
        pageNum,
        name,
        pageSize,
        searchCount,
        status
    }).then(res=>{
        if(status==='' && caseType===''){
            this.toggleDraft();
        };
        this.setData({
              isTriggered:false
          })
        // if(pageNum==1){
        //    this.setData({
        //        isTriggered:false
        //    })
        // }
         if(res.list.length==0){
             this.setData({
                lock:true
             });
             return;
         };
         this.setData({
             list:this.data.list.concat(res.list)
         })
       
    }).catch(error=>{
        this.setData({
            isTriggered:false
        })
    })
  },
  onConfirm(){
      let id=this.data.editId;
    this.setData({
        showCheck:false
    })
    app.method.navigateTo({
        url: '/case/pages/createCase/createCase?medicalRecordId='+id+"&status=2",
      })
  },
  onCancel(){
    this.setData({
        showCheck:false
    })
  },
  onConfirmAgree(){
    this.setData({
        showAgree:false
    });
    //this.getSite();
    app.method.navigateTo({
        url:'/case/pages/bankCard/bankCard'
    })
  },
  onCancelAgree(){
    this.setData({
        showAgree:false
    })
  },
  goSearch(value){
    this.setData({
        lock:false,
        pageNum:1,
        name:value.detail,
        list:[]
      });
      this.handleCaseList()
  },
  handleRefresher(){
     let {status}=this.data;
     if(status!=-1){
        this.setData({
            lock:false,
            pageNum:1,
            list:[]
          });
          this.handleCaseList()
     }else{
         this.setData({
            isTriggered:false
         })
     }
    
   },
   lower(e) {
      
    let {lock}=this.data;
    let addPage=this.data.pageNum+1;
    if(!lock){
      this.setData({
        pageNum:addPage
      });
      this.handleCaseList();
    }  
  },
  chooseStatus(e){
    let {hasDraft,statusList,typeList}=this.data;
      let {id,value,name,select,index}=e.currentTarget.dataset;
      this.selectComponent('#'+id).toggle(false);
    
      if(id=="item1"){
        statusList.forEach((item,key)=>{
            let cur_obj='statusList['+key+'].select'
            this.setData({
                [cur_obj]:false
            })
        })
        let obj='statusList['+index+'].select';
         this.setData({
            status:!select?value:'',
            status_title:!select?name:'病例状态',
            [obj]:!select,   
         })
        if(value==-1 && this.data.statusList[0].select){
            this.setData({
                showDraft:hasDraft?true:false,
                list:[]
            })
        }else if(value==-1 && !this.data.statusList[0].select){
           
            this.handleRefresher();
         }else{
            this.setData({
                showDraft:false
            })
          this.handleRefresher();
           
        }
        let hasSelect=this.data.statusList.some(item=> item.select==true );
        if(hasSelect){
            this.setData({
                select_status:true
            })
        }else{
            this.setData({
                select_status:false
            })
        }

      }else{
        typeList.forEach((item,i)=>{
            let cur_obj='typeList['+i+'].select'
            this.setData({
                [cur_obj]:false
            })
        })
        let obj='typeList['+index+'].select';
        this.setData({
            caseType:!select?value:'',
            [obj]:!select,
            casetype_title:!select?name:'病例类型'
         })
         if(this.data.status==-1 && this.data.statusList[0].select){
           
            this.setData({
                showDraft:hasDraft?true:false,
                list:[]
            })
         }else if(this.data.status==-1 && !this.data.statusList[0].select){
            this.handleRefresher();
         }else{
            this.setData({
                showDraft:false
            })
            this.handleRefresher();
         }
         let hasSelect=this.data.typeList.some(item=> item.select==true );
         if(hasSelect){
             this.setData({
                select_type:true
             })
         }else{
            this.setData({
                select_type:false
             })  
         }
        console.log(this.data.typeList);
      }
      
    
  },
  onConfirmEntry(){
    this.setData({
      showEntryTip:false
    })
  },
  onCloseEntry(){
    this.setData({
       showEntryTip:true,
      showEntryTip_second:true
    })
  },
  onConfirmEntry_second(){
    this.setData({
      showEntryTip_second:false,
    });
    //wx.setStorageSync('hasEntry', true);
   
  },
  onCloseEntry_second(){
     wx.exitMiniProgram({success: (res) => {}})
     this.setData({
      showEntryTip_second:false,
      showEntryTip:false,
    });
    
   },
   toggleDraft(){
    let caseDraft=wx.getStorageSync('caseDraft');
    let draftTime=wx.getStorageSync('draftTime')
    if(caseDraft){
        this.setData({
            caseDraft:JSON.parse(caseDraft),
            hasDraft:true,
            showDraft:true,
            draftTime:draftTime
        })
    }else{
        this.setData({
            showDraft:false,
            hasDraft:false
        })
    }
   },
   isHasToken(){
    let tokenStr=''
    const { envVersion } = wx.getAccountInfoSync().miniProgram;
    if(envVersion=="develop" || envVersion=="trial"){
      tokenStr="DEV_CASE_TOKEN"
    }else{
      tokenStr="PROD_CASE_TOKEN"
    }
    let token = wx.getStorageSync(tokenStr);
    if(token){
        this.setData({
            isLogin:true
        })
        return true
    }else {
        this.setData({
            isLogin:false
        })
        return false
    }
   },
  onLoad(){
    this.storeBindings = createStoreBindings(this, {
        store,
        fields: [,"active"],
        actions: ["updateActive"],
      });
      this.isHasToken()
      this.getAuthStatus();
     
  },
  onUnload() {
    this.storeBindings.destroyStoreBindings();
   
},
  onShow(){
   
    this.updateActive('list');
    let nav=this.selectComponent('#nav');
    nav.clearKeyWord();
    this.setData({
        name:'',
        select_status:false,
        select_type:false,
        status_title:'病例状态',
        casetype_title:'病例类型',
        status:'',
        caseType:''
    })
    if(this.isHasToken()){
        this.toggleDraft();
        this.handleRefresher();
      }
    
    
    wx.getPrivacySetting({
        success: res => {
          console.log(res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
          if (res.needAuthorization) {
            // 需要弹出隐私协议
            this.setData({
              showEntryTip:true
            });
          } else {
            this.setData({
              showEntryTip:false
            })
            // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用已声明过的隐私
          }
        },
        fail: () => {},
        complete: () => {}
      })
  }
});
