// packageF/storeManagement/storeGoodsManagement/storeGoodsManagement.js
var behavior = require('../common.js');
var app = getApp();
Page({
  behaviors: [behavior],
  /**
   * 页面的初始数据
   */
  data: {
    active: '-1',
    keyWord: '',
    isBatchOperation: false,
    allCheck: false,
    goodsList: [],
    goodsCount:0,
    batchGoods: [], // 批量操作的商品id
    batchGoodsAll:[],// 全部商品ID，用于操作全选
    optionBtns: [
      {text: "批量上架", type: "up"},
      {text: "批量下架", type: "down"},
      {text: "批量删除", type: "delete"},],

    page: 1, //分页数，当前页数
    isLoadMore: true, //判断是否要加载更多的标志
    total_page: 0, //总页数
    networkLoading:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getGoodsList();
  },
  initData() {
    this.setData({
      page: 1,
      total_page: 0,
      isLoadMore: true,
      networkLoading: false,
    });
  },
  handSearch(evt){
    this.data.keyWord = evt.detail;
    this.getGoodsList();
  },
  getGoodsList(){
    this.initData();
    let requestParams = {
      page: this.data.page,
      search: {
        title: this.data.keyWord
      }
    };
    if (this.data.active !== '-1') {
      requestParams.search.status = this.data.active;
    }
    let urlStr = app.getNetAddresss("plugin.shop-assistant.frontend.goods.get-list");
    app._postNetWork({
      url: urlStr,
      data: requestParams,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result != 1) return app.tips(res.msg);
        this.data.total_page = res.data.last_page;
        if (!this.data.total_page) {
          this.data.total_page = 0;
        }
        
        if(res.data.data){
          
          let batchGoodsAll= res.data.data.map((item)=>{
            return item.id+"";
          });
          this.data.batchGoodsAll = batchGoodsAll;
        }
        this.setData({
          goodsList:res.data.data,
          goodsCount:res.data.total,
          networkLoading:true
        });	
      }
    });
  },

  selectBolfun () {
    this.setData({
      isBatchOperation:true
    });
  },
  cancelBatchOperation(){
    this.setData({
      isBatchOperation:false
    });
  },
  checkboxGroupChange(evt){
    this.setData({
      batchGoods:evt.detail
    });
  },
  toggleAll (evt) {
    let allCheck = evt.detail;
    let batchGoods=[];
    if(allCheck){
      batchGoods = JSON.parse(JSON.stringify(this.data.batchGoodsAll));
    }
    this.setData({
      allCheck,batchGoods
    });
  },
  changeTabs(evt){

    this.data.active = evt.detail.name;
    this.getGoodsList();
  },

  async onShelf(evt){

    let goodsId = evt.currentTarget.dataset.goodsid;
    let option = evt.currentTarget.dataset.option;

    let tipText = option?'上架':'下架';
    let confirmFlag = await app.confirm(`是否${tipText}该商品`);
    if(!confirmFlag) return;
    let urlStr = app.getNetAddresss("plugin.shop-assistant.frontend.goods.update-on-shelf");
    app._postNetWork({
      url: urlStr,
      data: {id: goodsId, status: option},
      success: (resdata) => {
        var res = resdata.data;
        app.tips(res.msg);
        if (res.result != 1) return ;
        this.getGoodsList();
      }
    });
  },

  async deleteGoods(evt){
    let goodsId = evt.currentTarget.dataset.goodsid;
    let confirmFlag = await app.confirm('是否删除该商品');
    if(!confirmFlag) return;
    let urlStr = app.getNetAddresss("plugin.shop-assistant.frontend.goods.delete");
    app._postNetWork({
      url: urlStr,
      data: {id: goodsId},
      success: (resdata) => {
        var res = resdata.data;
        app.tips(res.msg);
        if (res.result != 1) return ;
        this.getGoodsList();
      }
    });
  },

  handlerBatchOpt(evt){
    let opt = evt.currentTarget.dataset.item;
    if (this.data.batchGoods.length === 0) {
      return app.tips("请先选择需要批量操作的商品");
    }
    if (opt.type === "up"){
      this.batchOnShelf(1);
    } else if (opt.type === "down"){
      this.batchOnShelf(0);
    } else {
      this.batchDelte();
    }
  },

  //批量上下架
  async batchOnShelf(option){
    let tipText = option?'上架':'下架';
    let confirmFlag = await app.confirm(`正在进行批量${tipText}操作，是否继续？`);
    if(!confirmFlag) return;

    let urlStr = app.getNetAddresss("plugin.shop-assistant.frontend.goods.batch-update-shelf");
    app._postNetWork({
      url: urlStr,
      data: {ids: this.data.batchGoods, status: option},
      success: (resdata) => {
        var res = resdata.data;
        app.tips(res.msg);
        if (res.result != 1) return ;
        this.getGoodsList();
        this.setData({
          batchGoods:[]
        });
      }
    });


  },

  async batchDelte(){
    let confirmFlag = await app.confirm('正在进行批量删除操作，是否继续？');
    if(!confirmFlag) return;
    let urlStr = app.getNetAddresss("plugin.shop-assistant.frontend.goods.batch-delete");
    app._postNetWork({
      url: urlStr,
      data: {ids: this.data.batchGoods},
      success: (resdata) => {
        var res = resdata.data;
        app.tips(res.msg);
        if (res.result != 1) return ;
        this.getGoodsList();
        this.setData({
          batchGoods:[]
        });
      }
    });
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  _getMoreData(){
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.total_page) {
      // that.loading = true;
      return;
    } else {
      this.data.page += 1;
      let requestParams = {
        page: this.data.page,
        search: {
          title: this.data.keyWord
        }
      };
      if (this.data.active !== '-1') {
        requestParams.search.status = this.data.active;
      }
      let urlStr = app.getNetAddresss('plugin.shop-assistant.frontend.goods.get-list');

      app._postNetWork({
        url: urlStr,
        data:requestParams,
        success: (resdata) => {
          let res = resdata.data;
          this.data.isLoadMore = true;
          if (res.result === 1) {
            if(res.data.data){
              let batchGoodsAll= res.data.data.map((item)=>{
                return item.id+"";
              });
              this.data.batchGoodsAll.push(...batchGoodsAll);
            }

            let goodsList = this.data.goodsList.concat(res.data.data);
            this.setData({goodsList});
          } else {
            this.data.page = this.data.page - 1;
            this.data.isLoadMore = false;
          }
        }
      });
    }
  },

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

  }
});