const app = getApp();
const util = require("../../../util/util.js")
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    ctx: false,
    hidden: true,
    showcamara: false,
    type:'card',
    phone:'',
    info:{
      card_code:"",
      phone:"",
      name:""
    }
  },
  onLoad: function (options) {
    let info = this.data.info;
    app.getMakerInfo(  res =>{
      Object.assign( info, res )
      let phone = info.phone||''
      this.setData( {info, phone })
    })
  },
  onReady: function (res) {
    var ctx = wx.createCameraContext('myCamera')
    this.setData({ ctx: ctx })
  },
  getInfo( ){
    util.http( '/wx/getMakerInfo', {}, (err,res)=>{
      if( err!= 0 ) return;
      console.log("http",err, res)
      let phone= res.info.phone||''
      this.setData({info: res.info,phone})
    })
  },
  previewImage: function (e) {
    var current = e.target.dataset.src;
    wx.previewImage({
      current: current, 
      urls: [current]
    })
  } ,
  takeCard(){
    this.setData( {showcamara:true, type:'card'})
  },
  takeCardBack(){
    this.setData( {showcamara:true, type:'cardBack'})
  },
  identify( err, {url} ){
    if( err !=0 || !url ) {
      util.showMsg("图片上传失败")
      return
    }
    let info = this.data.info
    let method=this.data.type=='card'?'/maker/addMakerCard':'/maker/addMakerBackCard';
    let showcamara= false
    util.http( method, {url}, (err,res)=>{
      if( err!= 0 ) return;
      console.log("http",err, res)
      Object.assign( info, res)
      this.setData({info,showcamara})
    })
  },
  chooseImg: function () {
    var that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album'], 
      success: function (res) {
        util.uploadFile( res.tempFilePaths[0], that.identify )
      }
    })
  },
  takePhoto() {
    var that = this
    var ctx = this.data.ctx
    that.setData({ hidden: false })
    ctx.takePhoto({
      quality: 'low',
      success: (res) => {
        var tempImagePath = res.tempImagePath
        util.uploadFile( tempImagePath, that.identify )
      },
      fail: function (res) {
        cosole.log('take error', res)
        that.setData({ hidden: true })
        app.showMsg('拍照失败')
      }
    })
  },
  onConfirm( e ){
    let {phone} = e.detail.value
    let info = this.data.info
    let {card_img, card_back_img} = this.data.info
    if( !card_img ) return util.showMsg( "身份证正面有误");
    if( !card_back_img ) return util.showMsg( "身份证背面有误");
    if( !phone || phone.length != 11 ) return util.showMsg( "手机号码有误");
    util.http( '/maker/identifyMaker', {phone}, (err,res)=>{
      if( err!= 0 ) return;
      this.setData({info})
    })

  },
  goBack() {
    wx.navigateBack({
      delta: 1
    })
  }
})