<template>

<view>
   <view id="store-list">
        <view class="commodity-top" catchtouchmove="move">
            <view class="sidebar mx-1px-bottom">
                <view class="sidebar-left">
                <span class="iconfont icon-fenzu" @tap="classF">

                </span>
                </view>
                <view class="sidebar-right">
                    <view class="right-seek iconfont icon-sousuo" @tap="search">

                    </view>
                    <view class="right-cart iconfont icon-gouwuche" @tap="cart">

                    </view>
					<view class="right-cart iconfont icon-qiehuan1" v-if="arrangement == 'rank'" @tap="changeRange">
					
					</view>
					<view class="right-cart iconfont icon-qiehuanduotuSVG" v-if="arrangement == 'vertical'" @tap="changeRange">
					
					</view>
                </view>
            </view>
            <view class="filter-box">
                <view class="filter-item mx-1px-right" data-type="updated_at" @tap="changeOrderBy">
                    <view class="left" :class=" orderBy === 'updated_at' ? 'active' : ''">最新</view>
                    <view class="right" :class="(orderBy === 'updated_at' && sort === 'desc') ? 'desc' : ''"></view>
                </view>
                <view class="filter-item mx-1px-right" data-type="sell_price" @tap="changeOrderBy">
                    <view class="left" :class=" orderBy === 'sell_price' ? 'active' : ''">价格</view>
                    <view class="right" :class="(orderBy === 'sell_price' && sort === 'desc') ? 'desc' : ''"></view>
                </view>
                <view class="filter-item mx-1px-right" data-type="sale" @tap="changeOrderBy">
                    <view class="left" :class=" orderBy === 'sale' ? 'active' : ''">销量</view>
                    <view class="right" :class="(orderBy === 'sale' && sort === 'desc') ? 'desc' : ''"></view>
                </view>
                <view class="filter-item big-filter" :class="c_id ? '' : 'dis'" @tap="showFilterF">
                    筛选 ▼
                </view>
            </view>
        </view>
       
        <view class="commodity-bottom" :hidden="showFilter">
			<!-- 一排显示1个 -->
            <view v-for="(items, idx) in storeList" :key="idx" v-if="arrangement == 'rank'">
                <view class="commodity-out" :data-id="item.id" v-for="(item, index) in storeList[idx]" :key="index" @tap="jump">
                    <view class="commodity-box">
                        <view class="commodity-img">
                            <image mode="widthFix" :src="item.img"></image>
                        </view>
                        <view class="commodity-name">
                            {{item.name}}
                        </view>
                        <view class="commodity-money">
                            <view class="money">
                                ￥{{item.sell_price}}
								<view class="origin-money">
									￥{{item.market_price}}
								</view>
                            </view>
                            <!-- <view class="discount-tags">
                                <span class="tags-item" v-for="(tags, index) in item.discount_tags" :key="index" >{{tags}}</span>
                            </view> -->
                
                        </view>
                    </view>
                </view>
            </view>
			<!-- 一排显示一个 -->
			<view v-for="(items, idx) in storeList" :key="idx"  v-if="arrangement == 'vertical'">
				<view class="commodity-out-vertical" :data-id="item.id" v-for="(item, index) in storeList[idx]" :key="index" @tap="jump">
					<view class="img-box">
						<image mode="widthFix" :src="item.img"></image>
					</view>
					<view class="right-box">
						<view class="goods-name">
							{{item.name}}
						</view>
						<view class="goods-money">
							￥{{item.sell_price}}
							<view class="origin-money">
								￥{{item.market_price}}
							</view>
						</view>
					</view>
				</view>
			</view>

           <view class="loadingbox" :hidden="!show">
                正在加载下一页数据
            </view>

         </view>

    </view>
	
	
	
	
    <view class="right-filter-box" :hidden="!showFilter">

        <view class="box">
            <view>
                <view class="title">
                    价格区间
                </view>
                <view class="list">
                    <view class="list-block">
                        <view data-num="200-500" :class="shadows.price == '200-500' ? 'selected' : ''" @tap="checkPrice">200-500元</view>
                    </view>
                    <view class="list-block">
                        <view data-num="501-1000" :class="shadows.price == '501-1000' ? 'selected' : ''" @tap="checkPrice">501-1000元</view>
                    </view>
                    <view class="list-block">
                        <view data-num="1001-1500" :class="shadows.price == '1001-1500' ? 'selected' : ''" @tap="checkPrice">1001-1500元</view>
                    </view>
                    <view class="list-block">
                        <view data-num="1501-2000" :class="shadows.price == '1501-2000' ? 'selected' : ''" @tap="checkPrice">1501-2000元</view>
                    </view>
                    <view class="list-block">
                        <view data-num="2000-" :class="shadows.price == '2000-' ? 'selected' : ''" @tap="checkPrice">2000-元以上</view>
                    </view>

               <!--    <view class="price-inputs">
                    <input type="number" data-type="0" bindinput="modifyPrice" />
                    <view class="minus">
                      -
                    </view>
                    <input type="number" data-type="1" bindinput="modifyPrice" />
                    </view> -->

                </view>
            </view>
           <!-- #ifdef APP-PLUS || MP-WEIXIN -->
		   <view v-for="(item, index) in filter" :key="index">
		       <view class="title">
		           {{item.key}}
		       </view>
		       <view class="list">
		           <view class="list-block" v-for="(obj, index) in item.values" :key="index">
		               <view :class="!!selections[obj.id] ? 'selected' : ''" :data-id="obj.id" :data-type="obj" @tap="check">
		                   {{obj.text}}
		               </view>
		           </view> 
		       </view>
		   </view>
     
           <!-- #endif -->
		   
		   <!-- #ifdef H5 -->
		   <view v-for="(item, index) in filter" :key="index">
		       <view class="title">
		           {{item.key}}
		       </view>
		       <view class="list">
		           <view class="list-block" v-for="(obj, index) in item.values" :key="index">
		               <view :class="!!selections[obj.id] ? 'selected' : ''" :data-id="obj.id" :data-type="obj" @tap="check(obj)">
		                   {{obj.text}}
		               </view>
		           </view>
		       </view>
		   </view>
		   
		   <!-- #endif -->

            <view class="button-box">
                <button type="default" @tap="cancel">取消</button>
                <button type="primary" @tap="confirm">确定</button>
            </view>
        </view>
    </view>
