// case/pages/register/register.js
import {throttle} from "../../../utils/util"
import {hostConfig} from "../../../utils/config"
import {getArea,getHospital,getOfficeList,getPosition,smsRegister,sendSms,getCaptcha} from "../../../api/api"
import {base64src} from "../../../utils/base64ToImg"
const host=hostConfig().host;
const app=getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        showImprove:false,
        showSuccess:false,
        img_host:app.hostConfig().imghost,
        showArea:false,
        areaColumns:[
            {
                values: [1,2],
                className: 'column1',
            },
            {
                values: [3,4],
                className: 'column2',
                defaultIndex: 0
            },
            {
                values: [3,4],
                className: 'column3',
                defaultIndex: 0
            }
            ],
            hospitalColumns:[],
            officeColumns:[],
            positionColumns:[],
            showHospital:false,
            showOffice:false,
            showPosition:false,
        showNext:false,
        fileList:[],
        disabled:false,
        county_id:'',
        hospital_name:'',
        hospital_uuid:'',
        mobile:'',//17601211874
        name:'',
        office_name:'',
        office_uuid:'',
        password:'',
        position_uuid:'',
        certificate:'',
        certificate_img:'',
        codeActive:true,
        msg:'获取验证码',
        captchaUuid:'',
        captchaCode:'',
        loginDevice:5,
        imgCode:'',
        sms:'',
        timer:null,
        time:59,
        smsType:1,
        showCrop:false,
        width: 250, //宽度
        height: 250, //高度
        max_width: 300,
        max_height: 300,
        disable_rotate: true, //是否禁用旋转
        disable_ratio: false, //锁定比例
        limit_move: true, //是否限制移动
    },
    closeCrop(){
        this.setData({
          showCrop:false
        })
      },
      submit() {
        this.setData({
          showCrop:false
        })
        this.cropper.getImg((obj) => {
          this.uploadImg(obj)
        });
    },
    cropperload(e) {
      console.log('cropper加载完成');
    },
      initCrop(options){
      
        this.cropper = this.selectComponent("#image-cropper");
    
        
    
        if(options.imgSrc){
          this.setData({
            src: options.imgSrc
        });
        }
       
        // if(!options.imgSrc){
        //     this.cropper.upload(); //上传图片
        // }
      },
      loadimage(e) {
        this.cropper.imgReset();
    },
    onConfirmSuccess(){
        this.setData({
            showSuccess:false
        })
        app.method.navigateTo({
            url:"/case/pages/mobileLogin/mobileLogin"
          })
    },
    opeArea(){
        this.setData({
           showArea:true
        })
    },
    openOffice(){
      this.setData({
          showOffice:true,
      })
    },
    openPosition(){
        this.setData({
            showPosition:true,
        })
      },
    onChange(e){
        const {value} = e.detail;

        const {id}=e.currentTarget.dataset;
        // console.log(value,id)
        this.setData({
            [id]: value
        });
    },
    onChangeArea(event){
        const { picker, value, index } = event.detail;
        if(index==0){
            const provinceId=value[0].id;
            this.handleGetArea(provinceId,2)
        }else if(index==1){
            let cityId=value[1].id
            this.handleGetArea(cityId,3)
        }
       
    },
    confirmArea(event){
        const {value} = event.detail;
        let countyId='';
       if(value[2]){
        countyId=value[2].id
       }else{
        countyId=value[1].id 
       }
       
        this.setData({
            county_id:countyId,
            showArea:false
        });
        this.handleGetHospital(countyId)
    },
    cancelArea(){
        this.setData({
            showArea:false
        })
    },
    confirmHospital(event){
        let {value}=event.detail;
        this.setData({
            showHospital:false,
            hospital_uuid:value.uuid,
            hospital_name:value.name
        })
    },
    cancelHospital(){
        this.setData({
            showHospital:false
        })
    },
    confirmOffice(event){
        let {value}=event.detail;

        this.setData({
            office_name:value.officeName,
            office_uuid:value.officeUuid,
            showOffice:false
        })
    },
    cancelOffice(){
        this.setData({
            showOffice:false
        })
    },
    confirmPosition(event){
        let {value}=event.detail;
        this.setData({
            position_uuid:value.uuid,
            position_name:value.name,
            showPosition:false
        })
    },
    cancelPosition(){
        this.setData({
            showPosition:false
        })
    },
    goNext(){
        let {mobile,sms,password,captchaCode}=this.data;
        if(!/^1[3456789]\d{9}$/.test(mobile)){
           wx.showToast({
             title: `请输入有效的手机号码！`,
             icon: 'none',
           });
           return false;    
         };
         if(!captchaCode){
           wx.showToast({
               title: `请输入图形验证码`,
               icon: 'none',
             });
             return false;     
         }
         if(!sms){
           wx.showToast({
               title: `请输入短信验证码`,
               icon: 'none',
             });
             return false;     
         }
         if(!(/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/.test(password))){
           wx.showToast({
               title: `请输入6-16位字母、数字组合密码！`,
               icon: 'none',
             });
             return false;     
         }
        this.setData({
            showNext:true
        })
    },
    showNext(){
        this.setData({
            showNext:false
        })
    },
    handleGetArea(id,type){
       getArea({
           parent:id
       }).then(res=>{
           if(type==1){
                let obj='areaColumns[0].values';
                this.setData({
                    [obj]:res
                }) 
                this.handleGetArea(res[0].id,2)
           }else if(type==2){
            let obj='areaColumns[1].values';
                this.setData({
                    [obj]:res
                })
                this.handleGetArea(res[0].id,3)
           }else if(type==3){
            let obj='areaColumns[2].values';
            this.setData({
                [obj]:res
            })   
           }
           
         
       }).catch(error=>{
           console.log(error)
       })
    },
     handleGetHospital(countyId){
        getHospital(countyId).then(res=>{
           this.setData({
               showHospital:true,
              hospitalColumns:res.concat({uuid:1,name:'其他医院'})
           })
        })
     },
     handleGetOffice(){
        getOfficeList({}).then(res=>{
            this.setData({
                officeColumns:res
            })
        }).catch(error=>{
            console.log(error)
        })
     },
     handleGetPosition(){
        getPosition().then(res=>{
            this.setData({
                positionColumns:res
            })
        })
     },
     handleSmsRegister:throttle(function(){
         let {mobile,name,sms,password,captchaCode,hospital_uuid,hospital_name,office_name,office_uuid,position_uuid,certificate,certificate_img,county_id}=this.data;
         if(!/^1[3456789]\d{9}$/.test(mobile)){
            wx.showToast({
              title: `请输入有效的手机号码！`,
              icon: 'none',
            });
            return false;    
          };
          if(!captchaCode){
            wx.showToast({
                title: `请输入图形验证码`,
                icon: 'none',
              });
              return false;     
          }
          if(!sms){
            wx.showToast({
                title: `请输入短信验证码`,
                icon: 'none',
              });
              return false;     
          }
          if(!(/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/.test(password))){
            wx.showToast({
                title: `请输入6-16位字母、数字组合密码！`,
                icon: 'none',
              });
              return false;     
          }
          if(!(/^[\u4E00-\u9FA5·]{2,20}$/.test(name))){
            wx.showToast({
                title: `请输入您的真实姓名`,
                icon: 'none',
              });
              return false;     
          }
          if(!hospital_uuid){
            wx.showToast({
                title: `请选择医院`,
                icon: 'none',
              });
              return false;     
          }
          if(!office_uuid){
            wx.showToast({
                title: `请选择科室`,
                icon: 'none',
              });
              return false;     
          }
          if(!position_uuid){
            wx.showToast({
                title: `请选择职称`,
                icon: 'none',
              });
              return false;     
          }
          if(!certificate_img){
            wx.showToast({
                title: `请上传执业医师资格证或工作胸牌`,
                icon: 'none',
              });
              return false;     
          }
        smsRegister({
            mobile,
            name,
            sms,
            password,
            hospital_uuid,
            hospital_name,
            office_name,
            office_uuid,
            county_id,
            position_uuid,
            certificate,
            certificate_img
        }).then(res=>{
            this.setData({
                showSuccess:true,
            })
       
         
        })
     }),
    handleThrottle:throttle(function(){
        this.getCode()
      }),
      handleGetCaptcha(){
        getCaptcha().then(res=>{
            base64src(res.captchaBase64Image,(img)=>{
              this.setData({
                imgCode:img,
                captchaUuid:res.captchaUuid
              })
            })
        })
      },
     getCode(){
      if(this.data.disabled)return;
      let {mobile,captchaCode,captchaUuid,loginDevice,smsType}=this.data;
      if(!/^1[3456789]\d{9}$/.test(mobile)){
        wx.showToast({
          title: `请输入有效的手机号码！`,
          icon: 'none',
        });
        return false;    
      };
      if(!captchaCode){
        wx.showToast({
            title: `图形验证码不能为空`,
            icon: 'none',
          });
          return false;   
      }
      sendSms({
        mobile,
        captchaCode,
        captchaUuid,
        smsType,
        loginDevice
      }).then((res)=>{
        let timer=setInterval(() => {
          if (this.data.time == 0) {   
            clearInterval(this.data.timer);
            this.setData({
              time:59,
              msg:'重新获取验证码',
              disabled:false,
              codeActive:true,
            })
          } else {
            let msg= this.data.time + " s 后重新发送";
            this.setData({
              disabled:true,
              msg:msg,
              codeActive:false,
            })
            let time=this.data.time--;
            this.setData({
             msg:time + " s 后重新发送"
            })
          }
        }, 1000);
    
        this.setData({
          timer:timer
        })
      }).catch(()=>{
          this.handleGetCaptcha();
      });
      
    },
    uploadImg(file){
        let THIS=this;
        wx.showLoading({
            title: '图片上传中',
            mask: true
          })
       
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        wx.uploadFile({
          url: host+'/user/uoloadImg', // 仅为示例，非真实的接口地址
          filePath: file.url,
          name: 'file',
          formData: file,
          success(res) {
            let result=JSON.parse(res.data);
            wx.hideLoading();
            if(result.code==200){
                THIS.setData({ 
                    certificate_img:result.data
                 });
            }else{
                wx.showToast({
                  title:result.msg,
                  icon:'none'
                })
            }
            
          },
          complete(res){
            console.log(res)
          }
        });
    },
    afterRead(event) {
        const {
            file
          } = event.detail;
        this.setData({
            src:file.url
          },()=>{
            this.setData({
                showCrop:true,
              })
          })
     
      },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.handleGetCaptcha();
        this.handleGetArea('',1);
        this.handleGetOffice();
        this.handleGetPosition();
        this.initCrop(options);
    },

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

    },

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

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

    },

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

    },

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

    },

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

    },

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

    // }
})