var util = require('../../../utils/util.js');
var api = require('../../../api/api.js');
var check = require('../../../utils/check.js');

var app = getApp();

Page({
  data: {
    hasLogin:true,
    workerNo:'',
    isExist:false,//服务者是否存在
    showOcr:false,
    workerTel:'',
    certificateFileUrl:[],
    headPic:'',
    worker: {
      healthCertificate:'',//0未上传 1已上传 2健康证即将到期 3健康证到期
      // workerTel: '',
      // workerIdcard: '',
      // workerName: '',
      // famousRace: '',
      // idcardAddr: '',
      // birthday: '',
      // workType: '',
      // contactAddr: "",
      // validStartDate: "",
      // validEndDate: "",
      // healthCert: '',
      // healthStart: '',
      // healthEnd: '',
      // experience: '',
      // education: '',
      // emergencyContact: "",
      // emergencyPhone: '',
      // city: ''
    },
    applyType: '请选择',
    showExperience: false,
    showEducation: false, //显示学历
    showServiceItem: false, //显示技能项目
    showHealthStart: false, //健康证起始日期
    showIssuanceDate:false,//健康证发证日期
		showHealthEnd: false, //健康证起始日期
		showHukou:false,//户口选择
		showShebao:false,//社保
    showCity: false,
    experience: ['无', '1-3年', '3-5年', '5年以上'],
    education: ['小学', '初中', '高中', '专科', '本科'],
    serviceItem: ['日常保洁', '做饭家厨', '精细擦窗', '空调除尘', '浴室清洁', '厨房清洁', '除尘除螨', '油烟燃气', '洗衣冰箱', '洗衣空调'],
    citys: ['上海', '北京', '深圳', '南京', '苏州', '杭州', '武汉'],
		minDate: new Date().setTime((new Date()).getTime() - 3600 * 1000 * 24 * 365),
		residenceTypeList:[{key:'1',value:'农村'},{key:'2',value:'城镇'}],
		socialSecurityList:[{key:'1',value:'社保'},{key:'2',value:'新农保'},{key:'3',value:'已退休'},{key:'4',value:'无'}],
    idFront: '', //身份证正反面
    idBack: '',
    showSubmit: true //是否显示提交按钮
  },
  goValid() {
    if (this.data.workerTel == '' || !check.isValidPhone(this.data.workerTel)) {
      wx.showToast({
        title: '请输入个人手机号',
        icon:none
      });
      return false;
    }
    this.getWorkerInfo({
      phone: this.data.workerTel
    });

  },
  getWorkerInfo(params){
    util.request(api.ServantValid, params, 'GET').then(res=> {
      wx.hideLoading();
      console.log(res);
      if (res.errno === 0) {
        // wx.showToast({
        //   title: '已存在，待完善',
        //   icon: 'success',
        //   duration: 2000
        // });
        this.setData({
          isExist:true,
          worker:res.data,
          showOcr:res.data.orcFlag,//是否需要做ocr,
          certificateFileUrl:res.data.certificateFileUrl==''?[]:res.data.certificateFileUrl.split(','),
          headPic:res.data.headPic,
          idFront:res.data.idcardFront,
          idBack:res.data.idcardBack
				});
				this.setData({
					'worker.certificateFileUrl':res.data.certificateFileUrl==''?[]:res.data.certificateFileUrl.split(',')
				});
        this.setData({
          workerNo:res.data.workerNo
				});
				let hukou=''; 
				this.data.residenceTypeList.forEach(e=>{ 
					if(res.data.residenceType!=''&&res.data.residenceType==e.key){
						hukou=e.value;
					}
				})
				let shebao=''; 
				this.data.socialSecurityList.forEach(e=>{ 
					if(res.data.socialSecurity!=''&&res.data.socialSecurity==e.key){
						shebao=e.value;
					}
				}) 
				this.setData({ 
					'worker.residenceTypeName': hukou,
					'worker.socialSecurityName': shebao  
				}); 
        if(this.data.worker.idcardStartdate){
          this.setData({
            'worker.break': '至',
          });
        }

        if(!this.data.showOcr){
          this.setData({
           idFront:res.data.idcardFront,
           idBack:res.data.idcardBack
          });
        }
      } else {
        this.setData({
          isExist:false
        });
        wx.showModal({
          title: '提示',
          content: res.errmsg,
          showCancel:false,
          success (res) {
            if (res.confirm) {

            }
          }
        });


      }
    });
  },
  submitFeedback: function (e) {
    let that = this;
    let worker = that.data.worker;

    console.info(worker)
    if (worker.workerIdcard == '' || worker.workerIdcard.length != 18) {
      // util.showErrorToast('请上传身份证并识别');
      wx.showToast({
        title: '请上传身份证并识别',
        icon:'none',
        duration: 3000
      });
      return false;
    }
    // if (worker.workerTel == '' || !check.isValidPhone(worker.workerTel)) {
    //   util.showErrorToast('请输入个人手机号');
    //   return false;
    // }
    // if (worker.workerType == '') {
    //   util.showErrorToast('请选择工作类型');
    //   return false;
    // }
    // if (worker.experience == '') {
    //   util.showErrorToast('请选择工作经验');
    //   return false;
    // }
    // if (worker.city == '') {
    //   util.showErrorToast('请选择工作城市');
    //   return false;
    // }

    // if (worker.education == '') {
    //   util.showErrorToast('请选择学历');
    //   return false;
    // }
    // if (worker.contactAddr == '') {
    //   util.showErrorToast('请输入联系地址');
    //   return false;
    // }

    // if (worker.emergencyContact == '' || worker.emergencyPhone == '' || !check.isValidPhone(worker.emergencyPhone)) {
    //   util.showErrorToast('请填写紧急联系人');
    //   return false;
    // }
    if (worker.certificateFileUrl == [] || worker.certificateNo == '' || worker.issuanceDate == ''||worker.expirationDateStart == ''|| worker.expirationDateEnd == '') {
      // util.showErrorToast('请填写健康证信息');
      wx.showToast({
        title: '请填写健康证信息',
        icon:'none',
        duration: 3000
      });
      return false;
    }

    if (worker.expirationDateEnd <= worker.expirationDateStart) {
      // util.showErrorToast('请选择正确健康证有效期');
      wx.showToast({
        title: '请选择正确健康证有效期',
        icon:'none',
        duration: 3000
      });
      return false;
    }

    wx.showModal({
      title: '提醒',
      content: '请核对填写信息，提交后无法更改，确定提交？',
      success: function (res) {
        wx.showLoading({
          title: '提交中...',
          mask: true,
        });
	let params=JSON.parse(JSON.stringify(worker));
	params.certificateFileUrl=params.certificateFileUrl.join(',')
        util.request(api.ServantPerfect,
          params, 'POST').then(function (res) {
          wx.hideLoading();
          if (res.errno === 0) {
            that.setData({
              showSubmit: false
            })
            wx.showToast({
              title: '信息完善成功',
              icon: 'success',
              duration: 2000
            });
          } else {
            util.showErrorToast(res.errmsg);
          }
        });


      }
    })
  },
  bindWorkerTel(e) {
    this.setData({
      workerTel: e.detail.value
    });
  },
  bindContactAddr(e) {
    this.setData({
      'worker.contactAddr': e.detail.value
    });
  },
  bindEmergencyContact(e) {
    this.setData({
      'worker.emergencyContact': e.detail.value
    });
  },
  bindHeight: function (e) {
    this.setData({
      'worker.height': e.detail.value
    });
  },
  bindWeight: function (e) {
    this.setData({
      'worker.weight': e.detail.value
    });
  },
  bindBankNo:function(e){
    this.setData({
      'worker.bankNo': e.detail.value
    });
  },
  bindBankOfDeposit:function(e){
    this.setData({
      'worker.bankOfDeposit': e.detail.value
    });
  },
  bindWorkerTel1: function (e) {
    this.setData({
      'worker.workerTel1': e.detail.value
    });
  },
  bindHealthCert(e) {
    this.setData({
      'worker.certificateNo': e.detail.value
    });
  },
  showHealthStart() {
    this.setData({
      showHealthStart: true
    });
  },
  showIssuanceDate() {
    this.setData({
      showIssuanceDate: true
    });
  },

  showHealthEnd() {
    this.setData({
      showHealthEnd: true
    });
  },
  showEducation() {
    this.setData({
      showEducation: true
    });
  },
  showExperience() {
    this.setData({
      showExperience: true
    });
  },
  showServiceItem() {
    this.setData({
      showServiceItem: true
    });
  },
  showCity() {
    this.setData({
      showCity: true
    });
	},
	showShebao:function(){ 
		this.setData({
      showShebao: true,
    });
	}, 
	onShebaoCancel:function(){
		this.setData({
      showShebao: false,
    });
	},
	onShebaoConfirm:function(event){
		console.log(event);
		let k=event.detail.value.key;
		if(this.data.worker.residenceType==undefined||this.data.worker.residenceType==''){
			wx.showToast({
        title: '请先选择户口,再选社保',
        icon:'none',
        duration: 2000
			});
			return ;
		}
		if(this.data.worker.residenceType==1&&(k==1||k==3)){
			wx.showToast({
        title: '农村户口请选：新农保、无',
        icon:'none',
        duration: 2000
			});
			return ;
		}
		if(this.data.worker.residenceType==2&&(k==2)){
			wx.showToast({
        title: '城镇户口不能选新农保',
        icon:'none',
        duration: 2000
			});
			return ;
		}
		this.setData({
			'worker.socialSecurity': event.detail.value.key,
			'worker.socialSecurityName': event.detail.value.value,
			showShebao: false,
		});
	},
	showHukou:function(){
		this.setData({
      showHukou: true,
    });
	},
	onHukouCancel:function(){
		this.setData({
      showHukou: false,
    });
	},
	onHukouConfirm:function(event){
	console.log(event.detail); 
	this.setData({
		'worker.residenceType': event.detail.value.key,
		'worker.residenceTypeName': event.detail.value.value,
		showHukou: false,
	});
	},
  onHealthEndCancel: function () {
    this.setData({
      showHealthEnd: false,
    });
  },
  onHealthEndConfirm: function (event) {
    let date = util.toDate(event.detail / 1000, true, '');
    this.setData({
      'worker.expirationDateEnd': date,
      showHealthEnd: false,
    });
  },
  onHealthStartCancel: function () {
    this.setData({
      showHealthStart: false,
    });
  },
  onHealthStartConfirm: function (event) {
    let date = util.toDate(event.detail / 1000, true, '');
    console.info(date)
    this.setData({
      'worker.expirationDateStart': date,
      showHealthStart: false,
    });
  },
  onIssuanceDateCancel: function () {
    this.setData({
      showIssuanceDate: false,
    });
  },
  onIssuanceDateConfirm: function (event) {
    let date = util.toDate(event.detail / 1000, true, '');
    console.info(date)
    this.setData({
      'worker.issuanceDate': date,
      showIssuanceDate: false,
    });
  },
  onServiceItemCancel: function () {
    this.setData({
      showServiceItem: false,
    });
  },
  onServiceItemConfirm: function (event) {
    this.setData({
      'worker.workType': event.detail.value,
      showServiceItem: false,
    });
  },
  onExperienceCancel: function () {
    this.setData({
      showExperience: false,
    });
  },
  onExperienceConfirm: function (event) {
    this.setData({
      'worker.experience': event.detail.value,
      showExperience: false,
    });
  },
  onEducationCancel: function () {
    this.setData({
      showEducation: false,
    });
  },
  onEducationConfirm: function (event) {
    this.setData({
      'worker.education': event.detail.value,
      showEducation: false,
    });
  },
  onCityCancel: function () {
    this.setData({
      showCity: false,
    });
  },
  onCityConfirm: function (event) {
    this.setData({
      'worker.city': event.detail.value,
      showCity: false,
    });
  },
  uploadHeadPic(){
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        let file=res.tempFilePaths[0];
        that.upload(file,'head');
      }
    })
  },
  uploadHealth(){
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        let file=res.tempFilePaths[0];
        that.upload(file,'health');
      }
    })
  },
  upload: function (path,type) {
    var that = this;
    const uploadTask = wx.uploadFile({
      url: api.StorageUpload(),
      filePath: path, //res.tempFilePaths[0],
      name: 'file',
      success: function (res) {
        var _res = JSON.parse(res.data);
        if (_res.errno === 0) {
          var url = _res.data.fileUrl
           if(type=='head'){
            that.setData({
              headPic:url,
              'worker.headPic':url
            });
           }else{
            that.setData({
              certificateFileUrl:[url],
              'worker.certificateFileUrl':[url]
            });
           }
        }
      },
      fail: function (e) {
        wx.showModal({
          title: '错误',
          content: '上传失败',
          showCancel: false
        })
      },
    })
  },
  chooseImage: function (e) {
    var that = this;
    let type = e.currentTarget.dataset.type;
    console.info(type)
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        if (type == "back")
          that.setData({
            idBack: res.tempFilePaths[0]
          });
        else
          that.setData({
            idFront: res.tempFilePaths[0]
          });
      }
    })
  },
  uploadIdFrontImage: function () {
    if (this.data.idBack == '' || this.data.idFront == '') {
      util.showErrorToast('请选择身份证照片');
      return;
    }
    wx.showLoading({
      title: '识别正面',
    })
    var that = this;
    wx.uploadFile({
      url: api.ServantPerfectOCR(),
      filePath: that.data.idFront,
      name: 'file',
      formData: {
        type: 'front'
      },
      header: {
        'Content-Type': 'multipart/form-data',
        'X-JZ-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        wx.hideLoading();
        var _res = JSON.parse(res.data);
        console.info(_res)
        if (_res.errno === 0) {
          //赋值
          var data=_res.data;
          console.log(data);
          that.setData({
            'worker.workerIdcard': data.workerIdcard,
            'worker.workerName': data.workerName,
            'worker.idcardAddress': data.idcardAddress,
            'worker.gender': data.gender,
            'worker.nation': data.nation,
            'worker.nativePlace': data.nativePlace
          })
          that.uploadIdBackImage();
        } else {
          wx.showModal({
            title: '错误',
            content: _res.errmsg,
            showCancel: false
          })
        }
      },
      fail: function (e) {
        console.info(e)
        wx.hideLoading();
        wx.showModal({
          title: '错误',
          content: '请重新选择正反面后上传',
          showCancel: false
        })
      },
    })

  },
  uploadIdBackImage: function () {
    wx.showLoading({
      title: '识别反面',
    })
    var that = this;
    const uploadTask = wx.uploadFile({
      url: api.ServantPerfectOCR(),
      filePath: that.data.idBack,
      name: 'file',
      formData: {
        type: 'back'
      },
      header: {
        'Content-Type': 'multipart/form-data',
        'X-JZ-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        wx.hideLoading();
        that.getWorkerInfo({
          workerNo: that.data.workerNo
        });
        var _res = JSON.parse(res.data);
        console.log(_res);
        if (_res.errno === 0) {
          var data=_res.data;
          console.log(data);
          that.setData({
            'worker.idcardStartdate': _res.data.idcardStartdate,
            'worker.break': '到',
            'worker.idcardEnddate': _res.data.idcardEnddate,
          })
          wx.showToast({
            title: '识别成功',
            duration: 2000
          });
        } else {
          wx.showModal({
            title: '错误',
            content: _res.errmsg,
            showCancel: false
          })
        }
      },
      fail: function (e) {
        console.info(e)
        wx.hideLoading();
        wx.showModal({
          title: '错误',
          content: '上传失败',
          showCancel: false
        })
      },
    })

  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: [e.currentTarget.id] // 需要预览的图片http链接列表
    })
  },
  onLoad: function (options) {
     let hasLogin=app.globalData.hasLogin;
     this.setData({
       hasLogin:hasLogin
     });
     if(hasLogin){
      //  通过workerno获取信息
      let userInfo = wx.getStorageSync('userInfo');
      if(userInfo && userInfo.workerNo){
        let workerNo=userInfo.workerNo;
        this.setData({
          workerNo:workerNo
        });
        this.getWorkerInfo({
          workerNo:workerNo
        });
      }


     }else{
      // 通过手机号获取信息
     }
  },
  onReady: function () {

  },
  onShow: function () {
    // wx.hideHomeButton();
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  }
})
