// pages/member/info/info.js
var app = getApp();
import uitil from '../../../utils/util.js';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    code:'',
    info:{},
    avatar_image: '',
    nickname: '',//用户名
    _nickname:'',//昵称
    fileList:[],
    change_hidden:true,
    //个人信息
    info_form: {
      realname: '', //用户姓名
      telephone: '', //联系电话
      mobile: '', //绑定电话
      wx: '', //微信
      alipay: '', //支付宝
      birthday: '', //生日
      alipay_name: '', //支付宝名字
      gender: '', //性别 0未定义 1男 0女
      avatar: '', //头像
      province_name: '', //省
      city_name: '', //市
      area_name: '', //区
      province: '', //省ID
      city: '', //市ID
      area: '', //区ID
      address: '',//详细地址,
      nickname:""//昵称
    },
    sexName: '',
    isShowSex: false,
    isShowAddress: false,
    districtName: '',
    isShowBirthday: false,
    //手机 btn
    bind_btn: '',
    //自定义参数
    is_custom: false,
    custom_title: '', //自定义title
    custom_value: '', //自定义值
    isForm: false,
    customDatas: [],
    //余额支付密码是否开启
    isBalancePwd: false,
    //性别----
    showSex: false,
    sexItems: [
      {
        name: '男'
      },
      {
        name: '女'
      },
    ],
    birthdayShow: false,
    minDate: new Date(1900, 1, 1).getTime(),
    maxDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    currentDate_1: new Date().getTime(),
    date: uitil.formatTime(new Date()).substring(0, 10),
    //地区
    showAdd: false,
    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],
    selectAddressData: [],
    is_open_converge_pay: false, //判断是否开启汇聚支付
    formOpen: false, // 开启必填自定义字段
    formEdit: false, // 自定义字段是否可编辑
    // 是否开启账号注销功能
    memberCancel: false,
    // 登录后才显示微信号，支付宝信息，银行卡信息
    lofgin_show:false,
    //开启/关闭修改头像、昵称
    change_info:false 
  },
  bindDateChange(e) {
    console.log(e.detail.value);
    this.setData({
      'info_form.birthday': e.detail.value
    });
  },
  deletePhoto(){
      this.setData({fileList:[]})
  },
  //头像上传
  afterRead(event){
    let {file} = event.detail;
    let urlStr = app.getNetAddresss('upload.uploadPic');
    wx.uploadFile({
      url: urlStr, 
      filePath: file.url,
      name: 'file',
      formData: null,
      success:(res)=> {
        console.log(JSON.parse(res.data))
        let _res =JSON.parse(res.data);
        this.setData({
          fileList:[{url:_res.data.img_url}],
          "info_form.avatar":_res.data.img_url
        })
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {},

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this._init();
    //加载地址数据初始化
    this._initAddressInfo();
    //获取信息
    this._getMemberInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.setData({
      change_hidden:false
    })
  },

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

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {},
  // getCode(){
  //   let that=this
  //   wx.getUserInfo({
  //     success: function (_info) {
  //             that.setData({
  //               info:_info
  //             })
  //             console.log(_info)
  //             that.updateInfo()
  //           },
  //           fail: function (res) {
  //             console.log('错误信息:::' + res.errMsg)
  //           }
  //         })
     
  // },
  getUserProfileTap(){
    let that = this;
    wx.getUserProfile({
      desc:'获取用户信息',
      success:function(_info){
        console.log("info:", _info);
        let is_info = {
          'nickName' : _info.userInfo.nickName,
          'avatarUrl' : _info.userInfo.avatarUrl,
          'gender' : _info.userInfo.gender
        };
        that.setData({
          info:is_info
        });
        that.updateInfo();
      },
      fail:function(err){
        console.log(err);
      }
    });
  },
  updateInfo() {
    let that = this;
    let urlStr = app.getNetAddresss('member.member-update.index');
    app._postNetWork({
      url: urlStr,
      data: {
        type: 2,
        info:that.data.info,
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
          that._getMemberInfo();
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //获取信息
  _getMemberInfo() {
    let that = this;
    let urlStr = app.getNetAddresss('member.member.getUserInfo');
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let is_open_converge_pay = false;
          let formOpen = false;
          let formEdit = false;
          let formName = false;
          if(that.data.change_hidden){
            that.setData({fileList:[{url:res.data.avatar_image,isImage: true}],'_nickname':res.data.nickname})
          }
          that.setData({nickname:res.data.nickname,change_info:res.data.change_info})
          if (res.data.is_open_converge_pay == 1) {
            is_open_converge_pay = true;
          } else {
            is_open_converge_pay = false;
          }
          if (res.data.myform && res.data.myform.base) {
            formOpen = (res.data.myform.base.form_open == "1" ? true : false);
            formEdit = (res.data.myform.base.form_edit == "1" ? true : false);
            formName = (res.data.myform.base.name == "1" ? true : false);
          }
          if(res.data.name_must){
            that.setData({
              name_must:res.data.name_must == '1'?true:false
            });
          }
          that.setData({
            is_open_converge_pay,
            formOpen,
            formEdit,
            formName,
            lofgin_show:true
          });
          that._initData(res.data);
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //初始化个人信息
  _initData(data) {
    this.setData({
      avatar_image: data.avatar_image
    });
    this.setData({
      nickname: data.nickname
    });
    this._initSex(data);
    this.setData({
      'info_form.wx': data.wechat
    });
    this.setData({
      'info_form.realname': data.realname
    });
    this._initAliPay(data);
    this._initDistrict(data, '');
    this.setData({
      'info_form.avatar': data.avatar,
      memberCancel: data.member_cancel_status
    });
    this._initBirthday(data);
    this._initMobile(data);

    this._initCustomData(data);

    this._initCustomForm(data);

    this._getBalancePawInfo();
  },
  //初始化性别
  _initSex(data) {
    if (data.myform.base) {
      this.setData({
        isShowSex: data.myform.base.sex == 1 ? true : false //设置是否显示
      });
    }
    if (data.gender == 1) {
      this.setData({
        'info_form.gender': '1',
        sexName: '男'
      });
    } else if(data.gender == 2) {
      this.setData({
        'info_form.gender': '2',
        sexName: '女'
      });
    } else {
      this.setData({
        'info_form.gender': '0',
        sexName: '未定义'
      }); 
    }
  },
  //支付宝
  _initAliPay(data) {
    this.setData({
      'info_form.alipay': data.alipay,
      'info_form.alipay_name': data.alipay_name
    });
  },
  //初始化城市
  _initDistrict(data, district) {
    console.log(app._isTextEmpty(data.myform));
    if (!app._isTextEmpty(data)) {
      if (!app._isTextEmpty(data.myform.form)) {
        this.setData({
          isShowAddress: data.myform.base.address == 1 ? true : false
        });
      }
      this.setData({
        'info_form.province': data.province,
        'info_form.province_name': data.province_name,
        'info_form.city': data.city,
        'info_form.city_name': data.city_name,
        'info_form.area': data.area,
        'info_form.area_name': data.area_name,
        districtName:
          data.province_name + ' ' + data.city_name + ' ' + data.area_name,
        'info_form.address': data.address
      });
      return;
    }

    if (!app._isTextEmpty(district)) {
      this.setData({
        'info_form.province': district.itemValue1,
        'info_form.province_name': district.itemName1,
        'info_form.city': district.itemValue2,
        'info_form.city_name': district.itemName2,
        'info_form.area': district.itemValue3,
        'info_form.area_name': district.itemName3
      });
      this.setData({
        districtName:
          district.itemName1 +
          ' ' +
          district.itemName2 +
          ' ' +
          district.itemName3
      });
    }
  },
  //初始化生日
  _initBirthday(data) {
    if (data.myform.base) {
      this.setData({
        isShowBirthday: data.myform.base.birthday == 1 ? true : false
      });
    }
    let time = new Date(data.birthday);
    let changetime = time.getTime();
    this.setData({
      'info_form.birthday': data.birthday,
      currentDate: changetime
    });
  },
  //初始化手机 绑定 修改 显示
  _initMobile(data) {
    this.setData({
      'info_form.mobile': data.mobile
    });
    if (!app._isTextEmpty(this.data.info_form.mobile)) {
      this.setData({
        bind_btn: '修改手机'
      });
    } else {
      this.setData({
        bind_btn: '绑定手机'
      });
    }
  },
  //初始化自定义数据
  _initCustomData(data) {
    if (!app._isTextEmpty(data.yz_member)) {
      this.setData({
        custom_value: data.yz_member.custom_value
      });
      this._getMemberInfo2(this.data.custom_value); //获取自定义数据
    }
  },
  //获取自定义数据
  _getMemberInfo2(value) {
    let that = this;
    let urlStr = app.getNetAddresss('member.member.get-custom-field');
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            is_custom: res.data.is_custom == '1' ? true : false,
            custom_title: res.data.custom_title
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //初始化自定义表单
  _initCustomForm(data) {
    if (app._isTextEmpty(data.myform) || app._isTextEmpty(data.myform.form)) {
      this.setData({
        isForm: false
      });
      return;
    }
    if (data.myform.form.length == 0) {
      this.setData({
        isForm: false
      });
      return;
    }
    this.setData({
      isForm: true
    });
    this.setData({
      customDatas: data.myform.form
    });
  },
  //获取余额支付密码是否设置
  _getBalancePawInfo() {
    let that = this;
    let urlStr = app.getNetAddresss('member.balance-password.is-use');
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            isBalancePwd: res.data.is_use
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  nicknameChange(e){
    this.setData({
      '_nickname':e.detail.value
    })
  },
  //姓名值绑定
  realnameinp(e) {
    let val = e.detail.value;
    this.setData({
      'info_form.realname': val
    });
  },
  //绑定手机
  bindTel() {
    wx.navigateTo({
      url:
        '/packageA/member/editmobile/editmobile?num=' +
        this.data.info_form.mobile +
        '&fromApp=2&editType=1'
    });
    wx.setStorage({
      key: 'isset',
      data: 1
    });
  },
  //显示性别设置
  showSexInfo() {
    this.setData({
      showSex: true
    });
  },
  sexSelectBtn(e) {
    let val = e.detail.name;
    console.log(val);
    if (val == '男') {
      this.setData({
        'info_form.gender': '1',
        sexName: '男'
      });
    } else if (val == '女') {
      this.setData({
        'info_form.gender': '2',
        sexName: '女'
      });
    }
    this.setData({
      showSex: false
    });
  },
  sexClose() {
    this.setData({
      showSex: false
    });
  },
  //生日选择
  openPicker() {
    this.setData({
      birthdayShow: true
    });
  },
  birthdayClose() {
    this.setData({
      birthdayShow: false
    });
  },
  birthdayChange(event) {
    let time = event.detail;
    this.setData({
      currentDate: time
    });
  },
  timestampToTime(timestamp) {
    var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M =
      (date.getMonth() + 1 < 10
        ? '0' + (date.getMonth() + 1)
        : date.getMonth() + 1) + '-';
    var D = date.getDate();
    return Y + M + D;
  },
  // birthdayconfirm(e) {
  // 	let time = e.detail;
  // 	let changtime = this.timestampToTime(time);
  //   console.log(changtime)
  // 	this.setData({
  // 		"info_form.birthday": changtime,
  // 		birthdayShow: false
  // 	})
  // },
  //微信号值绑定
  wxinp(e) {
    let val = e.detail.value;
    this.setData({
      'info_form.wx': val
    });
  },
  //支付宝账号值绑定
  alipayinp(e) {
    let val = e.detail.value;
    this.setData({
      'info_form.alipay': val
    });
  },
  //支付宝账号姓名
  alipayNameinp(e) {
    let val = e.detail.value;
    this.setData({
      'info_form.alipay_name': val
    });
  },
  //所在地选择显示
  showAddBtn() {
    this.setData({
      showAdd: true
    });
  },
  // 关闭选择收货地址
  _closeDateLw: function() {
    this.setData({
      showAdd: false
    });
  },
  //地址选择器数据初始化
  _initAddressInfo: function() {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function(res) {
        console.log('地址信息准备就绪');
        that._getProvinceData();
      },
      fail: function(res) {
        console.log('省fail');
        app._getNetWork({
          url: app.getNetAddresss('member.member-address.address'),
          success: function(res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: 'provinceData',
              data: province
            });
            wx.setStorage({
              key: 'cityData',
              data: city
            });
            wx.setStorage({
              key: 'districtData',
              data: district
            });
            that._initAddressInfo();
          },
          fail: function(res) {},
          state: true
        });
      }
    });
  },
  // 读取省key
  _getProvinceData: function() {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function(res) {
        console.log('省读取成功', res.data);
        that.setData({
          provinceData: res.data
        });
        that.setData({
          'selectAddressData[0].name':
            res.data[that.data.pickerValue[0]].areaname,
          'selectAddressData[0].id': res.data[that.data.pickerValue[0]].id,
          'selectAddressData[0].index': that.data.pickerValue[0]
        });
        that._getCityData();
      }
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function() {
    var _data = this.data.selectAddressData[0];
    console.log('城市', '_data', _data);
    var that = this;
    var _keyName = 'cityData';
    wx.getStorage({
      key: _keyName,
      success: function(res) {
        console.log('城市读取成功', res);

        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log('城市数据筛选', _json);
        that.setData({
          cityData: _json
        });
        that.setData({
          'selectAddressData[1].name': _json[that.data.pickerValue[1]].areaname,
          'selectAddressData[1].id': _json[that.data.pickerValue[1]].id,
          'selectAddressData[1].index': that.data.pickerValue[1]
        });
        that._getDistrictData();
      }
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function() {
    var _data = this.data.selectAddressData[1];
    console.log('地区', '_data', _data);
    console.log(_data);
    var that = this;
    var _keyName = 'districtData';
    wx.getStorage({
      key: _keyName,
      success: function(res) {
        console.log('地区读取成功');
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log('地区数据筛选', _json);
        that.setData({
          districtData: _json
        });
        console.log('districtData', _json);
        that.setData({
          'selectAddressData[2].name': _json[that.data.pickerValue[2]].areaname,
          'selectAddressData[2].id': _json[that.data.pickerValue[2]].id,
          'selectAddressData[2].index': that.data.pickerValue[2]
        });
        console.log('over', that.data.selectAddressData);
      }
    });
  },
  // 收货地址滚动事件
  bindChange: function(e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      'pickerValue[0]': val[0],
      'pickerValue[1]': val[1],
      'pickerValue[2]': val[2]
    });
    this._initAddressInfo();
  },
  //城市结果
  resultAdd: function() {
    let seleData = this.data.selectAddressData;
    let district = {
      itemValue1: seleData[0].id,
      itemName1: seleData[0].name,
      itemValue2: seleData[1].id,
      itemName2: seleData[1].name,
      itemValue3: seleData[2].id,
      itemName3: seleData[2].name
    };
    this._initDistrict('', district);
    this._closeDateLw();
  },
  //详细地址值绑定
  addressinp(e) {
    let val = e.detail.value;
    this.setData({
      'info_form.address': val
    });
  },
  //其他信息值绑定
  cItemInp(e) {
    let citemidx = e.currentTarget.dataset.citemidx;
    let val = e.detail.value;
    console.log(this.data.customDatas);
    this.setData({
      ['customDatas[' + citemidx + '].value']: val
    });
  },
  //银行卡
  editBank() {
    wx.navigateTo({
      url: '/packageA/member/memberBank/memberBank'
    });
  },
  //余额支付密码设置
  editBalancePwd() {
    // let that = this;
    let urlStr = app.getNetAddresss('member.balance-password.is-has-password');
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (res.data.is_has) {
            wx.navigateTo({
              url: '/packageA/member/balance_password/balance_password'
            });
          } else {
            wx.navigateTo({
              url: '/packageA/member/set_balance_password/set_balance_password'
            });
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //编辑自定义字段
  editCustom() {
    if (app._isTextEmpty(this.data.custom_value)) {
      //跳转自定义界面 info_costom
      wx.navigateTo({
        url: '/packageA/member/info_costom/info_costom'
      });
    } else {
      return;
    }
  },
  //开户信息
  // gotoBankCash() {
  //   wx.navigateTo({
  //     url: '/packageA/member/AccoutInfo/AccoutInfo'
  //   });
  // },
  // 跳转汇聚账户信息
  editUSer() {
    wx.navigateTo({
      url: '/packageA/others/HJinfo/bankCardInformation/bankCardInformation'
    });
  },
  //提交个人信息
  submitInfo() {
    let that = this;
    that.setData({
      'info_form.customDatas': this.data.customDatas,
      'info_form.avatar':this.data.fileList[0].url,
      'info_form.nickname':this.data._nickname
    });
    if (that.data.formOpen && (that.data.customDatas instanceof Array)) {
      let result = that.data.customDatas.every((item) => {return (item.value != "");});
      if (!result) {
        wx.showToast({
          title: '请先填写自定义信息',
          icon: "none"
        });
        return;
      }
    }
    let urlStr = app.getNetAddresss('member.member.updateUserInfo');
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: {
        data: this.data.info_form
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500,
            success: function() {
              setTimeout(function() {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1
                });
              }, 1500); //延迟时间
            }
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {}
    });
  },
  _init() {
    this.setData({
      //个人信息
      info_form: {
        realname: '', //用户姓名
        telephone: '', //联系电话
        mobile: '', //绑定电话
        wx: '', //微信
        alipay: '', //支付宝
        birthday: '', //生日
        alipay_name: '', //支付宝名字
        gender: '', //性别 0未定义 1男 2女
        avatar: '', //头像
        province_name: '', //省
        city_name: '', //市
        area_name: '', //区
        province: '', //省ID
        city: '', //市ID
        area: '', //区ID
        address: '' //详细地址
      },
      sexName: '',
      isShowSex: false,
      isShowAddress: false,
      districtName: '',
      isShowBirthday: false,
      //手机 btn
      bind_btn: '',
      //自定义参数
      is_custom: false,
      custom_title: '', //自定义title
      custom_value: '', //自定义值
      isForm: false,
      customDatas: [],
      //余额支付密码是否开启
      isBalancePwd: false,
      //性别----
      showSex: false,
      sexItems: [
        {
          name: '男'
        },
        {
          name: '女'
        }
      ],
      birthdayShow: false,
      minDate: new Date(1900, 1, 1).getTime(),
      maxDate: new Date().getTime(),
      currentDate: new Date().getTime(),
      //地区
      showAdd: false,
      provinceData: [],
      cityData: [],
      districtData: [],
      pickerValue: [0, 0, 0],
      selectAddressData: []
    });
  },
  goMemberCancel () {
    wx.navigateTo({
      url: '/packageI/member_cancel/member_cancel'
    });
  },

  // 退出登录
  LogOutLogin(){
    wx.removeStorageSync("nickname");
    wx.removeStorageSync("session");
    wx.removeStorageSync("wx_token");
    wx.removeStorageSync("storeMessage");

    wx.navigateTo({
      url: '/packageG/member_v2/member_v2'
    });
  }



});
