const api = require('../../../utils/api.js');
const login = require('../../../utils/index.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img:[],
    index: 0,
    tabindex: 0,
    codeType: ['身份证', '士官证', '港澳台居住证'],
    sbCodeIndex:0,
    lxCodeIndex:0,
    mask: false,
    imgList:[],
    image:[],
    dis: false,
    disabled:true,
    items: [
      { name: 'pickUp', value: '自取',checked: 'true' },
      { name: 'post', value: '邮寄' },
    ],
    textaddress:true
  },
  blur:function(e){
    this.setData({
      youjiaddress: e.detail.value,
      textaddress: true
    })
  },
  addresstext:function(e){
    this.setData({
      textaddress:false
    })
  },
  scroll:function(e){
    console.log(e)
  },
  kindToggle: function (e) {
    let that = this
    if (that.data.expand ===e.currentTarget.dataset.value){
      that.setData({
        dis: false,
        expand: e.currentTarget.dataset.value,
      })
      that.data.expand=''
    }else{
      that.setData({
        dis: true,
        expand: e.currentTarget.dataset.value,
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this
    that.data.flag=options.flag
    if(options.search){
      that.data.search = options.search
    }
    wx.request({
      url: api.guide,
      data: { unid:options.unid,userId:wx.getStorageSync('userId')},
      success(res){
        let levelList=[]
        for (var i = 0; i < res.data.data.preService.preServiceMaterialList.length;i++){
          if (res.data.data.preService.preServiceMaterialList[i].importLevel=='2'){
            that.data.image.push('')
            levelList.push(res.data.data.preService.preServiceMaterialList[i])
          }
        }
        res.data.data.preService.preServiceMaterialList=levelList
        that.setData({
          server:res.data.data,
          search: options.search == 1 ? true:false
        })
      }
    })
    var query = wx.createSelectorQuery();
    query.select('.tab').boundingClientRect();
    query.select('.flxed-bottom').boundingClientRect();
    query.exec(function (res) {
      that.data.topHeight = res[0].height
      that.data.flexHeight = res[1].height
      wx.getSystemInfo({
        success: function (res) {
          that.data.oldHeight = res.windowHeight - that.data.topHeight - that.data.flexHeight
          that.setData({
            clientHeight: res.windowHeight - that.data.topHeight - that.data.flexHeight
          });
        }
      })
    })
  },

  //提交表单
  formData:function(e){
    let that=this
    
    if (!that.setInput()){
      wx.showToast({
        title: '请完善表单信息',
        icon:'none'
      })
      return false;
    }
    for(let i=0;i<that.data.server.preService.preServiceMaterialList.length;i++){
      if (that.data.server.preService.preServiceMaterialList[i].importLevel==2){
        if (that.data.server.preService.preServiceMaterialList[i].isSet!=1){
          wx.showToast({
            title: '请上传必要材料信息',
            icon: 'none'
          })
          return false
        }
      }
    }
    if (that.data.mode =='post'){
      if (!e.detail.value.applyCardtype){
        wx.showToast({
          title: '请填写邮寄地址',
          icon: 'none'
        })
        return false
      }
    }
    wx.showLoading({
      title: '正在提交',
    })
    // for (var i = 0; i < that.data.server.preService.preServiceMaterialList.length;i++){
    //   if (!that.data.server.preService.preServiceMaterialList[i].isSet && that.data.server.preService.preServiceMaterialList[i].importLevel!=2){}
    // }
    if (that.data.user.identity == '0'){
      if (!e.detail.value.applyCardtype) {
        e.detail.value.applyCardtype = that.data.user.pDocumentType
      } else {
        e.detail.value.applyCardtype = that.data.contactmanCardtype[parseInt(e.detail.value.applyCardtype)].dictValueCode
      }
    }else{
      if (!e.detail.value.applyCardtype) {
        e.detail.value.applyCardtype = that.data.user.lInstitutionType
      } else {
        e.detail.value.applyCardtype = that.data.contactmanCardtype[parseInt(e.detail.value.applyCardtype)].dictValueCode
      }
    }
    if (!e.detail.value.contactmanCardtype) {
      e.detail.value.contactmanCardtype = that.data.contactmanCardtype[0].dictValueCode
    }else{
      e.detail.value.contactmanCardtype = that.data.contactmanCardtype[parseInt(e.detail.value.contactmanCardtype)].dictValueCode
    }
    e.detail.value.servicecode = that.data.server.preService.serviceCode
    e.detail.value.receiveUseid=wx.getStorageSync('userId')
    if(wx.getStorageSync('flag')==1){
      e.detail.value.applyType='个人申请'
    }else{
      e.detail.value.applyType = '法人申请'
    }
    e.detail.value.applyerTypeCode=wx.getStorageSync('flag')
    e.detail.value.applyCardtypeCode = e.detail.value.applyCardtype//申请者证件类型代码
    e.detail.value.contactmanCardtypeCode = e.detail.value.contactmanCardtype//代理人证件类型
    // 处理图片
    var imgList=[]
    for (var i = 0; i < that.data.server.preService.preServiceMaterialList.length;i++){
      var imgObj = {}
      imgObj.attrname = that.data.server.preService.preServiceMaterialList[i].name
      imgObj.amount = that.data.server.preService.preServiceMaterialList[i].copyNum + that.data.server.preService.preServiceMaterialList[i].srcNum
      imgObj.fileUrl=''
      imgObj.filename=''
      imgList.push(imgObj)
    }
    if(!that.data.image){
      that.data.image=[]
    }
    for (var j = 0; j < that.data.image.length; j++) {
      if (that.data.image[j]!=''){
        imgList[parseInt(that.data.image[j].index)].fileUrl += that.data.image[j].url + '^'
      }
    }
    e.detail.value.preAttrFile=imgList
    that.setData({
      disabled: false
    })
    if (that.data.mode =='post'){
      e.detail.value.resultAccess='02'
    }else{
      e.detail.value.resultAccess = '01'
    }
    wx.request({
      url: api.apasinfo,
      data: e.detail.value,
      success(res){
        wx.hideLoading();
        if(res.data.errno==0){
          wx.navigateTo({
            url: '/pages/success/index?type=handle&code='+res.data.data,
          })
        }else{
          wx.showToast({
            title: '网络繁忙，请稍候再试',
            icon:'none'
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that=this
    wx.showLoading({
      title: '正在加载',
      mask:true
    })
    wx.request({
      url: api.server,
      data: { code: 'CARDTYPE' },
      success(res){
        that.data.contactmanCardtype=res.data.data
        wx.request({
          url: api.getUser,
          data: { userId: wx.getStorageSync('userId') },
          success(r) {
            wx.hideLoading()
            var codeType = ''
            if (r.data.data.user.identity=='0'){
              if (r.data.data.user.pDocumentType) {
                for (var i = 0; i < res.data.data.length; i++) {
                  if (res.data.data[i].dictValueCode == r.data.data.user.pDocumentType) {
                    codeType = i
                  }
                }
              }
            } else if (r.data.data.user.identity == '1'){
              if (r.data.data.user.lInstitutionType) {
                for (var i = 0; i < res.data.data.length; i++) {
                  if (res.data.data[i].dictValueCode == r.data.data.user.lInstitutionType) {
                    codeType = i
                  }
                }
              }
            }
            console.log(r.data.data.user)
            that.setData({
              user: r.data.data.user,
              code: res.data.data,
              codeIndex: codeType ? codeType : 0,
              flag:that.data.flag,
              identity: r.data.data.user.identity,
            })
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that=this
    if (wx.getStorageSync('setImageIndex')){
      var setImageIndex = wx.getStorageSync('setImageIndex')
      wx.removeStorageSync('setImageIndex')
      var httpUrl = wx.getStorageSync('httpUrl');
      wx.removeStorageSync('httpUrl')
      
      // obj = { "url": '', "index": '', "time": '' }
      var imgUrl = wx.getStorageSync('imgUrl')
      if (!that.data.image) {
        that.data.image = []
      }
      for (var i = 0; i < imgUrl.length;i++){
        var obj = {}
        obj.url = imgUrl[i]
        obj.index = setImageIndex
        obj.time = i + '' + Math.random()
        obj.http = httpUrl
        that.data.image.push(obj)
      }
      that.data.server.preService.preServiceMaterialList[obj.index].isSet = 1
      that.data.img = that.data.image
      console.log(that.data.image)
      that.setData({
        image: that.data.image,
        ['server.preService.preServiceMaterialList']: that.data.server.preService.preServiceMaterialList
      })
      wx.removeStorageSync('imgUrl')
    }
    var obj = { "url": '', "index": 0, "time": 0}
    if (!that.data.img){
      obj = { "url": '', "index": wx.getStorageSync('setImageIndex'), "time": Math.random(), 'http': httpUrl}
    }

    for(var i=0;i<wx.getStorageSync('key').length;i++){

    }
  },
  image:function(e){
    let that=this
    that.data.imgIndex = e.target.dataset.index
    wx.showActionSheet({
      itemList: ['拍照', '选择图库', '我的材料'],
      success(res) {
        if (res.tapIndex==0){
          that.uploadImg('camera');
        } else if (res.tapIndex == 1){
          that.uploadImg('album');
        } else if (res.tapIndex == 2){
          wx.setStorageSync('setImageIndex', that.data.imgIndex.toString())
          wx.navigateTo({
            url: 'setData/setData',
          })
        }
      },
      fail(res) {
      }
    })
    return false
    
  },
  //跳转到基本表单
  basicForm:function(){
    this.setData({
      index:1
    })
  },
  dataName:function(e){
    this.data.dataName=e.detail.value
  },
  uploadImg:function(type){
    var that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success(res) {
        wx.showLoading({
          title: '正在上传',
        })
        
        wx.hideLoading();
        wx.uploadFile({
          url: api.uploadImg, 
          filePath: res.tempFilePaths[0],
          header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', },
          name: 'filePath',
          formData: {
            'fileType': 'image'
          },
          success(res1) {
            var obj = {}
            wx.hideLoading()
            that.data.uploadImage = JSON.parse(res1.data)
            that.data.img = that.data.image ? that.data.image : []
            for (var i = 0; i < res.tempFilePaths.length; i++) {
              obj = { "url": that.data.uploadImage.data.filePath, "index": that.data.imgIndex, "time": i + '' + Math.random(), 'http': that.data.uploadImage.data.filePathPrefix }
              that.data.img.push(obj)
            }
            
            if (that.data.uploadImage.errno==0) {
              that.data.server.preService.preServiceMaterialList[that.data.imgIndex].isSet=1
              that.setData({
                image: that.data.img,
                mask: true,
                imageIndex: that.data.imgIndex,
                ['server.preService.preServiceMaterialList']: that.data.server.preService.preServiceMaterialList
              })
            }
          }
        })
      }
    })
  },
  // 编辑材料名称
  maskSubmit:function(){
    let that=this
    if (!that.data.dataName){
      wx.showToast({
        title: '名称不能为空',
        icon:'none'
      })
      return false;
    }
    wx.request({
      url: api.addMaterial,
      data: {
        userId: wx.getStorageSync('userId'),
        materialName: that.data.dataName,
        materialUrl: that.data.uploadImage.data.filePath
      },
      method:'POST',
      success(res) {
        wx.showToast({
          title: '添加成功',
          icon: 'none'
        })
        that.setData({
          mask: false
        })
      }
    })
  },
  
  //预览图片
  preview:function(e){
    var url=[]
    for (var i = 0; i < e.target.dataset.url.length;i++){
      if(e.target.dataset.url[i]!=''){
        url.push(e.target.dataset.url[i].http + e.target.dataset.url[i].url)
      }
    }
    wx.previewImage({
      current: e.target.dataset.url[e.target.dataset.i].http+e.target.dataset.url[e.target.dataset.i].url, // 当前显示图片的http链接
      urls: url // 需要预览的图片http链接列表
    })
  },
  // 删除已选图片
  deleteImg:function(e){
    var that=this;
    for(var i=0;i<that.data.img.length;i++){
      if (that.data.img[i].time == e.target.dataset.id){
        that.data.img.splice(i,1);
      }
    }
    var number=0
    for (var i = 0; i < that.data.img.length; i++){
      if (that.data.img[i].index == e.target.dataset.index){
        number++
      }
    }
    if(number>0){
      that.data.server.preService.preServiceMaterialList[e.target.dataset.index].isSet = 1
    }else{
      that.data.server.preService.preServiceMaterialList[e.target.dataset.index].isSet = 0
    }
    that.setData({
      image: that.data.img,
      ['server.preService.preServiceMaterialList']: that.data.server.preService.preServiceMaterialList
    })
  },
  applyname: function (e) {
    e.detail.value ? this.data.applyname = true : false
    this.setData({
      applyname: e.detail.value
    })
  },
  applyCardnumber: function (e) {
    e.detail.value ? this.data.applyCardnumber = true : false
    this.setData({
      applyCardnumber: e.detail.value
    })
  },
  contactman:function(e){
    e.detail.value?this.data.contactman=true:false
    this.setData({
      contactman: e.detail.value
    })
  },
  contactmanCardnumber:function(e){
    e.detail.value ? this.data.contactmanCardnumber = true : false
    this.setData({
      contactmanCardnumber: e.detail.value
    })
  },
  telphone:function(e){
    e.detail.value ? this.data.telphone = true : false
    this.setData({
      telphone: e.detail.value
    })
  },
  postcode:function(e){
    this.setData({
      postcode: e.detail.value
    })
  },
  address:function(e){
    this.setData({
      address: e.detail.value
    })
  },
  remark: function (e) {
    this.setData({
      remark: e.detail.value
    })
  },
  setInput(){
    if (this.data.contactman && this.data.contactmanCardnumber && this.data.telphone){
      return true
    }else{
      return false
    }
  },
  //切换自取、邮寄
  radioChange: function (e) {
    this.data.mode=e.detail.value
    if (e.detail.value=='pickUp'){
      this.setData({
        modeInput: false,
        ['items[0].checked']: true
      })
    } else if (e.detail.value =='post'){
      this.setData({
        modeInput: true,
        ['items[1].checked']:true
      })
    }
  },
  // 打开遮罩层
  mask: function () {
    let that = this;
    that.setData({
      mask: true
    })
  },
  // 关闭遮罩层
  clear: function () {
    let that = this;
    that.setData({
      mask: false
    })
  },
  // 确认申报
  submit: function () {
    wx.navigateTo({
      url: '../success/success',
    })
  },
  
  // 申报人证件类型
  bindSbCodeChange: function (e) {
    this.setData({
      codeIndex: e.detail.value
    })
  },
  // 联系人证件类型
  bindLxCodeChange: function (e) {
    this.setData({
      lxCodeIndex: e.detail.value
    })
  },
  // tab切换
  tab: function (e) {
    let that = this
    if (that.setInput()) {
      that.setData({
        index: e.currentTarget.dataset.index,
        current_index: e.currentTarget.dataset.index,
        setInput: true
      })
    } else {
      that.setData({
        index: e.currentTarget.dataset.index,
        current_index: e.currentTarget.dataset.index,
        setInput: false
      })
    }
    if(e.currentTarget.dataset.index==3){
      var query = wx.createSelectorQuery();
      query.select('.tab').boundingClientRect();
      query.select('.flxed-bottom1').boundingClientRect();
      query.exec(function (res) {
        that.data.topHeight = res[0].height
        that.data.flexHeight = res[1].height
        wx.getSystemInfo({
          success: function (res) {
            that.setData({
              clientHeight: res.windowHeight - that.data.topHeight - that.data.flexHeight
            });
          }
        })
      })
    }else{
      that.setData({
        clientHeight:that.data.oldHeight
      })
    }
  },
  change: function (e) {
    var that=this
    if (that.setInput()) {
      that.setData({
        index: e.detail.current,
        setInput: true
      })
    } else {
      that.setData({
        index: e.detail.current,
        setInput: false
      })
    }
  },
  // 下一步
  next: function () {
    let that = this
    that.setData({
      index: that.data.index + 1,
      current_index: that.data.index + 1
    })
  },
  // 上一步
  up: function () {
    let that = this
    that.setData({
      index: that.data.index - 1,
      current_index: that.data.index - 1
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

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

  },

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

  },

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

  },

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

  }
})