// case/pages/improveInfo/improveInfo.js
// case/pages/register/register.js
import {throttle} from "../../../utils/util"
import {hostConfig} from "../../../utils/config"
import {getArea,addBank,getExpertSign,getBankInfo,getfangxinSite,ocrIdCard} from "../../../api/api"
const host=hostConfig().host;
const app=getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        isCanEdit:true,
        isFirst:true,
        taskStatus:2, //2未签署 1已签署
        signUrl:'',
        showSuccess:false,
        img_host:app.hostConfig().imghost,
        showArea:false,
        cityName:'',
        areaColumns:[
            {
                values: [1,2],
                className: 'column1',
            },
            {
                values: [3,4],
                className: 'column2',
                defaultIndex: 0
            },
            {
                values: [3,4],
                className: 'column3',
                defaultIndex: 0
            },
            ],
            showArea:false,
        bankCardNo:'',
        bankName:'',
        cityId:'',
        countyId:'',
        provId:'',
        idCardName:'',
        idCardNo:'',
        signImg:'',
    },
    seeIdCard(frontFile){
        ocrIdCard({
            frontBase64:frontFile
        }).then(res=>{
            wx.hideLoading()
        if(res.idCardNo){
            this.setData({
                idCardNo:res.idCardNo
            })
        }
        })
    },
    afterRead(event){
      
        const { file } = event.detail;
        wx.getFileSystemManager().readFile({
                 filePath:file.url,
				encoding:'base64',
			   success:res=>{
                   wx.showLoading({
                    title: '正在识别中...',
                    mask: true
                  })
                this.seeIdCard(res.data)
               }
        })
    },
    getBank(){
        getBankInfo().then(res=>{
             let hasBank=false; 
            if(res){         
                this.setData({
                   isCanEdit:false 
                })
                //this.handleGetArea(res.provId,2);
                hasBank=true;
                for (const key in res) {
                       this.setData({
                           [key]:res[key]
                       })                 
                }
                let {provId,cityId}=this.data; 
                 if(provId){
                    wx.showLoading({
                        title: '加载中',
                        mask: true
                      })
                    this.handleGetArea('',1,false);
                    this.handleGetArea(provId,2,false);
                    this.handleGetArea(cityId,3,false);         
              };
            }else{
                this.handleGetArea('',1)
            }
            this.handleGetSign(hasBank);
        })
    },
    
    getSite:throttle(function(){
        wx.showLoading({
            title: '加载中',
            mask: true
          })
        getfangxinSite().then(res=>{
           
            app.method.navigateTo({
                url:'/case/pages/webSign/webSign?src='+encodeURIComponent(res.linkUrl),
                success(){
                    wx.hideLoading()
                }
            })
        })
    }),
    goSignSite:throttle(function(){
        let {signUrl}=this.data;
        app.method.navigateTo({
            url:'/case/pages/webSign/webSign?src='+encodeURIComponent(signUrl)
        })
    }),
    handleGetSign(hasBank){
        getExpertSign().then(res=>{
            //有银行卡，已签署
            if(hasBank && res.taskStatus==1){
                  this.setData({
                      taskStatus:1,
                      signUrl:res.taskFileUrl
                  })
            }
             //有银行卡，未签署
            if(hasBank && res.taskStatus==2){
                this.setData({
                    taskStatus:2
                })
                //跳转签署地址
                //this.getSite();
                
            }
            //无银行卡，未签署
            if(!hasBank && res.taskStatus==2){
                //跳转签署地址
                
            }
        }).catch(error=>{
             if(error.code==30007){
                wx.showToast({
                    title: '您未登录',
                    icon:'none',
                    duration:4000
                  })
                app.method.navigateTo({
                  url: '/case/pages/mobileLogin/mobileLogin',
                })
             }
        })
      },
    opeArea(){
        if(!this.data.isCanEdit) return false;
        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;
        this.setData({
            [id]: value
        });
    },
    onChangeArea(event){
        const { picker, value, index } = event.detail;
        const provinceId=value[0].id;
        const cityId=value[1].id;
        if(index==0){
            this.handleGetArea(provinceId,2);
        }else if(index==1){
            this.handleGetArea(cityId,3)
        }
    },
    confirmArea(event){
        const {value} = event.detail;
        let provId=value[0].id;
        let cityId=value[1].id;
         let countyId=value[2]?value[2].id:value[1].id;
         let cityName='';
         for (let i = 0; i <value.length; i++) {
             if(value[i]){
                cityName+=value[i].name   
             };
           
         };
        this.setData({
            provId:provId,
            cityId:cityId,
            countyId:countyId,
            cityName:cityName,
            showArea:false
        });
       
    },
    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
        })
    },
 
   
   
   
    handleAddBank:throttle(function(){
        if(!this.data.isCanEdit){
            wx.showToast({
                title: `当前状态不可提交`,
                icon: 'none',
              });
            return false
        };
        let {signImg,bankCardNo,bankName,cityId,countyId,idCardNo,idCardName,provId}=this.data;
        if (!/^([\u4e00-\u9fa5\·]{2,30})$/.test(idCardName)) {
            wx.showToast({
              title: `姓名要求在2-30个汉字`,
              icon: 'none',
            });
            return false;
          };
          if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(idCardNo)){
            wx.showToast({
              title: `请输入有效的身份证号`,
              icon: 'none',
            });
            return false;
          };
          if(!provId){
            wx.showToast({
                title: `请选择开户行所在城市`,
                icon: 'none',
              });
              return false;
          }
          if(!bankName){
            wx.showToast({
                title: `请输入开户行`,
                icon: 'none',
              });
              return false;
          }
          if(!this.luhnCheck(bankCardNo)){
            wx.showToast({
                title: `请输入有效银行卡号`,
                icon: 'none',
              });
              return false;
          };
        //   if(!signImg){
        //     wx.showToast({
        //         title: `请添加签名`,
        //         icon: 'none',
        //       });
        //       return false;
        //   }
        addBank({
            bankCardNo,
            bankName,
            cityId,
            countyId,
            idCardNo,
            idCardName,
            provId
        }).then(res=>{
            let that=this;
            wx.showToast({
              title: '绑定成功',
              icon:'none',
              duration:2000,
              success:function(){
                that.getBank();
                // let timer=setTimeout(()=>{
                //     wx.switchTab({
                //         url: '/pages/index/index',
                //       })
                //     clearTimeout(timer)
                //  },1000)
              }
            })
        })
     }),
     luhnCheck(cardNumber) {  
        var sum = 0;  
        var shouldDouble = false;  
        var digit;  
      
        // 去除任何非数字字符  
        cardNumber = cardNumber.replace(/\D/g, '');  
      
        // 从右向左遍历数字  
        for (var i = cardNumber.length - 1; i >= 0; i--) {  
            digit = parseInt(cardNumber.charAt(i), 10);  
      
            if (shouldDouble) {  
                if ((digit *= 2) > 9) digit -= 9;  
            }  
      
            sum += digit;  
            shouldDouble = !shouldDouble;  
        }  
      
        // 如果校验和能被10整除，则卡号有效  
        return (sum % 10) === 0;  
    },
    goSign:throttle(function(){
        app.method.navigateTo({
            url:'/case/pages/signcanvas/signcanvas'
        })
    }),
    async handleGetArea(id,type,flag=true){
        let isFlag=flag
      const res=await getArea({
           parent:id
       });
       if(type==1){
        let obj='areaColumns[0].values';
        this.setData({
            [obj]:res,  
        }) 
        if(isFlag){
           
            this.handleGetArea(res[0].id,2,isFlag)
        }    
       }else if(type==2){
        let obj='areaColumns[1].values';
        this.setData({
            [obj]:res
        })
        if(isFlag){
            this.handleGetArea(res[0].id,3,isFlag)
        }
        
       }else{
        let obj='areaColumns[2].values';
        this.setData({
            [obj]:res,
          })
        let areaName='';
       if(!isFlag){
        let {provId,cityId,countyId,areaColumns}=this.data;
         setTimeout(()=>{
            if(provId){
                for (let i = 0; i < areaColumns[0].values.length; i++) {
                   if(areaColumns[0].values[i].id==provId){
                    areaName+=areaColumns[0].values[i].name;
                    break;
                }
             }
          };
          if(cityId){
            for (let i = 0; i < areaColumns[1].values.length; i++) {
               if(areaColumns[1].values[i].id==cityId){
                areaName+=areaColumns[1].values[i].name;
                break;
            }
         }
      };
          if(countyId){
            for (let i = 0; i < areaColumns[2].values.length; i++) {
               if(areaColumns[2].values[i].id==countyId){
                areaName+=areaColumns[2].values[i].name;
                break;
            }
         }
      };
        this.setData({
            cityName:areaName
        })
        wx.hideLoading()
         },600)
       }
       }
     
      
      
    },
     handleGetOffice(){
        getOfficeList({}).then(res=>{
            this.setData({
                officeColumns:res
            })
        }).catch(error=>{
            console.log(error)
        })
     },
     handleGetPosition(){
        getPosition().then(res=>{
            this.setData({
                positionColumns:res
            })
            this.handleNeedInfo();
        })
     },
    
   
  
   
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
       
        //this.handleGetArea('',1); 
        
    },

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

    },

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

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

    },

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

    },

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

    },

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

    },

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

    // }
})