// pages/member/rankingListSecond/rankingListSecond.js
var app = getApp();
let time = 0;
let timer = null;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    language: '',
    card_id: '',
    chooseItem: [],
    // 录音
    showStart: false,
    localId: '',
    serverId: '',
    downLoadId: '',
    time: 0,
    timer: null,

    // 地址
    // district: District, // 地址本地数据
    pictures: [],
    form: {
      status: '1',
      member_id: '',
      card_avatar: '',
      card_name: '',
      card_mobile: '',
      card_wechat: '',
      role_name: '',
      role_id: '', // 角色ID
      introduction: '', // 简介
      voice: '',
      province: '',
      city: '',
      district: '',
      street: '',
      address: '',
      picture: [],
      goods_id: [],
      addressName: '', // 地址区域
      streetName: '',
      isOldVoice: false,
      company:''
    },

    addressShow: false,

    strShow: false, // 街道显示
    streetShow: false, // 街道pop

    // 角色
    showRole: false,
    columns: [],
    role: {},

    // 图片
    photosize: 1024 * 1024 * 4,
    imageUrl: '',
    fileList2: [],
    Timestart: 0,
    onFocus: false, // textarea焦点是否选中
    isShowText: false // 控制显示 textarea 还是 text
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      card_id: options.card_id
    });

    if (options.isShow) {
      this.setData({
        isShow: options.isShow
      });
    } else {
      this.setData({
        isShow: false
      });
    }
    this.getData();
    this.getRole();

    var that = this;
    this.recorderManager = wx.getRecorderManager();
    this.recorderManager.onError(function () {
      that.tip('录音失败！');
    });
    this.recorderManager.onStop(function (res) {
      that.setData({
        src: res.tempFilePath,
        localId: res.tempFilePath
      });
      console.log(res.tempFilePath, '上传的路径');
      that.tip('录音完成！');
      that.upVoice();
    });

    this.innerAudioContext = wx.createInnerAudioContext();
    this.innerAudioContext.onError((res) => {
      that.tip('播放录音失败！');
    });
  },
  bindRegionChange: function (e) {
    console.log(e);
    if (e.detail.code[1] == '441900'){
      e.detail.value[2] = "东莞市";
      e.detail.code[2] = "659004523";
      this.setData({
        region: e.detail.value
      });
    }else{
      this.setData({
        'form.province': e.detail.code[0],
        'form.city': e.detail.code[1],
        'form.district': e.detail.code[2]
      });
      this.setData({
        region: e.detail.value
      });
    }
    this.setData({
      addressShow: false,
      'form.addressName': e.detail.value[0] + e.detail.value[1] + e.detail.value[2],
      'form.streetName': '',
      'form.street': ''
    });
    this.getStreet(e.detail.code[2]);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({ 'language': language.en});
    this.audioCtx = wx.createAudioContext('yp');
  },

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

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

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

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多了');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  /**
  * 提示
  */
  tip: function (msg) {
    wx.showModal({
      title: '提示',
      content: msg,
      showCancel: false
    });
  },
  checkRole() {
    this.setData({
      showRole: true
    });
  },
  checkoutAdress() {
    this.setData({
      addressShow: true
    });
  },
  // 角色取消
  onCancel() {
    this.setData({
      showRole: false
    });
  },
  // 角色确定
  onConfirm(e) {
    for (var i in this.data.columnsObj) {
      if (this.data.columnsObj[i] == e.detail.value) {
        this.setData({
          showRole: false,
          'form.role_name': e.detail.value,
          'form.role_id': i
        });
      }
    }
  },
  // 地址取消
  checkClose() {
    this.setData({
      addressShow: false
    });
  },
  // 地址确定
  checkClick(val) {
    let adrVal = val.detail.values;
    let name = '';
    adrVal.forEach(item => {
      name += item.name;
    });
    this.setData({
      'form.province': adrVal[0].code,
      'form.city': adrVal[1].code,
      'form.district': adrVal[2].code
    });
    this.getStreet(adrVal[2].code);
    this.setData({
      addressShow: false,
      'form.addressName': name,
      'form.streetName': '',
      'form.street': ''
    });
  },
  // 上传图片
  onRead() {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        that.upload(that, tempFilePaths);
      }
    });
  },
  upload(page, path) {
    let wx_token = wx.getStorageSync('wx_token');
    let session = wx.getStorageSync('session');
    let urlStr = app.getNetAddresss('plugin.business-card.frontend.controllers.card.card.upload');
    urlStr += '&3rd_session=' + session;
    wx.showToast({
      icon: 'loading',
      title: '正在上传'
    }),
    wx.uploadFile({
      url: urlStr,
      filePath: path[0],
      name: 'file',
      formData: {
        // 和服务器约定的token, 一般也可以放在header中
        '_wx_token': wx.getStorageSync('wx_token')
      },
      header:{
        "Content-Type": "multipart/form-data",
        Cookie: "PHPSESSID=" + wx_token,
      },
      success: (res) => {
        let data = JSON.parse(res.data);
        if (data.result == 1) {
          this.setData({
            'form.card_avatar': data.data.img_url
          });
        } else {
          wx.showModal({
            title: '提示',
            content: data.msg,
            showCancel: false
          });
        }
      },
      fail: function (e) {
        console.log(e);
        wx.showModal({
          title: '提示',
          content: '上传失败',
          showCancel: false
        });
      },
      complete: function () {
        wx.hideToast(); // 隐藏Toast
      }
    });
  },
  onRead_1() {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        that.upload2(that, tempFilePaths);
      }
    });
  },
  upload2(page, path) {
    let wx_token = wx.getStorageSync('wx_token');
    let session = wx.getStorageSync('session');
    let urlStr = app.getNetAddresss('plugin.business-card.frontend.controllers.card.card.upload');
    urlStr += '&3rd_session=' + session;
    wx.showToast({
      icon: 'loading',
      title: '正在上传'
    }),
    wx.uploadFile({
      url: urlStr,
      filePath: path[0],
      name: 'file',
      formData: {
        // 和服务器约定的token, 一般也可以放在header中
        '_wx_token': wx.getStorageSync('wx_token')
      },
      header:{
        "Content-Type": "multipart/form-data",
        Cookie: "PHPSESSID=" + wx_token,
      },
      success: (res) => {
        let data = JSON.parse(res.data);
        if (data.result == 1) {
          let picture = this.data.form.picture;
          picture.push(data.data.img_url);
          page.setData({ // 上传成功修改显示头像
            'form.picture': picture,
            pictures: picture
          });
        } else {
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          });
        }
      },
      fail: function (e) {
        console.log(e);
        wx.showModal({
          title: '提示',
          content: '上传失败',
          showCancel: false
        });
      },
      complete: function () {
        wx.hideToast(); // 隐藏Toast
      }
    });
  },
  removeImg(e) {
    let index = e.target.dataset.index || e.currentTarget.dataset.index;
    let pictures = this.data.form.picture;
    pictures.splice(index, 1);
    this.setData({
      'form.picture': pictures
    });
  },
  getData() {
    let urlStr = app.getNetAddresss('plugin.business-card.frontend.controllers.card.card.index');
    urlStr += '&card_id=' + this.data.card_id;
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        var response = res.data;
        if (response.result == 1) {
          let data = response.data.card;
          if (app._isTextEmpty(data.voice)) {
            this.setData({
              isOldVoice: false
            });
          }else if (data.voice.indexOf('amr') != '-1') {
            this.setData({
              isOldVoice: false
            });
          }  else {
            this.setData({
              isOldVoice: true,
              'form.voice': data.voice
            });
          }
          if (!this.options.type) {
            if (app._isTextEmpty(this.data.form.street)) {
              this.getStreet(this.data.form.district);
            }
            wx.getStorage({
              key: 'chooseItem',
              success: res => {
                this.setData({
                  chooseItem: res.data
                });
              }
            });
            wx.getStorage({
              key: 'cardData',
              success: res => {
                this.setData({
                  form: res.data
                });
              }
            });
          } else {
            this.setData({
              'form.status': data.status,
              'form.member_id': data.member_id,
              'form.card_avatar': data.card_avatar,
              'form.card_name': data.card_name,
              'form.card_mobile': data.card_mobile,
              'form.card_wechat': data.card_wechat,
              'form.role_name': data.role_name,
              'form.role_id': data.role_id,
              'form.introduction': data.introduction,
              'form.address': data.address,
              'form.company': data.company,
            });
            var status = this.data.form.status;
            status = status.toString();
            this.setData({
              'form.status': status
            });
            if (data.areas[0]) {
              this.setData({
                'form.addressName': data.areas[0] + data.areas[1] + data.areas[2]
              });
            }
            if (data.areas[3]) {
              this.setData({
                'form.streetName': data.areas[3]
              });
            }
            this.setData({
              'form.province': data.area_id[0],
              'form.city': data.area_id[1],
              'form.district': data.area_id[2],
              'form.street': data.area_id[3],
              'form.address ': data.address
            });
            if (data.area_id[2]) {
              this.getStreet(data.area_id[2]);
            }
            if (!data.picture) {
              this.setData({
                'form.picture': []
              });
            } else {
              this.setData({
                'form.picture': data.picture
              });
            }
            this.setData({
              chooseItem: response.data.card_goods
            });
            // 把选择的商品保存在本地
            wx.setStorage({
              key: 'chooseItem',
              data: this.data.chooseItem
            });
          }
        } else {
          wx.showToast({
            title: response.msg,
            icon: 'none'
          });
          setTimeout(() => {
            wx.reLaunch({
              url: '/packageG/index/index'
            });
          }, 2000);
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getRole() {
    let urlStr = app.getNetAddresss('plugin.business-card.frontend.controllers.card.card.getRoles');
    urlStr += '&card_id=' + this.data.card_id;
    app._getNetWork({
      url: urlStr,
      success: (response) => {
        var res = response.data;
        if (res.result == 1) {
          let arr = [];
          this.setData({
            role: res.data
          });
          Object.keys(res.data).forEach(function (key) {
            arr.push(res.data[key]);
          });
          this.setData({
            columns: arr,
            columnsObj: res.data
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  streetChoose(e) {
    if (app._isTextEmpty(this.data.form.addressName)) {
      wx.showToast({
        title: '请先选择所在地区',
        icon: 'none'
      });
    } else {
      this.setData({
        streetShow: true
      });
    }
  },
  // 选择街道
  streetConfirm(e) {
    let item = e.target.dataset.item || e.currentTarget.dataset.item;
    this.setData({
      'form.streetName': item.areaname,
      'form.street': item.id,
      streetShow: false
    });
  },
  // 获取街道
  getStreet(param) {
    let urlStr = app.getNetAddresss('member.memberAddress.street');
    urlStr += '&district_id=' + param;
    app._getNetWork({
      url: urlStr,
      success: (response) => {
        var res = response.data;
        if (res.result == 1 && !app._isTextEmpty(res.data)) {
          if (
            !app._isTextEmpty(res.data) &&
            res.data.length > 0
          ) {
            this.setData({
              districtVal: res.data,
              strShow: true
            });
          } else {
            this.setData({
              strShow: false
            });
          }
        }else if(res.result==1 && app._isTextEmpty(res.data)){
          this.setData({
            strShow: false
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          });
          this.setData({
            strShow: false
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  setJSONData() {
    let card_id = this.data.card_id;
    this.setData({
      'form.card_id': card_id
    });
    let goods = [];
    for (let i = 0; i < this.data.chooseItem.length; i++) {
      goods.push(this.data.chooseItem[i].id);
    }
    this.setData({
      'form.goods_id': goods
    });
    if (
      this.data.form.role_id != '1' &&
      this.data.form.role_id != '2' &&
      this.data.form.role_id != '3' &&
      this.data.form.role_id != '6'
    ) {
      this.setData({
        'form.goods_id': []
      });
    }
  },
  // 删除商品
  deleteGoods(e) {
    let id = e.target.dataset.id || e.currentTarget.dataset.id;
    let data = this.data.chooseItem;
    for (let i = 0; i < data.length; i++) {
      if (data[i].id == id) {
        data.splice(i, 1);
      }
    }
    this.setData({
      chooseItem: data
    });
    wx.setStorage({
      key: 'chooseItem',
      data: this.data.chooseItem
    });
  },
  saveData(event) {
    if (!this.data.form.card_name) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }
    this.setJSONData();
    if (this.data.form.district == '441903'){
      this.data.form.district = '659004523';
    }
    console.log(this.data.form.district);
    let urlStr = app.getNetAddresss('plugin.business-card.frontend.controllers.card.card.edit');
    let form = this.data.form;
    wx.setStorage({
      key: 'streetName',
      data: form.streetName
    });
    app._postNetWork({
      url: urlStr,
      data: form,
      success: (response) => {
        var res = response.data;
        if (res.result == 1) {
          wx.setStorage({
            key: 'cardData',
            data: ''
          });
          wx.setStorage({
            key: 'chooseItem',
            data: ''
          });
          if (this.data.isShow == false) {
            wx.navigateBack({
              delta: 1
            });
          } else {
            wx.navigateBack({
              delta: 4
            });
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  onChangeName(e) {
    this.setData({
      'form.card_name': e.detail.value
    });
    console.log(this.data.form.card_name, 'name');
  },
  onChangePhone(e) {
    this.setData({
      'form.card_mobile': e.detail.value
    });
  },
  onChangeWechat(e) {
    this.setData({
      'form.card_wechat': e.detail.value
    });
  },
  onChangeCompany(e){
    console.log(e);
    this.setData({
      'form.company': e.detail.value
    });
  },
  onChangeAddress(e) {
    this.setData({
      'form.address': e.detail.value
    });
  },
  onChangeRadio(e) {
    let i = e.detail.toString();
    this.setData({
      'form.status': i
    });
  },
  onShowTextare() { // 显示textare

    this.setData({
      isShowText: true,
      onFacus: true
    });
  },
  onShowText() { // 显示text
    this.setData({
      isShowText: false,
      onFacus: false
    });
  },
  changeLine(e) {
    this.setData({
      'form.introduction': e.detail.value
    });
  },
  // 录音
  start() {
    this.setData({
      showStart: true
    });
    /**
   * 录制mp3音频
  */
    this.recorderManager.start({
      format: 'mp3'
    });
    time = 0;
    timer = setInterval(() => {
      time++;
      this.setData({
        time});
    }, 1000);
  },
  // 重新录音
  reloadVoice() {
    // this.start()
    this.setData({
      isOldVoice: false
    });
  },
  /**
  * 停止录音
  */
  stop() {
    this.setData({
      showStart: false
    });
    clearInterval(timer);
    this.setData({
      time: time,
    // 'form.voice': true,
    // isOldVoice: true
    });
    this.recorderManager.stop();
  },
  // 播放声音
  play() {
    if (app._isTextEmpty(this.data.form.voice)) {
      this.tip('请先录音！');
      return;
    }
    this.innerAudioContext.src = this.data.form.voice;
    this.innerAudioContext.play();
  },
  // 播放已有录音
  playAmr() {
    this.play();
  },
  upVoice() {
    let wx_token = wx.getStorageSync('wx_token');
    let session = wx.getStorageSync('session');
    let urlStr = app.getNetAddresss('plugin.business-card.frontend.controllers.card.card.uploadAudio');
    urlStr += '&3rd_session=' + session;
    wx.showToast({
      icon: 'loading',
      title: '正在上传'
    }),
    wx.uploadFile({
      url: urlStr,
      filePath: this.data.localId,
      name: 'file',
      header:{
        "Content-Type": "multipart/form-data",
        Cookie: "PHPSESSID=" + wx_token,
      },
      formData: {
        // 和服务器约定的token, 一般也可以放在header中
        '_wx_token': wx.getStorageSync('wx_token')
      },
      success: (res) => {
        var data = JSON.parse(res.data);
        if (data.result == 1) {
          wx.showModal({
            title: '提示',
            content: data.msg,
            showCancel: false
          });

          this.setData({
            'form.voice': data.data.audio_url
          });
        } else {
          wx.showModal({
            title: '提示',
            content: data.msg || '错误',
            showCancel: false,
            success: function (res) {}
          });
        }
        wx.hideToast();
      },
      fail: function (res) {
        console.log(res);
        wx.showModal({
          title: '提示',
          content: '网络请求失败，请确保网络是否正常',
          showCancel: false,
          success: function (res) {}
        });
      }
    });
  },
  toChooseGood() {
    wx.setStorage({
      key: 'cardData',
      data: this.data.form
    });
    wx.navigateTo({
      url: '/packageC/microshop/micro_shop_add_category/micro_shop_add_category' + '?formCard=' + this.data.card_id
    });
  },
  // 街道左侧按钮被点击的时候
  onClickLeft() {
    this.setData({
      streetShow: false
    });
  },
  areaConfirm(e){
    console.log(e);
    this.setData({
      addressShow: false,
      'form.province': e.detail[0].id,
      'form.city': e.detail[1].id,
      'form.district': e.detail[2].id,
      'form.addressName': e.detail[0].name + e.detail[1].name + e.detail[2].name,
      'form.streetName': '',
      'form.street': ''
    });

    this.getStreet(e.detail[2].id);
  },
});
