var app = getApp();
const config = require('../../../../config/config.js')
const util = require('../../../../utils/util.js')
const Http = require('../../../../utils/HttpBasics.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    businessLicenseInfo: null,
    idCardInfo: null,
    idDocInfo: null,
    idDocType: null,
    id: "",
    organizationType: '',
    isSeal: "false",
    commonLsit: [{
      id: "true",
      name: "是",
    },
    {
      id: "false",
      name: "否",
    }],
    licenseEffectiveIdentityType: 1, ///身份证有效期类型
    figureLsit: [{
      id: 1,
      name: "法定代表人/经营者"
    },
    {
      id: 2,
      name: "经办人"
    },
    ],

    figureType: "",

    certificateType: null, //证件类型
    certificateLsit: [{
      id: 1,
      name: "中国大陆居民-身份证"
    },
    {
      id: 2,
      name: "其他国家或地区居民-护照"
    },
    {
      id: 3,
      name: "中国香港居民--来往内地通行证"
    },
    {
      id: 4,
      name: "中国澳门居民--来往内地通行证"
    },
    {
      id: 5,
      name: "中国台湾居民--来往内地通行证"
    },
    {
      id: 6,
      name: "外国人居留证"
    },
    {
      id: 7,
      name: "港澳居民证"
    },
    {
      id: 8,
      name: "台湾居民证"
    },
    ],
    identityZUrl: "",
    identityFUrl: "",
    licenseEffectiveIdentity: "", //身份证生效日期
    licenseLoseIdentity: "", //

    contactInfo: {
      is_index: "0",
      is_seal: "true",
      certificateIndex: 0, //证件下标
      contact_type: "1", //超级管理员类型 1经营者/法人2经办人
      figureIndex: 0, //超管身份下标
      contact_name: "", //超级管理员姓名
      mobile_phone: "", //联系手机
      contact_email: "", //邮箱

      contact_department: "", //超级管理员部门(当选择经办人时传)
      contact_job: "", //超级管理员职务(当选择经办人时传)
      contact_id_doc_type: 1, //超级管理员证件类型 身份证 等(当选择经办人时传)
      contact_id_number: "", //超级管理员证件号码 (当选择经办人时传)
      contact_id_doc_copy_info: { //超级管理员证件正面照片 (当选择经办人时传)
        url: "",
        media_id: ""
      },
      contact_id_doc_copy_back_info: { //超级管理员证件反面照片  护照不传 (当选择经办人时传)
        url: "",
        media_id: ""
      },
      contact_period_type: "1", //1=定期 2=长期 (当选择经办人时传)
      contact_period_begin: "", //超级管理员证件有效期开始时间 (当选择经办人时传)
      contact_period_end: "", //超级管理员证件有效期结束时间 (当选择经办人时传)
      business_authorization_letter_info: { //业务办理授权函(当选择经办人时传)
        url: "",
        media_id: ""
      }
    },
    active1: '',
    active2: '',
    active3: '',
  },

  save(e) {
    let flag = e.currentTarget.dataset.flag
    let parame = {};
    let tempContactInfo = {}
    let reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/; //11位手机号码正则
    let reg_em = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/; //验证邮箱
    let errMeg = "";
    let errFlag = false;

    if (this.data.contactInfo.contact_type == 1) {
      if (!this.data.contactInfo.contact_name) {
        errMeg = "请输入超管姓名";
        errFlag = true;
      } else if (!this.data.contactInfo.mobile_phone || !reg_tel.test(this.data.contactInfo.mobile_phone)) {
        errMeg = "请输入正确手机号码";
        errFlag = true;
      } else if (!this.data.contactInfo.contact_email || !reg_em.test(this.data.contactInfo.contact_email)) {
        errMeg = "请输入正确电子邮箱";
        errFlag = true;
      }
    } else if (this.data.contactInfo.contact_type == 2) {
      if (!this.data.contactInfo.contact_name) {
        errMeg = "请输入超管姓名";
        errFlag = true;
      } else if (!this.data.contactInfo.mobile_phone || !reg_tel.test(this.data.contactInfo.mobile_phone)) {
        errMeg = "请输入正确手机号码";
        errFlag = true;
      } else if (!this.data.contactInfo.contact_email || !reg_em.test(this.data.contactInfo.contact_email)) {
        errMeg = "请输入正确电子邮箱";
        errFlag = true;
      } else if (!this.data.contactInfo.contact_id_doc_copy_info.url) {
        errMeg = "请上传证件正面照";
        errFlag = true;
      } else if (!this.data.contactInfo.contact_id_doc_copy_back_info.url) {
        errMeg = "请上传证件反面照";
        errFlag = true;
      } else if (!this.data.contactInfo.contact_id_number) {
        errMeg = "请输入证件号码";
        errFlag = true;
      } else if (!this.data.contactInfo.contact_department) {
        errMeg = "请输入职称部门";
        errFlag = true;
      } else if (!this.data.contactInfo.contact_job) {
        errMeg = "请输入职务";
        errFlag = true;
      }
      //else if (!this.data.contactInfo.business_authorization_letter_info.url) {
      //   errMeg = "请输入上传业务办理授权函";
      //   errFlag = true;
      // }
    }

    if (errFlag) {
      wx.showToast({
        title: errMeg,
        icon: "none",
        duration: 2000
      })
      return
    }

    if (this.data.contactInfo.contact_type == 1 && this.data.contactInfo.contact_period_type == 2) {
      let tempObj = this.data.contactInfo
      tempObj.contact_period_end = "长期"
      this.setData({
        contactInfo: tempObj
      })
    }

    if (this.data.contactInfo.contact_type == 1) { //1经营者/法人2经办人
      tempContactInfo.contact_type = this.data.contactInfo.contact_type
      tempContactInfo.contact_name = this.data.contactInfo.contact_name
      tempContactInfo.mobile_phone = this.data.contactInfo.mobile_phone
      tempContactInfo.contact_email = this.data.contactInfo.contact_email
      tempContactInfo.certificateIndex = this.data.contactInfo.certificateIndex

    } else if (this.data.contactInfo.contact_type == 2) {
      tempContactInfo.contact_type = this.data.contactInfo.contact_type
      tempContactInfo.contact_name = this.data.contactInfo.contact_name
      tempContactInfo.mobile_phone = this.data.contactInfo.mobile_phone
      tempContactInfo.contact_email = this.data.contactInfo.contact_email
      tempContactInfo.contact_department = this.data.contactInfo.contact_department
      tempContactInfo.contact_job = this.data.contactInfo.contact_job
      tempContactInfo.contact_id_doc_type = this.data.contactInfo.contact_id_doc_type
      tempContactInfo.contact_id_number = this.data.contactInfo.contact_id_number
      tempContactInfo.contact_id_doc_copy_info = this.data.contactInfo.contact_id_doc_copy_info
      if (this.data.contactInfo.contact_id_doc_type != 2) {
        tempContactInfo.contact_id_doc_copy_back_info = this.data.contactInfo.contact_id_doc_copy_back_info
      }

      tempContactInfo.contact_period_type = this.data.contactInfo.contact_period_type
      tempContactInfo.contact_period_begin = this.data.contactInfo.contact_period_begin
      tempContactInfo.contact_period_end = this.data.contactInfo.contact_period_end
      tempContactInfo.business_authorization_letter_info = this.data.contactInfo.business_authorization_letter_info
      tempContactInfo.figureIndex = this.data.contactInfo.figureIndex
      tempContactInfo.certificateIndex = this.data.contactInfo.certificateIndex
      tempContactInfo.is_index = this.data.contactInfo.is_index
      tempContactInfo.is_seal = this.data.contactInfo.is_seal

    }
    console.log(tempContactInfo)


    parame = {
      id: this.data.id,
      organizationType: this.data.organizationType,
      contactInfo: JSON.stringify(tempContactInfo)

    }


    console.log(parame, "parame")

    Http.post({
      url: config.api.receiverAdd,
      data: parame
    }).then(res => {
      console.log(res, "res")
      if (flag == "save") {
        wx.reLaunch({
          url: '/pages/warehouse/warehouse',
        })
      } else if (flag == "next") {
        wx.switchTab({
          url: '/pages/mine/mine',
        })
      }

    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: "none",
        duration: 2000
      })
    })

  },

  normalImage(e) {
    let type = e.currentTarget.dataset.type
    if (type == 1) {
      this.setData({
        active1: false
      })
    } else if (type == 2) {
      this.setData({
        active2: false
      })
    } else if (type == 3) {
      this.setData({
        active3: false
      })
    }
    console.log('normalImage');
  },

  previewImage(e) {
    let type = e.currentTarget.dataset.type
    if (type == 1) {
      this.setData({
        active1: true
      })
    } else if (type == 2) {
      this.setData({
        active2: true
      })
    } else if (type == 3) {
      this.setData({
        active3: true
      })
    }
    console.log('previewImage');
  },

  setValue(e) {
    let flag = e.currentTarget.dataset.flag
    let value = e.detail.value.trim()
    let tempObj = this.data.contactInfo
    tempObj[flag] = value
    console.log(value)
    this.setData({
      contactInfo: tempObj
    })
  },

  setlicenseEffectiveIdentityType(e) {
    let index = e.currentTarget.dataset.index
    let tempObj = this.data.contactInfo
    tempObj.contact_period_type = index
    this.setData({
      contactInfo: tempObj
    })
  },

  getReceiverApply() {
    wx.showLoading({
      title: '加载中...',
    })
    Http.get({
      url: config.api.getReceiverApply,
      data: {
        merchantId: app.globalData.merchant.merchant_id
      }
    }).then(res => {
      if (res.data && res.data.organizationType) {
        this.setData({
          organizationType: res.data.organizationType
        })
      }

      if (res.data && res.data.id) {
        this.setData({
          id: res.data.id
        })
      }
      if (res.data && res.data.contactInfo) {
        let obj = JSON.parse(res.data.contactInfo)
        this.setData({
          contactInfo: {
            ...this.data.contactInfo,
            ...obj
          }
        })
      }
      console.log(this.data.contactInfo, "this.data.contactInfo")
      if (this.data && res.data.businessLicenseInfo) {
        let obj = JSON.parse(res.data.businessLicenseInfo)
        this.setData({
          businessLicenseInfo: obj
        })
      }
      if (res.data.idCardInfo) {
        let obj = JSON.parse(res.data.idCardInfo)
        console.log(obj.id_card_number, 'id_card_number');
        this.setData({
          idCardInfo: obj
        })
      }

      if (res.data && res.data.idDocInfo) {
        let obj = JSON.parse(res.data.idDocInfo)
        this.setData({
          idDocInfo: obj
        })
      }
      if (res.data && res.data.idDocType) {
        this.setData({
          idDocType: res.data.idDocType
        })
      }
      console.log(this.data.contactInfo, "contactInfo")

      wx.hideLoading();
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err.message,
        icon: "none",
        duration: 2000
      })
    })
  },

  authorization() {
    let that = this;
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: config.api.merchantUpload, // 仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            'token': app.globalData.token
          },
          success(res) {
            let tempObj = that.data.contactInfo
            tempObj.business_authorization_letter_info = JSON.parse(res.data).data
            that.setData({
              contactInfo: tempObj
            })
            // do something
            console.log(JSON.parse(res.data).data)
          }
        })
      }
    })
  },

  upIdentityZ() {
    let that = this;
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: config.api.merchantUpload, // 仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            'token': app.globalData.token
          },
          success(res) {
            let tempObj = that.data.contactInfo
            tempObj.contact_id_doc_copy_info = JSON.parse(res.data).data
            that.setData({
              contactInfo: tempObj
            })
            // do something
            console.log(JSON.parse(res.data).data)
          }
        })
      }
    })
  },
  upIdentityF() {
    let that = this;
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: config.api.merchantUpload, // 仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            'token': app.globalData.token
          },
          success(res) {
            let tempObj = that.data.contactInfo
            tempObj.contact_id_doc_copy_back_info = JSON.parse(res.data).data

            that.setData({
              contactInfo: tempObj
            })
            // do something
          }
        })
      }
    })
  },
  delIdentityFUrl() {
    let tempObj = this.data.contactInfo
    tempObj.contact_id_doc_copy_back_info = {}
    this.setData({
      contactInfo: tempObj,
    })
  },

  delIdentityZUrl() {
    let tempObj = this.data.contactInfo
    tempObj.contact_id_doc_copy_info = {}
    this.setData({
      contactInfo: tempObj,
    })
  },

  delAuthorization() {
    let tempObj = this.data.contactInfo
    tempObj.business_authorization_letter_info = {}
    this.setData({
      contactInfo: tempObj,
    })
  },
  setIsSealIndex(e) {
    let tempObj = this.data.contactInfo
    let id = this.data.commonLsit[e.detail.value].id
    tempObj.is_index = e.detail.value
    tempObj.is_seal = id
    this.setData({
      contactInfo: tempObj,
    })
  },

  bindDateChange1: function (e) {

    let id = this.data.figureLsit[e.detail.value].id
    let tempObj = this.data.contactInfo
    tempObj.contact_type = id
    tempObj.figureIndex = e.detail.value
    this.setData({
      contactInfo: tempObj
    })
  },

  bindDateChange2: function (e) {
    let id = this.data.certificateLsit[e.detail.value].id
    let tempObj = this.data.contactInfo
    tempObj.certificateIndex = e.detail.value
    tempObj.contact_id_doc_type = id
    this.setData({
      contactInfo: tempObj
    })
    console.log(id)
  },

  bindDateChange3: function (e) {
    let tempObj = this.data.contactInfo
    tempObj.contact_period_begin = e.detail.value
    this.setData({
      contactInfo: tempObj,
    })
  },

  bindDateChange4: function (e) {
    let tempObj = this.data.contactInfo
    tempObj.contact_period_end = e.detail.value
    this.setData({
      contactInfo: tempObj,
    })
  },

  downloadUrl() {
    let param = {
      contact_name: this.data.contactInfo.contact_name, //经办人姓名
      contact_id_number: this.data.contactInfo.contact_id_number, //经办人身份证
      contact_department: this.data.contactInfo.contact_department, //部门
      contact_job: this.data.contactInfo.contact_job, //职位
      id_card_number: this.data.idCardInfo.id_card_number,// 法人身份证号
      legal_person: this.data.businessLicenseInfo.legal_person, //法人姓名
      is_seal: this.data.contactInfo.is_seal, //是否有公章（字符串"true","false"）
      merchant_name: this.data.businessLicenseInfo.merchant_name, //商户或企业名称
      card_period_begin: '',
      card_period_end: ''
    }

    if (this.data.idDocType == 1) {
      param.id_card_number = this.data.idCardInfo.id_card_number ? this.data.idCardInfo.id_card_number : ''; //法人身份证
      param.card_period_begin = this.data.idCardInfo.card_period_begin ? this.data.idCardInfo.card_period_begin : ''; //法人身份证有效期开始
      param.card_period_end = this.data.idCardInfo.card_period_end ? this.data.idCardInfo.card_period_end : ''; //法人身份证有效期结束
    } else {
      param.id_card_number = this.data.idDocInfo.id_card_number ? this.data.idDocInfo.id_card_number : ''; //法人身份证
      param.card_period_begin = this.data.idDocInfo.card_period_begin ? this.data.idDocInfo.card_period_begin : ''; //法人身份证有效期开始
      param.card_period_end = this.data.idDocInfo.card_period_end ? this.data.idDocInfo.card_period_end : ''; //法人身份证有效期结束
    }

    let errMeg = "";
    let errFlag = false;
    // 身份证号码正则校验——（中国大陆-兼容1代2代身份证号）
    const idReg = /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/

    if (!param.contact_name) {
      errMeg = "请输入证件姓名";
      errFlag = true;
    } else if (!param.contact_id_number) {
      errMeg = "请输入证件号码";
      errFlag = true;
    } else if (param.contact_id_number) {
      if (!idReg.test(param.contact_id_number)) {
        errMeg = "身份证号格式错误！";
        errFlag = true;
      }
    } else if (!param.contact_job) {
      errMeg = "请输入职务";
      errFlag = true;
    } else if (!param.contact_department) {
      errMeg = "请输入任职部门";
      errFlag = true;
    } else if (!param.legal_person) {
      errMeg = "请返回步骤一输入法人姓名";
      errFlag = true;
    } else if (!param.id_card_number) {
      errMeg = "请返回步骤一输入法人身份证号";
      errFlag = true;
    } else if (!param.card_period_begin || !param.card_period_end) {
      errMeg = "请返回步骤一输入法人身份证有效期";
      errFlag = true;
    } else if (!param.merchant_name) {
      errMeg = "请返回步骤一输入商户名称";
      errFlag = true;
    }

    // 当校验不通过时，阻止请求发送
    if (errFlag) {
      wx.showToast({
        title: errMeg,
        icon: "none",
        duration: 2000
      })
      return
    }

    wx.showLoading({
      title: '下载中...',
    })
    console.log(param, 'param');
    Http.post({
      url: config.api.getYwsqh,
      data: param
    }).then(res => {
      console.log(res, '获得的图片信息')
      const filepath = wx.env.USER_DATA_PATH + '/test.png';
      const imgTrans = wx.getFileSystemManager()
      imgTrans.writeFile({
        filePath: filepath,
        data: res.data,
        encoding: 'base64',
        success: res => {
          wx.saveImageToPhotosAlbum({
            filePath: filepath,
            success: function (res) {
              wx.hideLoading();
              wx.showToast({
                title: '保存成功',
                icon: "none"
              })
            },
            fail: function (err) {
              console.log(err, "errw")
              wx.showToast({
                title: "下载失败",
                icon: "none",
                duration: 3000
              })
            }
          })
        }
      })
    }).catch(err => {
      console.log(err)
      wx.hideLoading()
      wx.showToast({
        title: "下载失败",
        icon: "none",
        duration: 2000
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getReceiverApply()
    let that = this;
    //获取完整的日期
    let date = new Date;
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let tempObj = this.data.contactInfo
    tempObj.contact_period_begin = year + '-' + month + '-' + day
    tempObj.contact_period_end = year + '-' + month + '-' + day
    if (month < 10) {
      month = "0" + month
    }
    if (day < 10) {
      day = "0" + day
    }
    that.setData({
      licenseEffectiveIdentity: year + '-' + month + '-' + day,
      licenseLoseIdentity: year + '-' + month + '-' + day,
      contactInfo: tempObj
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})