import WxValidate from '../../utils/WxValidate.js';
const app = require('../../utils/util.js');
const request = require('../../utils/request.js');
const COS = require('../../utils/cos.js');
const tool = require('../../utils/tool.js');
Page({
  data: {
    form: {
      phone: '',
      height: '',
      weight: '',
      education: '',
      income: '',
      marriage: '',
      children: '',
      assetHouse: '',
      assetArea: '',
      assetHouseLoan: '',
      assetCar: '',
      assetCarValue: '',
      assetCarLoan: '',
      isCommen: '',
      controlTime: '',
      workStatus: '',
      companyNature: '',
      company: '',
      parents: '',
      fatherWork: '',
      motherWork: '',
      parentAssets:'',
      composition: '',
      motionState: '',
      hobby: '',
      photo: ''
    },
    heightArr: [],
    weightArr: [],
    educationArr: [],
    incomeArr: [],
    marriageList: [],
    childrenArr: [],
    deposit: '',
    assetHouseArr: ['租房', '购房'],
    assetAreaArr: ['80平以下', '80-120平', '120平以上'],
    assetHouseLoanArr: ['有', '没有'],
    assetCarArr: ['有', '没有'],
    assetCarValueArr: ['10万以下', '10-20万', '20-30万', '30-40万', '40-50万', '50-60万', '60-70万', '70-80万', '80-90万', '90-100万', '100万以上'],
    assetCarLoanArr: ['有贷款', '无贷款'],
    isCommenArr: ['一起', '没有'],
    controlTimeArr: [{
        name: '不限',
        value: '不限',
        checked: true
      },
      {
        name: '晚18：00以后',
        value: '晚18：00以后',
        checked: false
      }, {
        name: '星期六',
        value: '星期六',
        checked: false
      }, {
        name: '星期日',
        value: '星期日',
        checked: false
      }
    ],
    workStatusArr: [],
    companyNatureArr: [],
    parentsArr: ['爹妈比我都健康,一直很恩爱', '爹妈比我都健康,离婚了', '世事无常'],
    fatherWorkArr: ['退休', '政府机关', '事业单位', '外企企业', '世界500强', '上市公司', '国有企业', '私营企业', '个体'],
    motherWorkArr: ['退休', '政府机关', '事业单位', '外企企业', '世界500强', '上市公司', '国有企业', '私营企业', '个体'],
    parentAssetsArr:[],
    compositionArr: [{
        name: '没有唯我独尊',
        value: '没有唯我独尊',
        checked: false
      },
      {
        name: '有姐姐',
        value: '偶有姐姐',
        checked: false
      }, {
        name: '有哥哥',
        value: '有哥哥',
        checked: false
      }, {
        name: '有弟弟',
        value: '有弟弟',
        checked: false
      }, {
        name: '有妹妹',
        value: '有妹妹',
        checked: false
      }
    ],
    figureArr: ['龟息养生从不运动', '三天打鱼偶尔运动', '动如脱兔成天运动']
  },
  heightPicker(e) {
    let height = 'form.height'
    this.setData({
      [height]: this.data.heightArr[e.detail.value]
    })
  },
  weightPicker(e) {
    let weight = 'form.weight'
    this.setData({
      [weight]: this.data.weightArr[e.detail.value]
    })
  },
  educationPicker(e) {
    let education = 'form.education'
    this.setData({
      [education]: this.data.educationArr[e.detail.value]
    })
  },
  incomePicker(e) {
    let income = 'form.income'
    this.setData({
      [income]: this.data.incomeArr[e.detail.value]
    })
  },
  marriageChange(e) {
    console.log(e.detail.value)
    const items = this.data.marriageList
    let checked = 'marriageList[0].checked';
    let checked1 = 'marriageList[1].checked'
    this.setData({
      [checked]: false,
      [checked1]: false
    })
    for (let i = 0, lenI = items.length; i < lenI; ++i) {
      if (items[i].value == e.detail.value) {
        items[i].checked = true;
        break
      }
    }
    this.setData({
      marriageList: this.data.marriageList
    })
    let marriage = 'form.marriage'
    this.setData({
      [marriage]: e.detail.value
    })
  },
  childrenChange (e) {
    console.log(e.detail.value)
    const items = this.data.childrenArr;
    const values = e.detail.value;
    for (let i = 0, lenI = items.length; i < lenI; ++i) {
      items[i].checked = false
      for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (items[i].value === values[j]) {
          items[i].checked = true
          break
        }
      }
    }
    this.setData({
      childrenArr: this.data.childrenArr
    })
    let children = 'form.children'
    this.setData({
      [children]: e.detail.value
    })
  },
  assetHousePickerChange(e) {
    console.log(e)
    let assetHouse = 'form.assetHouse'
    this.setData({
      [assetHouse]: this.data.assetHouseArr[e.detail.value]
    })
  },
  assetAreaPickerChange(e) {
    console.log(e)
    let assetArea = 'form.assetArea'
    this.setData({
      [assetArea]: this.data.assetAreaArr[e.detail.value]
    })
  },
  assetHouseLoanPickerChange(e) {
    console.log(e)
    let assetHouseLoan = 'form.assetHouseLoan'
    this.setData({
      [assetHouseLoan]: this.data.assetHouseLoanArr[e.detail.value]
    })
  },
  assetCarPickerChange(e) {
    console.log(e)
    let assetCar = 'form.assetCar'
    this.setData({
      [assetCar]: this.data.assetCarArr[e.detail.value]
    })
  },
  assetCarValuePickerChange(e) {
    console.log(e)
    let assetCarValue = 'form.assetCarValue'
    this.setData({
      [assetCarValue]: this.data.assetCarValueArr[e.detail.value]
    })
  },
  assetCarLoanPickerChange(e) {
    console.log(e)
    let assetCarLoan = 'form.assetCarLoan'
    this.setData({
      [assetCarLoan]: this.data.assetCarLoanArr[e.detail.value]
    })
  },
  isCommenChange(e) {
    let isCommen = 'form.isCommen'
    this.setData({
      [isCommen]: this.data.isCommenArr[e.detail.value]
    })
  },
  controlTimeChange(e) {
    console.log(e.detail.value)
    const items = this.data.controlTimeArr;
    const values = e.detail.value;
    for (let i = 0, lenI = items.length; i < lenI; ++i) {
      items[i].checked = false
      for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (items[i].value === values[j]) {
          items[i].checked = true
          break
        }
      }
    }
    this.setData({
      controlTimeArr: this.data.controlTimeArr
    })
    let controlTime = 'form.controlTime'
    this.setData({
      [controlTime]: e.detail.value
    })
  },
  workStatusChange(e) {
    console.log(e.detail.value)
    const items = this.data.workStatusArr;
    const values = e.detail.value;
    for (let i = 0, lenI = items.length; i < lenI; ++i) {
      items[i].checked = false
      for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (items[i].value === values[j]) {
          items[i].checked = true
          break
        }
      }
    }
    this.setData({
      workStatusArr: this.data.workStatusArr
    })
    let workStatus = 'form. workStatus'
    this.setData({
      [workStatus]: e.detail.value
    })
  },
  workplacePicker (e) {
    let companyNature = 'form.companyNature'
    this.setData({
      [companyNature]: this.data.workplaceArr[e.detail.value]
    })
  },
  parentsPicker(e) {
    let parents = 'form.parents'
    this.setData({
      [parents]: this.data.parentsArr[e.detail.value]
    })
  },
  fatherworkPicker (e) {
    let fatherWork = 'form.fatherWork'
    this.setData({
      [fatherWork]: this.data.dadworkplaceArr[e.detail.value]
    })
  },
  motherworkPicker (e) {
    let motherWork = 'form.motherWork'
    this.setData({
      [motherWork]: this.data.momworkplaceArr[e.detail.value]
    })
  },
  parentAssetsPicker(e){
    let parentAssets = 'form.parentAssets'
    this.setData({
      [parentAssets]: this.data.parentAssetsArr[e.detail.value]
    })
  },
  compositionChange(e) {
    console.log(e.detail.value)
    const items = this.data.otherchildArr;
    const values = e.detail.value;
    for (let i = 0, lenI = items.length; i < lenI; ++i) {
      items[i].checked = false
      for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (items[i].value === values[j]) {
          items[i].checked = true
          break
        }
      }
    }
    this.setData({
      otherchildArr: this.data.otherchildArr
    })
    let composition = 'form.composition'
    this.setData({
      [composition]: e.detail.value
    })
  },
  figurePicker(e) {
    let motionState = 'form.motionState'
    this.setData({
      [motionState]: this.data.figureArr[e.detail.value]
    })
  },
  // 提交
  formSubmit(e) {
    const params = e.detail.value
    //校验表单
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    wx.request({
      url: app.globalData.publicUrl + '/wx/member/' + this.data.openid + '/info',
      method: "POST",
      data: params,
      success: (res) => {
        console.log(res)
        if (res.data.code == 0) {
          wx.showModal({
            title: '上传成功',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/targetInfo/targetInfo',
                })
              }
            }
          });
        }
      }
    })
  },
  //报错 
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  //验证函数
  initValidate() {
    const rules = {
      phone: {
        required: true
      },
      height: {
        required: true
      },
      weight: {
        required: true
      },
      education: {
        required: true
      },
      income: {
        required: true
      },
      marriage: {
        required: true
      },
      children: {
        required: true
      },
      assetHouse: {
        required: true
      },
      assetArea: {
        required: true
      },
      assetHouseLoan: {
        required: true
      },
      assetCar: {
        required: true
      },
      assetCarValue: {
        required: true
      },
      assetCarLoan: {
        required: true
      },
      isCommen: {
        required: true
      },
      controlTime: {
        required: true
      },
      workStatus: {
        required: true
      },
      companyNature: {
        required: true
      },
      company: {
        required: true
      },
      parents: {
        required: true
      },
      composition: {
        required: true
      },
      motionState: {
        required: true
      },
      hobby: {
        required: true
      },
      photo: {
        required: true
      }
    }
    const messages = {
      phone: {
        required: '请输入联系方式'
      },
      height: {
        required: '请选择身高'
      },
      weight: {
        required: '请选择体重'
      },
      education: {
        required: '请选择教育程度'
      },
      income: {
        required: '请选择收入'
      },
      marriage: {
        required: '请选择婚姻状态'
      },
      children: {
        required: '请选择有没有孩子'
      },
      assetHouse: {
        required: '请选择是否买房子'
      },
      assetArea: {
        required: '请选择房子多大面积'
      },
      assetHouseLoan: {
        required: '请选择房子贷款了没'
      },
      assetCar: {
        required: '请选择车子情况'
      },
      assetCarValue: {
        required: '请选择车子的价值'
      },
      assetCarLoan: {
        required: '请选择车子贷款了没'
      },
      isCommen: {
        required: '请选择是否与父母同住'
      },
      controlTime: {
        required: '请选择您的空闲时间'
      },
      workStatus: {
        required: '请选择您的工作状态'
      },
      companyNature: {
        required: '请选择您的单位性质'
      },
      company: {
        required: '请输入您的单位具体名称'
      },
      parents: {
        required: '请选择您的父母情况'
      },
      composition: {
        required: '请选择有没有兄弟姐妹'
      },
      motionState: {
        required: '请选择您是否喜欢运动'
      },
      hobby: {
        required: '请填写您的爱好'
      },
      photo: {
        required: '请上传您的照片'
      }
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  async onLoad(options) {
    this.initValidate();
    const getOpenid = await tool.openidStatus();
    this.setData({
      openid: getOpenid[0],
      sessionkey: getOpenid[1]
    })
    tool.formDetails('he_body_height').then(result => {
      this.setData({
        heightArr: result[0],
        heightArrValue: result[1]
      })
    })
    tool.formDetails('he_body_weight').then(result => {
      this.setData({
        weightArr: result[0],
        weightArrValue: result[1]
      })
    })
    tool.formDetails('he_education').then(result => {
      this.setData({
        educationArr: result[0],
        educationArrValue: result[1]
      })
    })
    tool.formDetails('he_income').then(result => {
      this.setData({
        incomeArr: result[0],
        incomeArrValue: result[1]
      })
    })
    tool.formDetails('he_marriage').then(result => {
      let marriageList = result[0].map((item, index) => {
        return Object.assign({}, {
          'name': item,
          'value':item,
          'checked':false
        })
      })
      let marriageListValue = result[1].map((item, index) => {
        return Object.assign({}, {
          'name': item,
          'value':item,
          'checked':false
        })
      })
      this.setData({
        marriageList:marriageList,
        marriageListValue: marriageListValue
      })
    })
    tool.formDetails('he_children').then(result => {
      let childrenArr = result[0].map((item, index) => {
        return Object.assign({}, {
          'name': item,
          'value':item,
          'checked':false
        })
      })
      let childrenArrValue = result[1].map((item, index) => {
        return Object.assign({}, {
          'name': item,
          'value':item,
          'checked':false
        })
      })
      this.setData({
        childrenArr: childrenArr,
        childrenArrValue: childrenArrValue
      })
    })
    tool.formDetails('he_control_time').then(result => {
      let controlTimeArr = result[0].map((item, index) => {
        return Object.assign({}, {
          'name': item,
          'value':item,
          'checked':false
        })
      })
      let controlTimeArrValue = result[1].map((item, index) => {
        return Object.assign({}, {
          'name': item,
          'value':item,
          'checked':false
        })
      })
      this.setData({
        controlTimeArr: controlTimeArr,
        controlTimeArrValue: controlTimeArrValue
      })
    })
    tool.formDetails('he_work_status').then(result => {
      let workStatusArr = result[0].map((item, index) => {
        return Object.assign({}, {
          'name': item,
          'value':item,
          'checked':false
        })
      })
      let workStatusArrValue = result[1].map((item, index) => {
        return Object.assign({}, {
          'name': item,
          'value':item,
          'checked':false
        })
      })
      this.setData({
        workStatusArr: workStatusArr,
        workStatusArrValue: workStatusArrValue
      })
    })
    tool.formDetails('he_company_nature').then(result => {
      this.setData({
        companyNatureArr: result[0],
        companyNatureArrValue: result[1]
      })
    })
    tool.formDetails('he_parents').then(result => {
      this.setData({
        parentsArr: result[0],
        parentsArrValue: result[1]
      })
    })
    tool.formDetails('he_father_work').then(result => {
      this.setData({
        fatherWorkArr: result[0],
        fatherWorkArrValue: result[1]
      })
    })
    tool.formDetails('he_mother_work').then(result => {
      this.setData({
        motherWorkArr: result[0],
        motherWorkArrValue: result[1]
      })
    })
    tool.formDetails('he_parent_assets').then(result => {
      this.setData({
        parentAssetsArr: result[0],
        parentAssetsArrValue: result[1]
      })
    })
    tool.formDetails('he_composition').then(result => {
      let compositionArr = result[0].map((item, index) => {
        return Object.assign({}, {
          'name': item,
          'value':item,
          'checked':false
        })
      })
      let compositionArrValue = result[1].map((item, index) => {
        return Object.assign({}, {
          'name': item,
          'value':item,
          'checked':false
        })
      })
      this.setData({
        compositionArr: compositionArr,
        compositionArrValue: compositionArrValue
      })
    })
  },
  // 上传头像
  uploadPhoto() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['', 'camera'],
      success: (res) => {
        console.log(res)
        let path = res.tempFilePaths[0];
        console.log(path)
        this.setData({
          carWin_img: path
        })
        this.toCos();
      }
    })
  },
  // 传cos
  toCos() {
    var Bucket = 'yuehe-1257653330';
    var Region = 'ap-beijing';
    var ForcePathStyle = false;
    var prefix = 'https://' + Bucket + '.cos.' + Region + '.myqcloud.com/';
    if (ForcePathStyle) {
      prefix = 'https://cos.' + Region + '.myqcloud.com/' + Bucket + '/';
    }
    var stsCache;
    var getCredentials = function (callback) {
      if (stsCache && Date.now() / 1000 + 30 < stsCache.expiredTime) {
        callback(data.credentials);
        return;
      }
      wx.request({
        method: 'POST',
        url: app.globalData.publicUrl + '/wx/member/' + this.data.openid + '/getCosSts',
        // dataType: 'json',
        success: function (result) {
          console.log(result, '222222222222')
          var credentials = result.data.credential.credentials;
          if (credentials) {
            stsCache = result.data.credential
          } else {
            wx.hideLoading()
            wx.showModal({
              title: '临时密钥获取失败',
              content: JSON.stringify(data),
              showCancel: false
            });
          }
          callback(stsCache && stsCache.credentials);
        },
        error: function (err) {
          wx.hideLoading()
          wx.showModal({
            title: '临时密钥获取失败',
            content: JSON.stringify(err),
            showCancel: false
          });
        }
      });
    };
    // 计算签名
    var getAuthorization = function (options, callback) {
      getCredentials(function (credentials) {
        callback({
          XCosSecurityToken: credentials.sessionToken,
          Authorization: COS({
            SecretId: credentials.tmpSecretId,
            SecretKey: credentials.tmpSecretKey,
            Method: options.Method,
            Pathname: options.Pathname,
          })
        });
      });
    };
    // 上传文件
    var Key = this.data.carWin_img.substr(this.data.carWin_img.lastIndexOf('/') + 1); // 这里指定上传的文件名
    var signPathname = '/';
    if (ForcePathStyle) {
      signPathname = '/' + Bucket + '/';
    }
    getAuthorization({
      Method: 'POST',
      Pathname: signPathname
    }, (AuthData) => {
      var requestTask = wx.uploadFile({
        url: prefix,
        name: 'file',
        filePath: this.data.carWin_img,
        formData: {
          'key': "face/" + Key,
          'success_action_status': 200,
          'Signature': AuthData.Authorization,
          'x-cos-security-token': AuthData.XCosSecurityToken,
          'Content-Type': '',
        },
        success: (res) => {
          console.log(res.header.Location)
          let photo = 'form.photo'
          this.setData({
            [photo]: res.header.Location
          })
          // this.tj(params, res.header.Location)
        },
        fail: function () {
          wx.hideLoading()
          wx.showModal({
            title: '上传失败',
            showCancel: false
          });
        }
      });
      requestTask.onProgressUpdate(function (res) {
        console.log('进度:', res.progress);
      });
    });
  }
})