</view>


</template>
<script>
var app = getApp();
import {pageLogin, getUrl,config,is} from '@/common/js/utils.js';
import Animation from '@/common/js/animation.js';

export default {
  data() {
    return {
      page: 1,
      storeList: [],
      orderBy: '',
      sort: '',
      c_id: '',
      meta: '',
      show: false,
      showFilter: false,
      filter: null,
	  price:{},
	  priceCache:{},
        shadows: {},
        selections:{},
		arrangement:'rank',//判断当前的排列方式，是横列 还是 竖列
    };
  },

  onReachBottom() {
    var hasMore = this.meta.pagination.total_pages > this.meta.pagination.current_page;

    if (!this.showFilter) {
      if (hasMore) {
        this.setData({
          show: true
        });
        var query = {
          sort: this.sort,
          orderBy: this.orderBy,
          c_id: this.c_id
        };
        var page = this.meta.pagination.current_page + 1;
        this.queryCommodityList(query, page);
      } else {
        wx.showToast({
          image: '../../../static/error.png',
          title: '再拉也没有啦'
        });
      }
    }
  },

  onReady() {
    var query = {
      sort: this.sort,
      orderBy: this.orderBy,
      c_id: this.c_id
    };
    this.queryCommodityList(query);
  },

  onLoad(e) {
    if (e.c_id) {
      this.setData({
        c_id: e.c_id
      });
    }

    if (e.orderBy) {
      this.setData({
        orderBy: e.orderBy,
        sort: e.sort
      });
    }

    var price = {
      min: '',
      max: ''
    };
    var shadows = {
      attr: {},
      specs: {}
    };

    if (e.attr) {
      e.attr.forEach(v => shadows.attr[v] = true);
    }

    Object.keys(e).forEach(key => {
      let ret = /^specs\[([^\]]+)]$/.exec(key);

      if (ret) {
        let name = ret[1];
        shadows.specs[name] = e[key];
      }
    });
    var priceList = ['200-500', '501-1000', '1001-1500', '1501-2000', '2000-'];
    shadows.price = e.price || '';

    if (!~priceList.indexOf(shadows.price)) {
      var parts = shadows.price.split(/\s*\-\s*/);
      price.min = parts[0] || '';
      price.max = parts[1] || '';
    }

    // this.setData({
    //   price: price,
    //   shadows: shadows,
    //   selections: {},
    //   priceList: priceList,
    //   priceCache: {}
    // });

      this.price=price;
      this.shadows=shadows;
      this.selections={};
      this.priceList=priceList;
      this.priceCache={};
	
	
  },

  onShareAppMessage() {
    var url = decodeURIComponent(getUrl());
    return {
      title: '商品列表',
      path: '/' + url
    };
  },

  methods: {
	  //点击切换排列方式
	  changeRange(){
		  if(this.arrangement == 'rank'){
			  this.arrangement = 'vertical'
		  } else if(this.arrangement == 'vertical'){
			  this.arrangement = 'rank'
		  }
	  },
	  
    // 价格点击
    checkPrice(e) {
      var num = e.currentTarget.dataset.num;
      if (this.shadows.price == num) {
        console.log("gaehgae");
        this.setData({
          'priceCache.value': num
        });
	
        if (this.priceCache.min !== undefined) {
          this.setData({
            'price.min': this.priceCache.min
          });
        }

        if (this.priceCache.max !== undefined) {
          this.setData({
            'price.min': this.priceCache.max
          });
        }

        // this.setData({
        //   'shadows.price': ''
        // });
		
		this.shadows={price:''}
		
		
      } else {
        console.log(46846846846846);

        if (this.price.min !== '') {
          // this.setData({
          //   'priceCache.min': this.priceCache.min
          // });
		  
		   this.priceCache.min=this.priceCache.min;
        }

        if (this.price.max !== '') {
          // this.setData({
          //   'priceCache.max': this.priceCache.max
          // });
		  this.priceCache.max=this.priceCache.max;
		  
        }

  //       this.setData({
  //         'price.min': '',
  //         'price.max': '',
  //         'shadows.price': num
  //       });
		//
		this.price.min='';
        this.price.max='';
		this.shadows.price=num;
      }
    },

    // 价格输入
    modifyPrice(e) {
      var type = e.currentTarget.dataset.type;
      var val = this.price[type ? 'max' : 'min'];
      val = parseFloat(val);
      if (isNaN(val)) val = '';

      if (this.price[type] == 'max') {
        // this.setData({
        //   'price.max': val
        // });
		this.price={max:val};
		
      } else {
        // this.setData({
        //   'price.min': val
        // });
		this.price={min:val};
      }
   //    this.setData({
   //      'shadows.price': ''
   //    });
	  //
	  this.shadows={price:''}
    },

    // 点击筛选条件
   // #ifdef APP-PLUS || MP-WEIXIN
   check(e) {
   		var type = e.currentTarget.dataset.type;
   
   		var id = type.id;
   		var selections = Object.assign({}, this.selections);
   
   		if (!selections[id]) {
   			for (let k in selections) {
   				if (selections.hasOwnProperty(k)) {
   					let o = selections[k]
   					if (o.type === type.type && o.key === type.key) {
   						delete selections[k];
   					}
   				}
   			}
   
   			selections[id] = {
   				key: type.key,
   				type: type.type,
   				value: type.value,
   				field: type.field
   			}
   		} else {
   			delete  selections[id];
   		}
   
   		this.setData({
   			selections: Object.assign({}, selections)
   		})
   	},
   // #endif
   
   // #ifdef H5 
   check(e) {
      var type = e;
      var id = type.id;
      var selections = Object.assign({}, this.selections);

      if (!selections[id]) {
        for (let k in selections) {
          if (selections.hasOwnProperty(k)) {
            let o = selections[k];

            if (o.type === type.type && o.key === type.key) {
              delete selections[k];
            }
          }
        }

        selections[id] = {
          key: type.key,
          type: type.type,
          value: type.value,
          field: type.field
        };
      } else {
        delete selections[id];
      }

      this.setData({
        selections: Object.assign({}, selections)
      });

	    /* this.selections=Object.assign({}, selections); */ 
    },
   // #endif
   
   
    // 取消
    cancel() {
	
	 // var animation = new Animation('show');
	 // animation.right().then(() => {
	   this.setData({
	     showFilter: false,
	     selections: {},
	     shadows: {}
	   });
	 // });
	

    },

    // 确定
    confirm() {
      var attr = [],
          specs = {};

      for (let k in this.selections) {
        if (this.selections.hasOwnProperty(k)) {
          let o = this.selections[k];

          if (o.type === 'attr') {
            attr.push(o.value);
          } else {
            specs['specs[' + o.field + ']'] = o.value;
          }
        }
      }

      attr = attr.join(',');
      var price = this.shadows.price;

      if (attr.length) {
        var query = Object.assign({}, {
          attr
        }, {
          c_id: this.c_id,
          orderBy: this.orderBy,
          sort: this.sort,
          price: price
        }, specs);
      } else {
        var query = Object.assign({}, {
          c_id: this.c_id,
          orderBy: this.orderBy,
          sort: this.sort,
          price: price
        }, specs);
      }

      console.log(query);
      this.queryCommodityList(query);
    },

    changeOrderBy(e) {
      var field = e.currentTarget.dataset.type;

      if (this.orderBy === field) {
        this.setData({
          sort: this.sort === 'desc' ? 'asc' : 'desc'
        });
      } else {
        this.setData({
          orderBy: field,
          sort: 'desc'
        });
      }

      wx.redirectTo({
        url: '/pages/store/list/list?orderBy=' + this.orderBy + '&sort=' + this.sort + '&c_id=' + this.c_id
      });
    },

    jump(e) {
      var id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/pages/store/detail/detail?id=' + id
      });
    },

    classF() {
		wx.switchTab({
		    url: '/pages/index/classification/classification'
		});
    },

    search() {
      wx.navigateTo({
        url: '/pages/store/search/search'
      });
    },

    cart() {
      wx.switchTab({
        url: '/pages/store/cart/cart'
      });
    },

    showFilterF() {
      if (this.c_id) {
        this.setData({
          showFilter: true
        });
        // var animation = new Animation('show');
        // animation.Pullleft();
      }
    },

    move() {},

    loadMore() {
      this.$http.get({
        api: "api/store/list?page=" + (this.page + 1)
      });
    },

    // 查询商品列表
    queryCommodityList(query = {}, page = 1) {
      var token = this.$cookieStorage.get('user_token') || '';
      var params = Object.assign({}, query, {
        page
      });
      wx.showLoading({
        title: '加载中',
        mask: true
      });
      this.$http.get({
        api: 'api/store/list',
        data: params,
        header: {
          Authorization: token
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            // 商品列表页赋值
            this.setData({
              [`storeList.${page - 1}`]: res.data,
              meta: res.meta
            }); // 右侧筛选赋值

	
            if (res.meta && res.meta.filter) {
              if (Array.isArray(res.meta.filter)) {
                this.setData({
                  filter: null
                });
              } else {
                let filter = res.meta.filter;
                let list = [];

                if (filter.attr && filter.attr.keys) {
                  let type = 'attr';
                  filter.attr.keys.forEach(key => {
                    let arr = [];
                    let arrText = [];

                    for (let attr in filter.attr.values[key]) {
                      !!attr && arrText.push(filter.attr.values[key][attr]);
                      !!attr && arr.push(attr);
                    }

                    list.push({
                      key,
                      values: arr.map((v, index) => {
                        return {
                          id: [type, key, v].join('-'),
                          key,
                          type,
                          value: v,
                          text: arrText[index]
                        };
                      })
                    });
                  });
                }

                if (filter.specs && filter.specs.keys) {
                  let type = 'specs';
                  filter.specs.keys.forEach(key => {
                    let entries = key.split(':');
                    let field = entries[1];
                    key = entries[0];
                    var newKey = key + ':' + field;
                    let specs = [];
                    let specsText = [];

                    for (let spec in filter.specs.values[newKey]) {
                      !!spec && specsText.push(filter.specs.values[newKey][spec]);
                      !!spec && specs.push(spec);
                    }

                    list.push({
                      key,
                      values: specs.map((v, index) => {
                        return {
                          id: [type, key, v].join('-'),
                          key,
                          type,
                          field,
                          value: v,
                          text: specsText[index]
                        };
                      })
                    });
                  });
                }

                this.setData({
                  filter: list
                });
              }
            }

            this.setData({
              showFilter: false
            });
          } else {
            wx.showModal({
              title: '',
              content: res.message,
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            title: '',
            content: "请求失败",
            showCancel: false
          });
        }

        this.setData({
          show: false
        });
        wx.hideLoading();
      }).catch(rej => {
        wx.showModal({
          title: '',
          content: '请求失败',
          success: res => {
            if (res.confirm) {}
          }
        });
        this.setData({
          show: false
        });
        wx.hideLoading();
      });
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  },
  computed: {},
  watch: {}
};
</script>
<style rel="stylesheet/less" lang="less">
    @import "list";
</style>