// packageC/o2o/store_add_goods/store_add_goods.js
var app = getApp();
var obj = {};  // 分类结构

Page({

  /**
	 * 页面的初始数据
	 */
  data: {
    language: '',
    columns: [], // picker的结构
    showPopup2: false,
    showPopup: false,
    result: [],
    min_price: '',
    max_price: '',
    keyword: '',
    status: '',
    store: '',
    store_id: '',
    commodity_data: [],
    catetory_menus: [], //分类
    parentid: [],
    childid: [],


    // more
    isLoadMore: true,
    page: 1,
    total_page: 0,
  },

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

  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {
    let language = wx.getStorageSync('langIndex');
    this.setData({ 'language': language.en});
  },

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

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

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

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

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

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

  chooseStatus(event) {
    this.setData({
      status: event.currentTarget.dataset.status
    });
  },
  onChange1(event) {
    const { picker, value } = event.detail;
    picker.setColumnValues(1, obj[value[0].value].list);
  },
  onConfirm(event) {
    this.setData({
      parentid: event.detail.value[0].value,
    });
    if(event.detail.value[1]) {
      this.setData({
        childid: event.detail.value[1].value
      });
    }else {
      this.setData({
        childid: ''
      });
    }
    this.AddGoods();
  },
  onClose2() {
    this.setData({ showPopup2: false });
  },
  onSmallInput(event) {
    let val = event.detail.value;
    this.setData({
      min_price: val
    });
  },
  onInput(event) {
    let val = event.detail.value;
    this.setData({
      max_price: val
    });
  },
  onClose() {
    this.setData({ showPopup: false });
  },
  onChange(event) {
    this.setData({
      result: event.detail
    });
  },
  inpbtn(e) {
    let val = e.detail.value;
    this.setData({
      keyword: val
    });
  },
  inpbtnclear() {
    this.setData({
      keyword: ''
    });
  },
  toShowPopup2() {
    if(this.data.result.length <= 0) {
      wx.showToast({
        icon: 'none',
        title: '请选选择商品',
        duration: 1500
      });
      return;
    }
    this.setData({
      showPopup2: true
    });
  },
  classifyBolbtn() {
    this.setData({
      showPopup: true
    });
  },
  search() {
    this.setData({ showPopup: false });
    this._getJson();
  },
  AddGoods() {
    let that = this;
    let json = {};

    let urls = 'plugin.store-product.api.product.index';
    json = {
      store_id: this.data.store_id,
      updateSelect: 'updateSelect',
      goods_ids: this.data.result,
      category: {
        parentid: [this.data.parentid],
        childid: [this.data.childid]
      }
    };
    let urlStr = app.getNetAddresss(urls);
    wx.showToast({
      title: '导入中',
      icon: 'loading',
      duration: 10000,
    });
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            result: [],
            showPopup2: false
          });
          wx.hideToast();
          wx.showToast({
            icon: 'success',
            title: '导入成功',
            duration: 1500
          });
        } else {
          wx.hideToast();
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {}
    });
  },
  // 商品数据获取
  _getJson() {
    let that = this;
    let urls = '';
    let json = {};
    that.setData({page: 1});

    if (this.data.store == 'store') {
      urls = 'plugin.store-product.api.product.index';
      json = {
        store_id: this.data.store_id,
        getGoodsInformation: 'getGoodsInformation',
        page: 1,
        search :{
          keyword: this.data.keyword,
          status: this.data.status,
          min_price: this.data.min_price,
          max_price: this.data.max_price
        }
      };
    } else if (this.data.store == 'supplier') {
      urls = 'plugin.supplier.frontend.goods.get-goods-list';
      json = {
        sid: this.data.store_id
      };
    }
    let urlStr = app.getNetAddresss(urls);
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            commodity_data: []
          });
          if (that.data.store == 'store') {
            let menus = res.data.getGoodsInformation.catetory_menus;

            if(menus.length > 0 && that.data.columns.length<=0) {
              let columns = [];
              res.data.getGoodsInformation.catetory_menus.map(function (item,index ) {
                let children = [];

                if(item.children) {
                  children = item.children.map(function (child,index ) {
                    return {name:child.name, value:child.id, parent_id:child.parent_id};
                  });
                }
                obj[item.id] = {name:item.name, value:item.id, list: children };
              });
              columns= [
                {
                  values: Object.keys(obj).map(key => {return {name: obj[key].name, value: obj[key].value};}),
                },
                {
                  values: obj[menus[0].id].list,
                  defaultIndex: 0
                }
              ];
              that.setData({
                columns: columns
              });
            }

            that.setData({
              catetory_menus: res.data.getGoodsInformation.catetory_menus,
              total_page: res.data.getGoodsInformation.list.last_page,
              commodity_data: res.data.getGoodsInformation.list.data
            });
          } else if (that.data.store == 'supplier') {
            for (let i = 0; i < res.data.list.length; i++) {
              res.data.list[i].edit_active = false;
            }
            console.log(res.data, '数组的格式');

            that.setData({
              total_page: res.data.list.last_page,
              commodity_data: res.data.list.data
            });
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {}
    });
  },
  // 获取更多数据
  getMoreData() {
    const that = this;
    let urls = '';
    let json = {};
    if (that.data.store == 'store') {
      urls = app.getNetAddresss('plugin.store-product.api.product.index');
      json = {
        store_id: that.data.store_id,
        getGoodsInformation: 'getGoodsInformation',
        search :{
          keyword: this.data.keyword,
          status: this.data.status,
          min_price: this.data.min_price,
          max_price: this.data.max_price
        }
      };
    } else if (that.data.store == 'supplier') {
      urls = app.getNetAddresss('plugin.supplier.frontend.goods.get-goods-list');
      json = {
        sid: that.data.store_id
      };
    }
    that.setData({
      isLoadMore: false
    });
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      that.setData({
        page: this.data.page + 1
      });
      json.page = that.data.page;
      app._postNetWork({
        url: urls,
        data: json,
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            if (that.data.store == 'store') {
              that.setData({
                commodity_data: that.data.commodity_data.concat(res.data.getGoodsInformation.list.data)
              });
            } else if (that.data.store == 'supplier') {
              for (var i = 0; i < res.data.list.data.length; i++) {
                res.data.list.data[i].edit_active = false;
              }
              that.setData({
                commodity_data: that.data.commodity_data.concat(res.data.list.data)
              });
            }
            that.setData({
              isLoadMore: true
            });
          } else {
            that.setData({
              page: that.data.page - 1,
              isLoadMore: false
            });
          }
        },
        fail: function(res) {
          console.log(res);
        }
      });
    }
  },
  initData() {
    this.setData({
      commodity_data: [],
      isLoadMore: true,
      page: 1,
      total_page: 0,
    });
  }
});
