<template>
<view id="favorite-index">
    <checkbox-group change="select">
    <view class="num-box">
        <view class="goods">您收藏了 <text class="num">{{total}}</text> 个商品</view>
        <view class="operation" @tap="editF">{{edit ? '完成' : '编辑'}}</view>
    </view>
    <view class="goods-list">
            <view v-for="(item, idx) in dataList" :key="idx">
                <view class="goods-item mx-1px-bottom" v-if="!item.remove" v-for="(item, index) in dataList[idx]" :key="index">
                    <view class="img-box">
                        <checkbox :hidden="!edit" color="#fff" @tap="fClick" :checked="item.isCheck" :data-ischecked="item.isCheck" :data-findex="idx" :data-index="index" :data-value="item.favoriteable_id" :value="item.favoriteable_id"></checkbox>
                        <image :src="item.favoriteable.img" :data-id="item.favoriteable_id" @tap="jump"></image>
                    </view>
                    <view class="text" :data-id="item.favoriteable.id" @tap="jump">
                        <view class="names">{{item.favoriteable.name}}</view>
                        <view class="money">¥{{item.favoriteable.sell_price}}</view>
                    </view>
                </view>
            </view>
        <view class="loadingbox" :hidden="!show">
            正在加载下一页数据
        </view>
    </view>
    </checkbox-group>
    <view class="cancel mx-1px-top" v-if="edit">
        <view class="checkbox">
            <label>
                <checkbox @tap="click" color="#fff" :checked="allCheck"></checkbox> 全选
            </label>
        </view>
        <view class="cancel-button" :style="'background: ' + config.mainColor" @tap="cancel">
            取消收藏
        </view>

    </view>
</view>

</template>
<script>
import {pageLogin, getUrl,config,is} from '@/common/js/utils.js';

export default {
  data() {
    return {
      page: 1,
      show: false,
      edit: false,
      meta: '',
      total: 0,
      dataList: [],
      checkList: [],
      allCheck: false,
      config: ''
    };
  },

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

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

  onShow() {
    this.queryFavoriteList(); // let app =getApp();
    // app.isBirthday().then(()=>{
    //     if(this.$cookieStorage.get("birthday_gift")){
    //         var giftData=this.$cookieStorage.get("birthday_gift").data;
    //         new app.ToastPannel().__page.showText(giftData);
    //     }
    // });
  },

  onLoad() {
    // 第三方平台配置颜色
    var config = this.$cookieStorage.get('globalConfig') || '';
    this.setData({
      config: config
    });
  },

  components: {},
  props: {},
  methods: {
    editF() {
      this.setData({
        edit: !this.edit
      });
    },

    select(e) {
      var value = e.detail.value;
      var newList = [];

      if (value.length == this.total) {
        this.setData({
          allCheck: true
        });
      } else {
        this.setData({
          allCheck: false
        });
      }

      value.forEach(v => {
        v = parseInt(v);
        newList.push(v);
      });
      this.setData({
        checkList: newList
      });
    },

    click() {
      var newList = this.dataList;

      if (this.allCheck) {
        newList.forEach(v => {
          v.forEach(i => {
            i.isCheck = false;
          });
        });
        this.setData({
          checkList: []
        });
      } else {
        var checkList = [];
        newList.forEach(v => {
          v.forEach(i => {
            i.isCheck = true;
          });
        });
        newList.forEach(v => {
          v.forEach(i => {
            checkList.push(i.favoriteable_id);
          });
        });
        this.setData({
          checkList: checkList
        });
      }

      this.setData({
        dataList: newList,
        allCheck: !this.allCheck
      });
    },

    fClick(e) {
      var index = e.currentTarget.dataset.index;
      var value = e.currentTarget.dataset.value;
      var fIndex = e.currentTarget.dataset.findex;
      var isCheck = e.currentTarget.dataset.ischecked;
      var list = `dataList[${fIndex}]`;
      // this.setData({
      //   [`${list}[${index}].isCheck`]: !this.dataList[fIndex][index].isCheck
      // });
	  
	  this.list[index].isCheck=!this.dataList[fIndex][index].isCheck;
    },

    cancel() {
      var data = {
        checkList: this.checkList,
        dataList: this.dataList
      };

      if (this.checkList.length === 0) {
        wx.showModal({
          title: '',
          content: '请选择你要删除的收藏',
          showCancel: false
        });
      } else {
        wx.showModal({
          title: '',
          content: '是否取消收藏',
          success: res => {
            if (res.confirm) {
              this.removeBatchFavorite(data);
            }
          }
        });
      }
    },

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

    // 查询收藏列表
    queryFavoriteList(status = 0, page = 1) {
      var token = this.$cookieStorage.get('user_token');
      this.$http.get({
        api: 'api/favorite',
        header: {
          Authorization: token
        },
        data: {
          page: page
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            var pages = res.meta.pagination;
            var total = res.meta.pagination.total;
            res.data.forEach(v => {
              v.remove = false;
              v.isCheck = false;
            });
            this.setData({
              total: total,
              //[`dataList[${page - 1}]`]: res.data,
              meta: res.meta
            });
			
			this.$set(this.dataList, page -1, res.data);
			
          } else {
            wx.showModal({
              title: '',
              content: res.message,
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            title: '',
            content: "请求失败",
            showCancel: false
          });
        }

        this.setData({
          show: false
        });
      }).catch(rej => {
        this.setData({
          show: false
        });
      });
    },

    // 批量删除收藏
    removeBatchFavorite(data) {
      var token = this.$cookieStorage.get('user_token');
      this.$http.post({
        api: 'api/favorite/delFavs',
        data: {
          favoriteable_id: data.checkList,
          favoriteable_type: 'goods'
        },
        header: {
          Authorization: token
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            var dataList = data.dataList;
            var checkList = data.checkList;
            dataList.forEach((v, idx) => {
              v.forEach((i, index) => {
                if (checkList.indexOf(i.favoriteable_id) != -1) {
      //             this.setData({
      //               [`dataList[${idx}][${index}].remove`]: true
      //             });
				  // 
				  this.dataList[idx][index].remove=true;
				  
                }
              });
            });
            this.queryFavoriteList();
            this.setData({
              checkList: []
            });
          } else {
            wx.showModal({
              title: '',
              content: res.message,
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            title: '',
            content: "请求失败",
            showCancel: false
          });
        }
      });
    },

    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 "index";
</style>