// packageH/circleCommunity/circleTopic/circleTopic.js

// packageC/micro_communities/microRelease/microRelease.js
var app = getApp();
var QQMapWX = require("../../../mymap/qqmap-wx-jssdk.min.js");
var qqmapsdk;
var clickTap = 0;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    language: "",
    height: "",
    /*地图数据*/
    point: {
      lat: "",
      lng: "",
    },
    city: "",
    address: "",
    suggestionshow: false,
    suggestion: [],
    /**/
    classificationshow: false,
    Locationshow: false,
    commodityTitle: "",
    addgoodslistshow: false,
    goodsdata: "",
    storeshow: false,
    storedata: "",
    protocolshow: false,
    photosize: 1024 * 1024 * 4, // 图片大小限制
    uploadUrl: "upload.uploadPic",
    catelist: [],
    catname: "",
    goodslistData: [],
    goodsisLoadMore: true,
    goodsPage: 1,
    goodsTotal: 0,
    selectgoodsData: {},
    storelistData: [],
    storePage: 1,
    storeTotal: 0,
    storeisLoadMore: true,
    selectstoreData: {},
    imgData: [],
    releasetitle: "",
    releasecontents: "",
    catid: "",
    releaseaddress: "",
    releasecity: "",
    releaselat: "",
    releaselnt: "",
    goodsId: "",
    storeId: "",
    checked: true,
    agreementcontent: "",
    goods_open: 0,
    store_open: 0,

    circleId: 0,
    stickid: 0, //代表修改
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.circleId && options.circleId != 0) {
      this.data.circleId = options.circleId;
    }
    if (options.stickId && options.stickId != 0) {
      this.data.stickid = options.stickId;
      this.getMicroCommentDetails();
    }
    if (!app.globalData.qqmapkey) {
      app._getTemplate().then((res) => {
        qqmapsdk = new QQMapWX({
          key: app.globalData.qqmapkey,
        });
        this.poscurrent();
      });
    } else {
      qqmapsdk = new QQMapWX({
        key: app.globalData.qqmapkey,
      });
      this.poscurrent();
    }

    this.getAgreement();
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          height: res.windowHeight - 70,
        });
      },
    });
  },

  removeImg(e) {
    let index = e.currentTarget.dataset.index;
    this.data.imgData.splice(index, 1);
    this.setData({
      imgData: this.data.imgData,
    });
  },

  poscurrent: function () {
    let that = this;
    wx.getSetting({
      success(resData) {
        if (!resData.authSetting["scope.userLocation"]) {
          wx.authorize({
            scope: "scope.userLocation",
            success() {},
            fail(msgData) {},
            complete() {},
          });
        }
      },
    });
    that.getlocaldata();
  },
  getlocaldata() {
    let that = this;
    wx.getLocation({
      type: "gcj02",
      success(res) {
        const latitude = res.latitude;
        const longitude = res.longitude;
        //    const speed = res.speed;
        //    const accuracy = res.accuracy;
        that._setaddressData({
          lat: latitude,
          lng: longitude,
        });
      },
      fail(err) {
        if (err.errMsg === "getLocation:fail auth deny") {
          console.log("当初用户拒绝，再次发起授权");
          wx.openSetting({
            success(settingdata) {
              if (settingdata.authSetting["scope.userLocation"]) {
                wx.showToast({
                  icon: "none",
                  title: "获取权限成功",
                  duration: 1500,
                });
                that.getlocaldata();
              } else {
                wx.showToast({
                  icon: "none",
                  title: "获取权限失败,定位需要用户授权",
                  duration: 1500,
                });
              }
            },
          });
        }
      },
    });
  },
  _setaddressData(e) {
    let that = this;
    qqmapsdk.reverseGeocoder({
      //位置坐标，默认获取当前位置，非必须参数
      location: {
        latitude: e.lat,
        longitude: e.lng,
      },
      sig: app.globalData.qqmapsig,
      success: function (res) {
        //成功后的回调
        console.log(res);
        that.setData({
          releaseaddress: res.result.address,
          releasecity: res.result.address_component.city ? res.result.address_component.city : res.result.address_component.province,
          releaselat: res.result.ad_info.location.lat,
          releaselnt: res.result.ad_info.location.lng,
          address_detail: "",
          Locationshow: false,
          point: {
            lat: res.result.ad_info.location.lat,
            lng: res.result.ad_info.location.lng,
          },
          city: res.result.address_component.city ? res.result.address_component.city : res.result.address_component.province,
          address: res.result.address,
        });
      },
      fail: function (error) {
        wx.showToast({
          duration: 3000,
          title: error.message,
          icon: "none",
        });
      },
      complete: function (res) {},
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({ language: language.en });
  },

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

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

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

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  onShareTimeline(){},
  getAgreement() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.circle.frontend.circle.get-set");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goods_open: res.data ? res.data.good_show : 0,
            store_open: res.data ? res.data.store_show : 0,
            agreementcontent: res.data ? res.data.user_control : "",
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  // 选择图片
  onRead() {
    let that = this;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: 9,
      sizeType: ["compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(res);
        for (let j = 0; j < tempFilePaths.length; j++) {
          wx.compressImage({
            src: tempFilePaths[j], // 图片路径
            quality: 60, // 压缩质量
            success(e) {
              console.log(e);
              let photourl = e.tempFilePath;
              wx.uploadFile({
                url: urlStr,
                filePath: photourl,
                name: "file",
                success(resdata) {
                  let res = JSON.parse(resdata.data);
                  if (res.result == 1) {
                    let imageUrl1 = res.data.img_url;
                    let imgData = that.data.imgData;
                    imgData.push(imageUrl1);
                    that.setData({
                      imgData: imgData,
                    });
                  } else {
                    wx.showToast({
                      icon: "none",
                      title: res.msg,
                      duration: 1500,
                    });
                  }
                },
              });
            },
            fail(e) {},
            complete(e) {},
          });
        }
      },
    });
  },
  releasetitleInp(e) {
    let val = e.detail.value;
    this.setData({
      releasetitle: val,
    });
  },
  releasecontentsInp(e) {
    let val = e.detail.value;
    this.setData({
      releasecontents: val,
    });
  },
  getClassification() {
    this.setData({
      classificationshow: true,
    });
    this.getClassificationData();
  },
  getClassificationData() {
    let that = this;
    let json = {};
    let urlStr = app.getNetAddresss("plugin.micro-communities.api.index.getCate");
    if (this.data.commodityTitle) {
      json.cName = this.data.commodityTitle;
    }
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            catelist: res.data,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getReleaseAddress() {
    this.address_detail = "";
    this.setData({
      Locationshow: true,
    });
  },
  getGoodsMessage() {
    this.getGoodsMessageData();
    this.setData({
      addgoodslistshow: true,
    });
  },
  getStoreMessage() {
    this.getStoreMessageData();
    this.setData({
      storeshow: true,
    });
  },
  getStoreMessageData() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.circle.frontend.circle-invitation.search-store");
    let json = {};
    json.store_name = this.data.storedata;
    that.setData({
      storePage: 1, //数组拼接
    });
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            storelistData: res.data.data,
            storeTotal: res.data.last_page,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getStoreMoreData() {
    const that = this;
    that.data.storeisLoadMore = false; // 防止多次请求分页数据
    if (this.data.storePage >= this.data.storeTotal) {
      return;
    } else {
      this.data.storePage = this.data.storePage + 1;
      let urlStr = app.getNetAddresss("plugin.circle.frontend.circle-invitation.search-store");
      app._getNetWork({
        url: urlStr,
        data: {
          page: that.data.storePage,
          store_name: that.data.storedata,
        },
        success: function (resdata) {
          var res = resdata.data;
          that.data.storeisLoadMore = true;
          if (res.result == 1) {
            let myData = res.data.data;
            console.log(that.data.storelistData);
            that.setData({
              storelistData: that.data.storelistData.concat(myData), //数组拼接
            });
          } else {
            that.data.storePage = that.data.storePage - 1;
            that.data.storeisLoadMore = false;
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    }
  },
  openProtocol() {
    this.setData({
      protocolshow: true,
    });
  },
  submitBtn() {
    //  let that = this;
    if (this.data.imgData.length == 0) return app.tips("请上传图片");
    if (!this.data.releasetitle) return app.tips("请填写标题");
    if (!this.data.releasecontents) return app.tips("请添加正文");
    if (!this.data.releaseaddress) return app.tips("请选择地点");

    // if (!this.data.goodsId) {
    // 	wx.showToast({
    // 		icon: 'none',
    // 		title: '请添加商品',
    // 		duration: 1500
    // 	})
    // 	return
    // }
    // if (!this.data.storeId) {
    // 	wx.showToast({
    // 		icon: 'none',
    // 		title: '请添加门店',
    // 		duration: 1500
    // 	})
    // 	return
    // }
    // if (!this.data.checked) return app.tips("请勾选用户协议");

    if (clickTap == "1") {
      console.log("重复请求");
      return;
    }
    clickTap = 1;
    let dataJson = {};
    let urlStr = app.getNetAddresss("plugin.circle.frontend.circle-invitation.release");
    dataJson.cat_id = this.data.catid;
    dataJson.content = this.data.releasecontents;
    dataJson.address = this.data.releaseaddress;
    dataJson.img = this.data.imgData;
    dataJson.title = this.data.releasetitle;
    dataJson.goods_id = this.data.goodsId;
    dataJson.store = this.data.storeId;
    dataJson.city = this.data.releasecity;
    dataJson.latitude = this.data.releaselat;
    dataJson.longitude = this.data.releaselnt;
    dataJson.ylat = this.data.releaselat;
    dataJson.ylng = this.data.releaselnt;
    dataJson.invitation_status = 1;
    dataJson.circle_id = this.data.circleId;
    if (this.data.stickid && this.data.stickid != 0) {
      dataJson.invitation_id = this.data.stickid;
    }
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: dataJson,
      success: (resdata) => {
        clickTap = 0;
        var res = resdata.data;
        app.tips(res.msg);
        if (res.result == 1) {
          try {
            let pages = getCurrentPages();
            let page = pages[pages.length - 3];
            page.updateView();
          } catch (error) {
            console.log(error);
          }

          wx.navigateBack({
            delta: 2,
          });
        }
      },
      fail: function (res) {
        clickTap = 0;
      },
    });
  },
  protocolBtn(e) {
    let bol = e.detail;
    this.setData({
      checked: bol,
    });
  },
  onClickLeft() {
    this.setData({
      classificationshow: false,
    });
  },
  onClickRight() {
    this.setData({
      classificationshow: false,
    });
  },
  commodityTitleClear() {
    this.setData({
      commodityTitle: "",
    });
  },
  commodityTitleInp(e) {
    let val = e.detail.value;
    this.setData({
      commodityTitle: val,
    });
  },
  searchBtn() {
    this.getClassificationData();
  },
  selectCateId(e) {
    let id = e.currentTarget.dataset.id;
    let name = e.currentTarget.dataset.name;
    this.setData({
      catid: id,
      catname: name,
      classificationshow: false,
    });
  },
  onAddressLeft() {
    this.setData({
      Locationshow: false,
      suggestionshow: false,
      address_detail: "",
    });
  },
  onAddressRight() {
    this.setData({
      Locationshow: false,
      suggestionshow: false,
      address_detail: "",
    });
  },
  addressinpbtn(e) {
    var val = e.detail.value;
    this.addressinp(val);
  },
  addressinp(val) {
    var _this = this;
    if (!val) {
      this.setData({
        suggestionshow: false,
      });
      return;
    }
    //调用关键词提示接口
    qqmapsdk.getSuggestion({
      //获取输入框值并设置keyword参数
      keyword: val, //用户输入的关键词，可设置固定值,如keyword:'KFC'
      //region:'北京', //设置城市名，限制关键词所示的地域范围，非必填参数
      sig: app.globalData.qqmapsig,
      success: function (res) {
        //搜索成功后的回调
        var sug = [];
        for (var i = 0; i < res.data.length; i++) {
          sug.push({
            // 获取返回结果，放到sug数组中
            title: res.data[i].title,
            id: res.data[i].id,
            addr: res.data[i].address,
            city: res.data[i].city,
            district: res.data[i].district,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng,
          });
        }
        _this.setData({
          //设置suggestion属性，将关键词搜索结果以列表形式展示
          suggestion: sug,
          suggestionshow: true,
        });
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {},
    });
  },
  //数据回填方法
  backfill: function (e) {
    var id = e.currentTarget.id;
    for (var i = 0; i < this.data.suggestion.length; i++) {
      if (i == id) {
        this.setData({
          releaseaddress: this.data.suggestion[i].addr,
          releasecity: this.data.suggestion[i].city,
          releaselat: this.data.suggestion[i].latitude,
          releaselnt: this.data.suggestion[i].longitude,
          address_detail: "",
          suggestionshow: false,
          Locationshow: false,
        });
      }
    }
  },
  onAddGoodsLeft() {
    this.setData({
      addgoodslistshow: false,
    });
  },
  onAddGoodsRight() {
    this.setData({
      addgoodslistshow: false,
    });
  },
  goodsdataClear() {
    this.setData({
      goodsdata: "",
    });
  },
  goodsdataInp(e) {
    let val = e.detail.value;
    this.setData({
      goodsdata: val,
    });
  },
  searchGoodBtn() {
    this.getGoodsMessageData();
  },
  getGoodsMessageData() {
    let that = this;
    let json = {};
    json.goods_name = this.data.goodsdata;
    let urlStr = app.getNetAddresss("plugin.circle.frontend.circle-invitation.search-goods");
    that.setData({
      goodsPage: 1, //数组拼接
    });
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            goodslistData: res.data.data,
            goodsTotal: res.data.last_page,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getGoodMoreData() {
    const that = this;
    that.data.goodsisLoadMore = false; // 防止多次请求分页数据
    if (this.data.goodsPage >= this.data.goodsTotal) {
      return;
    } else {
      this.data.goodsPage = this.data.goodsPage + 1;
      let urlStr = app.getNetAddresss("plugin.circle.frontend.circle-invitation.search-goods");
      app._getNetWork({
        url: urlStr,
        data: {
          page: that.data.goodsPage,
          goods_name: that.data.goodsdata,
        },
        success: function (resdata) {
          var res = resdata.data;
          that.data.goodsisLoadMore = true;
          if (res.result == 1) {
            let myData = res.data.data;
            that.setData({
              goodslistData: that.data.goodslistData.concat(myData), //数组拼接
            });
          } else {
            that.data.goodsPage = that.data.goodsPage - 1;
            that.data.goodsisLoadMore = false;
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    }
  },
  setGoodsId(e) {
    let id = e.currentTarget.dataset.id;
    this.setData({
      goodsId: id,
    });
    let selectgoodsData = {};
    for (let i = 0; i < this.data.goodslistData.length; i++) {
      if (this.data.goodsId == this.data.goodslistData[i].id) {
        selectgoodsData.id = this.data.goodslistData[i].id;
        selectgoodsData.title = this.data.goodslistData[i].title;
        selectgoodsData.thumb = this.data.goodslistData[i].thumb;
        selectgoodsData.price = this.data.goodslistData[i].price;
        selectgoodsData.market_price = this.data.goodslistData[i].market_price;
        selectgoodsData.show_sales = this.data.goodslistData[i].show_sales;
        break;
      }
    }
    this.setData({
      selectgoodsData: selectgoodsData,
      addgoodslistshow: false,
    });
  },
  storedataClear() {
    this.setData({
      storedata: "",
    });
  },
  storedataInp(e) {
    let val = e.detail.value;
    this.setData({
      storedata: val,
    });
  },
  searchStoreBtn() {
    this.getStoreMessageData();
  },
  setStoreId(e) {
    let id = e.currentTarget.dataset.id;
    this.setData({
      storeId: id,
    });
    let selectstoreData = {};
    for (let i = 0; i < this.data.storelistData.length; i++) {
      if (this.data.storeId == this.data.storelistData[i].id) {
        selectstoreData.id = this.data.storelistData[i].id;
        selectstoreData.thumb = this.data.storelistData[i].thumb;
        selectstoreData.store_name = this.data.storelistData[i].store_name;
        selectstoreData.address = this.data.storelistData[i].address;
        break;
      }
    }
    this.setData({
      selectstoreData: selectstoreData,
      storeshow: false,
    });
  },
  protocolLeft() {
    this.setData({
      protocolshow: false,
    });
  },
  onStoreLeft() {
    this.setData({
      storeshow: false,
    });
  },
  onStoreRight() {
    this.setData({
      storeshow: false,
    });
  },
  getMicroCommentDetails() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.circle.frontend.circle-invitation.details");
    let dataJson = {
      invitation_id: this.data.stickid,
    };
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: dataJson,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            releasecontents: res.data.content,
            releaseaddress: res.data.address,
          });

          that.setData({
            circleId: res.data.circle_id,
            imgData: res.data.img || [],
            releasetitle: res.data.title,
            goodsId: res.data.goods_id,
            releasecity: res.data.city,
            releaselat: res.data.ylat,
            releaselnt: res.data.ylng,
          });
          if (res.data.goods && res.data.goods.length > 0) {
            let has_one_goods = res.data.goods[0];
            that.setData({
              storeId: has_one_goods.id,
              "selectgoodsData.id": has_one_goods.id,
              "selectgoodsData.title": has_one_goods.title,
              "selectgoodsData.thumb": has_one_goods.thumb,
              "selectgoodsData.price": has_one_goods.price,
              "selectgoodsData.market_price": has_one_goods.market_price,
              "selectgoodsData.show_sales": has_one_goods.show_sales,
            });
          }

          if (res.data.store && res.data.store.length > 0) {
            let has_one_store = res.data.store[0];
            that.setData({
              "selectstoreData.id": has_one_store.id,
              "selectstoreData.thumb": has_one_store.thumb,
              "selectstoreData.store_name": has_one_store.store_name,
              "selectstoreData.address": has_one_store.address,
            });
          }
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {},
    });
  },
});
