// pages/newQuanzi/newQuanzi.js
import Dialog from '../../dist/dialog/dialog';
import Notify from '../../dist/notify/notify';

var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    circleId: 0,
    title: '',
    needCheck: false,
    servicePlace: '',

    isChangeFrontImg:false,
    fileList: [],
    frontImage: '',
    comment:"",

    deleteDialog:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log(options)
    if (options.circleId!=0){
      this.setData({
        circleId: options.circleId
      })
    }
    // var location = wx.getStorageSync('location');
    
    var config = wx.getStorageSync('config');
    wx.request({
      url: app.url +'ajax_get_circle_info.php',
      data:{
        unionId:config.unionId,
        circleId: options.circleId
      },
      success(res){
        console.log(res.data)
        if(res.data.status='OK'){
          var place = res.data.result.circleDat.province + res.data.result.circleDat.city + res.data.result.circleDat.district
          that.setData({
            servicePlace: place,
            title:res.data.result.circleDat.title,
            needCheck:res.data.result.circleDat.need_check,
            comment: res.data.result.circleDat.comment,
            fileList: [{ url: res.data.result.circleDat.front_image }],
          })
        }
      }
    })
  },

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

  },

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

  },

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

  },

  //判断上传的图片类型
  beforeRead(event) {
    const { file, callback } = event.detail;
    if (file[0].path.indexOf('jpg') < 0) {
      wx.showToast({ title: '请选择jpg图片上传', icon: 'none' });
      callback(false);
      return;
    }
    callback(true);
  },
  afterRead(event) {
    const { file } = event.detail;
    const fileList = this.data[`fileList`];
    this.setData({
      [`fileList`]: fileList.concat(file),
      frontImage: file[0].path
    });
  },
  delete(event) {
    const { index, name } = event.detail;
    const fileList = this.data[`fileList`];
    fileList.splice(index, 1);
    this.setData({
       [`fileList`]: fileList,
      isChangeFrontImg:true
       });
  },

  //获取圈子名称
  onInputTitle(event) {
    this.setData({
      title: event.detail
    })
  },

  //获取是否需要入圈审核
  onChangeNeedCheck({ detail }) {
    // 需要手动对 checked 状态进行更新
    this.setData({
      needCheck: detail
    });
  },

  //获取圈子简介
  onInputComment(event) {
    this.setData({
      comment: event.detail.value
    })
  },

  //删除圈子
  deleteCircle() {
    //显示删除对话框
    this.setData({
      deleteDialog: true
    })
    return
    
    //跳转到上传凭证页面
    Dialog.confirm({
      title: '',
      message: '是否删除圈子以及相关数据?'
    }).then(() => {

    }).catch(() => {

    });
  },

  //取消删除圈子
  cancelDelete() {
    this.setData({
      deleteDialog: false
    })
  },

  //确认删除圈子
  confirmDelete() {
    var that = this;
    var config = wx.getStorageSync('config');
    //调用删除接口
    wx.request({
      url: app.url + 'ajax_delete_circle.php',
      data: {
        unionId: config.unionId,
        circleId: that.data.circleId,
        zIndex: 100
      },
      header: { 'content-type': 'application/json' },
      method: 'GET',
      dataType: 'json',
      success: function (res) {
        console.log(res)
        if (res.statusCode == 200) {
          if (res.data.status == "OK") {
            //删除成功以后跳转到圈子模块首页
            wx.switchTab({
              url: '../circle/circle',
            })
          } else {
            Notify(res.data.message)
            return
          }
        }
      },
      fail: function (res) { },
      complete: function (res) {
        that.setData({
          deleteDialog: false
        })
      },
    })

  },

  //提交数据【编辑】
  editCircle() {
    var that = this;
    var config = wx.getStorageSync('config');
    var location = wx.getStorageSync('location');
    if (that.data.title == null || that.data.title.trim() == "") {
      Notify('请输入圈子名称')
      return
    }
    if (location == null || location.latitude == null) {
      Notify('请重新定位位置')
      return
    }

    if (that.data.comment == null || that.data.comment.trim() == "") {
      Notify('请输入圈子简介')
      return
    }

    if (that.data.fileList.length == 0) {
      Notify('请上传圈子封面')
      return
    }

    //提交数据
    wx.request({
      url: app.url + 'ajax_circle_edit.php',
      data: {
        unionId: config.unionId,
        latitude: location.latitude,
        longitude: location.longitude,
        province: location.province,
        city: location.city,
        district: location.district,
        title: that.data.title,
        comment: that.data.comment,
        needCheck: that.data.needCheck,
        circleId:that.data.circleId
      },
      header: { 'content-type': 'application/json' },
      method: 'GET',
      dataType: 'json',
      success: function (res) {
        console.log(res)
        if (res.statusCode == 200) {
          if (res.data.status == "OK" && that.data.isChangeFrontImg==true) {
            var filePath = that.data.fileList[0].path;
            //上传头像
            wx.uploadFile({
              url: app.url + 'ajax_circle_edit.php?unionId=' + config.unionId + '&circleId=' + that.data.circleId,
              filePath: filePath,
              name: 'frontImage',
              success: function (resp1) {
                //成功以后跳转到下一页面[圈子动态]
                wx.redirectTo({
                  url: '../newCircleMoment/newCircleMoment?circleId=' + that.data.circleId,
                })
              },
              fail: function (err) {
                console.log(err)
              }
            })
          } else {
            //跳转到圈子首页
            wx.navigateTo({
              url: '../circleDetails/circleDetails?circleId=' + that.data.circleId,
            })
          }
        }
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  //重新定位
  reLocation() {
    var config = wx.getStorageSync('config');
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        // console.log(res);
        var latitude = res.latitude;
        var longitude = res.longitude;
        let location = {
          latitude: res.latitude,
          longitude: res.longitude
        };
        wx.setStorage({
          key: 'location',
          data: location,
        })
        wx.request({
          url: app.url + 'ajax_get_location_place.php',
          data: {
            unionId: config.unionId,
            latitude: latitude,
            longitude: longitude
          },
          header: { 'content-type': 'application/json' },
          method: 'GET',
          dataType: 'json',
          success: function (res) {
            that.setData({
              servicePlace: res.data.result.province + res.data.result.city + res.data.result.district,
            })
            //保存最新地理位置信息
            location.province = res.data.result.province,
              location.city = res.data.result.city,
              location.district = res.data.result.district,
              wx.setStorage({
                key: 'location',
                data: location,
              })
          },
          fail: function (res) { },
          complete: function (res) { },
        })
      }
    })
  }
})