<template>
	
	<view>

		<view id="find">
		    <view class="search-box">
		        <view class="search">
		            <view class="iconfont icon-sousuo"></view>
		            <input type="text" placeholder="搜索关键词" @input="changeKeywords" @confirm="jumpfind" />
		        </view>
		
		    </view>
		    <view class="banner" v-if="banner.length">
		        <swiper indicator-dots="true" autoplay="true" circular="true" style="height: 180px">
		            <swiper-item v-for="(item, index) in banner" :key="index"  @tap="jumpSearch" :data-key="item.keywords">
		                <image :src="item.img"></image>
		            </swiper-item>
		        </swiper>
		    </view>
		   <view class="menu-box">
		       <view class="navbar">
		           <view class="item" :class="activeIndex == 0? 'active' : ''" @tap="tabClick" data-index="0" style="flex: .5">
		               <span>全部</span>
		           </view>
		           <view class="item" :class="activeIndex == index+1 ? 'active' : ''" @tap="tabClick" v-for="(item, index) in conditions.categories" :key="index"  v-if="index < 2" :data-index="index+1" :data-id="item.id">
		               <span>{{item.name}}</span>
		           </view>
		           <view class="item" :class="activeIndex == 3 ? 'active' : ''" @tap="moreClick" style="flex: .8">
		            <span>更多
		            <view class="iconfont icon-jiantou"></view>
		            </span>
		           </view>
		           <view class="item" @tap="filterClick" style="flex: .5">
		            <span>筛选
		            <view class="iconfont icon-filter"></view>
		            </span>
		           </view>
		       </view>
		       <!--        点击更多弹出-->
		       <view class="more-list" v-if="isMore && conditions.categories.length">
		           <view class="item" :class="item.id == category_id ? 'active' : ''" v-for="(item, index) in conditions.categories" :key="index"  @tap="changeCategories" :data-index="index" :data-id="item.id">{{item.name}}</view>
		       </view>
		   </view>
		    <view class="content-box" v-if="init">
		        <view v-if="list[0].length">
		            <view v-for="(items, idx) in list" :key="idx" >
		                <view class="something__box" v-for="(item, index) in items" :key="index" >
		                    <view class="li-item">
		                        <view class="something__item">
		                            <view class="item__user">
		                                <view class="user__img">
		                                    <image :src="item.avatar"></image>
		                                </view>
		                                <view class="user__title">
		                                    <view class="title__box">
		                                        <view class="title__title">
		                                            <span>{{item.nick_name}}</span>
		                                        </view>
		                                    </view>
		                                    <!--<view class="title__stick">
		                                        <i class="iconfont icon&#45;&#45;zhidingtuijian"></i>
		                                    </view>-->
		                                </view>
		                            </view>
		                            <view class="item__content">
		                                <view class="item__title" @tap="copyText" :data-txt="item.description">
		                                    {{item.description}}
		                                </view>
		                                <!--<view class="read__more" bindtap="more">
		                                    {{text}}
		                                </view>-->
		                                <view class="item__list" v-if="item.img_list.length==1">
		                                    <!--如果图片长度为1，显示一张-->
		                                    <view class="img">
		                                        <image mode="widthFix" :src="item.img_list[0]"></image>
		                                    </view>
		                                    <!-- <view class="list__li">
		                                         <view style="background: url('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1524827781748&di=d50541539b9b5f3850170d97854fc380&imgtype=0&src=http%3A%2F%2Fwww.pp3.cn%2Fuploads%2F201704%2F20170815006.jpg'); background-position: center;background-repeat: no-repeat;background-size: cover;">
		                                             <span></span>
		                                         </view>
		                                     </view>-->
		                                </view>
		                                <view class="item__list" v-else>
		                                    <view class="list__li" v-for="(i, imgkey) in item.img_list" :key="imgkey"   @tap="preImage" :data-index="index" :data-idx="idx" :data-url="i">
		                                        <view :style="'background: url(' + i + '); background-position: center;background-repeat: no-repeat;background-size: cover;'">
		                                            <span></span>
		                                        </view>
		                                    </view>
		                                </view>
		                                <view class="time-txet">{{item.created_at}}</view>
		                                <view class="tags" v-if="item.tags_list">
		                                    <view class="tag-item" v-for="(tag, n) in item.tags_list" :key="n">{{tag}}</view>
		                                </view>
		                                <view class="goods-box" v-if="item.goods" @tap="jumpDetail" :data-id="item.goods.id">
		                                    <view class="left-box">
		                                        <image :src="item.goods.img"></image>
		                                    </view>
		                                    <view class="right-box">
		                                        <view class="name">
		                                            {{item.goods.name}}
		                                        </view>
		                                        <view class="money">￥ {{item.goods.sell_price}}</view>
		                                    </view>
		                                </view>
		                            </view>
		
		                        </view>
		                        <view class="bottom-btn mx-1px-top">
		                            <view class="btn" :class="item.is_favorite ? 'active' : ''" :data-islike="item.is_favorite" @tap="favoriteClick" :data-index="index" :data-idx="idx" :data-id="item.id">
		                                <span class="iconfont icon-Group3"></span>
		                                <block v-if="item.is_favorite">已收藏</block>
		                                <block v-else>收藏</block>
		                            </view>
		                       
		                            <view class="btn" @tap="downloadImgs" :data-urls="item.img_list">
		                                <span class="iconfont icon-Group5"></span>
		                                下载
		                            </view>
		                            
		                        </view>
		                    </view>
		
		                    <!--<view class="index__end" wx:if="{{page == total_pages}}">
		                        已经全部加载完毕
		                    </view>-->
		                </view>
		            </view>
		        </view>
		        <view v-else class="no-data">暂无数据</view>
		    </view>
		    <view class="maks" v-if="isMore" @tap="moreClick"></view>
		<!--    筛选-->
		    <view class="filter-box" v-if="isFitter" @tap="filterClick">
		        <view class="content" @tap.stop="jumpClose">
		            <view class="select" v-if="conditions.brands.length">
		                <view class="topic">
		                    品牌
		                    <span>（单选）</span>
		                </view>
		                <view class="list">
		                    <view class="item" :class="index == brandIndex ? 'active' : ''" v-for="(item, index) in conditions.brands" :key="index" @tap.stop="radioBrand" :data-id="item.id" :data-name="item.name" :data-index="index">
		                        {{item.name}}
		                    </view>
		                </view>
		            </view>
		            <view class="select" v-if="conditions.tags.length">
		                <view class="topic">
		                    推荐标签
		                    <span>（最多选2个）</span>
		                </view>
		                <view class="list">
		                    <view class="item" :class="item.isChoose == true ? 'active':''" v-for="(item, index) in conditions.tags" :key="index"  @tap.stop="checkboxTag" :data-index="index" :data-id="item.id" :data-name="item.name" :data-isChoose="item.isChoose">
		                        {{item.name}}
		                    </view>
		                </view>
		            </view>
		            <view class="btn-box">
		                <view class="btn reset" @tap.stop="reset">重置</view>
		                <view class="btn confirm" @tap.stop="confirm">确定</view>
		            </view>
		        </view>
		    </view>
		
		
		
		    <view class="menu-box flex-menu-box" :hidden="isHidden">
		        <view class="navbar">
		            <view class="item" :class="activeIndex == 0? 'active' : ''" @tap="tabClick" data-index="0" style="flex: .5">
		                <span>全部</span>
		            </view>
		            <view class="item" :class="activeIndex == index+1 ? 'active' : ''" @tap="tabClick" v-for="(item, index) in conditions.categories" :key="index"  v-if="index < 2" :data-index="index+1" :data-id="item.id">
		                <span>{{item.name}}</span>
		            </view>
		            <view class="item" :class="activeIndex == 3 ? 'active' : ''" @tap="moreClick" style="flex: .8">
		            <span>更多
		            <view class="iconfont icon-jiantou"></view>
		            </span>
		            </view>
		            <view class="item" @tap="filterClick" style="flex: .5">
		            <span>筛选
		            <view class="iconfont icon-filter"></view>
		            </span>
		            </view>
		        </view>
		        <!--        点击更多弹出-->
		        <view class="more-list" v-if="isMore && conditions.categories.length">
		            <view class="item" :class="item.id == category_id ? 'active' : ''" v-for="(item, index) in conditions.categories" :key="index"  @tap="changeCategories" :data-index="index" :data-id="item.id">{{item.name}}</view>
		        </view>
		    </view>
		</view>
	</view>

</template>
<script>
//import { config, pageLogin, getUrl, sandBox, cookieStorage, writePhotosAlbum } from '../../../lib/myapp.js';

import {pageLogin, getUrl,writePhotosAlbum} from '@/common/js/utils.js';
import permision from "@/common/js/permission.js"

let a;

export default {
  data() {
    return {
      banner: [],
      conditions: '',
      //筛选条件
      list: [],
      more: true,
      page: '',
      init: false,
      isFitter: false,
      brandIndex: -1,
      brandItem: '',
      tagItem: [],
      category_id: '',
      //分类id
      activeIndex: 0,
      isMore: false,
      category_index: -1,
      isFavorite: false,
      tagIds: [],
      isTab: true,
      keywords: '',
      isHidden: true
    };
  },

  //下拉刷新
  onReachBottom() {
    if (this.more) {
      let page = this.page + 1;
      let brand_id = this.brandItem.id || '';
      let tags = '';
      let arr = [];

      if (this.tagItem.length) {
        this.tagItem.forEach(val => {
          arr.push(val.id);
        });
        tags = arr.join(',');
      }

      this.getContentList(page, brand_id, this.category_id, tags);
    } else {
      wx.showToast({
        image: '../../../static/error.png',
        title: '再拉也没有啦'
      });
    }
  },

  onShow() {
    if (a) {
      a = false;
      return;
    }

    this.getBanners();
    this.getConditions();
    this.getContentList(1, '', '', '');
  },

  onLoad() {},

  components: {},
  props: {},
  methods: {
	  
		  
    changeKeywords(e) {
      this.setData({
        keywords: e.detail.value
      });
    },

    // 监听滑动
    onPageScroll(e) {
      let scrollTop = e.scrollTop;

      if (scrollTop > 300) {
        this.setData({
          isHidden: false
        });
      } else {
        this.setData({
          isHidden: true
        });
      }
    },

    //点击分类
    tabClick(e) {
      this.setData({
        init: false
      });
      let index = e.currentTarget.dataset.index;
      let id = e.currentTarget.dataset.id || '';
      this.setData({
        activeIndex: index,
        category_id: id
      });
      let brand_id = this.brandItem.id || '';
      let tags = '';
      let arr = [];

      if (this.tagItem.length) {
        this.tagItem.forEach(val => {
          arr.push(val.id);
        });
        tags = arr.join(',');
      }

      this.getContentList(1, brand_id, this.category_id, tags, true);
    },

    //复制文案
    copyText(e) {
      let txt = e.currentTarget.dataset.txt;
      wx.setClipboardData({
        data: txt,

        success() {
          wx.showToast({
            title: "复制成功"
          });
        }

      });
    },

    //点击更多
    moreClick() {
      this.setData({
        isMore: !this.isMore
      });
    },

    changeCategories(e) {
      this.setData({
        init: false
      });
      let id = e.currentTarget.dataset.id;
      let index = e.currentTarget.dataset.index;

      if (this.conditions.categories.length >= 2) {
        if (index >= 2) {
          this.setData({
            activeIndex: 3
          });
        } else {
          this.setData({
            activeIndex: index + 1
          });
        }
      }

      this.setData({
        category_id: id,
        category_index: index
      });
      let brand_id = this.brandItem.id || '';
      let tags = '';
      let arr = [];

      if (this.tagItem.length) {
        this.tagItem.forEach(val => {
          arr.push(val.id);
        });
        tags = arr.join(',');
      }

      this.moreClick();
      this.getContentList(1, brand_id, this.category_id, tags, true);
    },

    //获取轮播图
    getBanners() {
      wx.showLoading({
        title: "加载中",
        mask: true
      });
      this.$http.get({
        api: 'api/discover/banners'
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            // this.setData({
            //   banner: res.data.banners
            // });
			
			this.banner=res.data.banners;
			
          } else {
            wx.showModal({
              content: res.message || '请求失败',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: res.message || '请求失败',
            showCancel: false
          });
        }

        // this.setData({
        //   show: false
        // });
		
		 this.show=false;
		
        wx.hideLoading();
      }).catch(rej => {
        wx.hideLoading();
        wx.showModal({
          content: res.message || '请求失败',
          showCancel: false
        });
      });
    },

    jumpDetail(e) {
      let id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: `/pages/store/detail/detail?id=${id}`
      });
    },

    //获取筛选条件
    getConditions() {
      wx.showLoading({
        title: "加载中",
        mask: true
      });
      this.$http.get({
        api: 'api/discover/conditions'
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            if (res.data.tags && res.data.tags.length) {
              res.data.tags.forEach(val => {
                val.isChoose = false;
              });
            }

            this.setData({
              conditions: res.data
            });
          } else {
            wx.showModal({
              content: res.message || '请求失败',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: res.message || '请求失败',
            showCancel: false
          });
        }

        // this.setData({
        //   show: false
        // });
		 this.show=false;
		
        wx.hideLoading();
      }).catch(rej => {
        wx.hideLoading();
        wx.showModal({
          content: res.message || '请求失败',
          showCancel: false
        });
      });
    },

    //获取文章列表
    getContentList(page, brand_id, category_id, tags, is_tab) {
      wx.showLoading({
        title: "加载中",
        mask: true
      });
      let token = this.$cookieStorage.get('user_token') || '';
      let tagList = '';

      if (tags) {
        tagList = tags.split(',').sort(function (a, b) {
          return a - b;
        }).join(',');
      }

      this.$http.get({
        api: 'api/discover/content/list',
        data: {
          page: page,
          brand_id: brand_id,
          category_id: category_id,
          tags: tagList
        },
        header: {
          Authorization: token
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            if (is_tab) {
              this.setData({
                list: []
              });
            }

            let pages = res.meta.pagination;
            let current_page = pages.current_page;
            let total_pages = pages.total_pages;
            this.setData({
              //[`list[${page - 1}]`]: res.data,
              more: current_page < total_pages,
              page: current_page,
              init: true
            });
			
			this.list[page -1]=res.data;
			
          } else {
            wx.showModal({
              content: res.message || '请求失败',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: res.message || '请求失败',
            showCancel: false
          });
        }

        // this.setData({
        //   show: false
        // });
		 this.show=false;
		
        wx.hideLoading();
      }).catch(rej => {
        wx.hideLoading();
        wx.showModal({
          content: res.message || '请求失败',
          showCancel: false
        });
      });
    },

    //点击筛选
    filterClick() {
      this.setData({
        isFitter: !this.isFitter
      });
    },

    radioBrand(e) {
      let index = e.currentTarget.dataset.index;
      let id = e.currentTarget.dataset.id;
	  let name = e.currentTarget.dataset.name;
      this.setData({
        brandIndex: index,
        brandItem: {
			id:id,
			name:name
		}
      });
    },

    checkboxTag(e) {

      let tags = this.conditions.tags; //渲染的数据

      let index = e.currentTarget.dataset.index;
      let item = {
		  id:e.currentTarget.dataset.id,
		  name:e.currentTarget.dataset.name,
		  isChoose:e.currentTarget.dataset.isChoose
	  };
      let tagItem = this.tagItem;
      let tagIds = this.tagIds;
      let idsIndex = tagIds.indexOf(item.id);

      if (idsIndex == -1) {
        if (tagItem.length < 2) {
          tags[index].isChoose = true;
          tagItem.push(item);
          tagIds.push(item.id); 
          this.setData({
            tagItem: tagItem,
            tagIds: tagIds,
            'conditions.tags': tags
          });
        } else {
          wx.showToast({
            title: '最多选择两个',
            icon: 'none'
          });
        }
      } else {
        tagItem.splice(idsIndex, 1);
        tagIds.splice(idsIndex, 1);
        tags[index].isChoose = false;
        this.setData({
          tagItem: tagItem,
          tagIds: tagIds,
          'conditions.tags': tags
        });
      }
    },

    //重置标签
    reset() {
      let tags = this.conditions.tags;
      tags.forEach(val => {
        val.isChoose = false;
      });
      this.setData({
        brandIndex: -1,
        brandItem: '',
        tagItem: [],
        tagIds: [],
        'conditions.tags': tags
      });
    },

    jumpClose() {
      return;
    },

    //确认筛选
    confirm() {
      this.setData({
        init: false
      });
      let brand_id = this.brandItem.id || '';
      let tags = '';
      let arr = [];

      if (this.tagItem.length) {
        this.tagItem.forEach(val => {
          arr.push(val.id);
        });
        tags = arr.join(',');
      }

      this.getContentList(1, brand_id, this.category_id, tags, true);
      this.filterClick();
    },

    //收藏内容
    addFavorite(content_id, idx, index) {
      let token = this.$cookieStorage.get('user_token');
      wx.showLoading({
        title: "收藏中",
        mask: true
      });
      this.$http.post({
        api: 'api/content/favorite/add',
        header: {
          Authorization: token
        },
        data: {
          content_id: content_id
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
              let items = this.list[idx];
              let item = items[index];
              item.is_favorite = 1;
              this.$set(this.list, idx, items)
            /*this.setData({
              [`list[${idx}][${index}].is_favorite`]: 1
            });*/
          } else {
            wx.showModal({
              content: res.message || '请求失败',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: res.message || '请求失败',
            showCancel: false
          });
        }

        wx.hideLoading();
      }).catch(rej => {
        wx.hideLoading();
        wx.showModal({
          content: res.message || '请求失败',
          showCancel: false
        });
      });
    },

    deleteFavorite(content_id, idx, index) {
      let token = this.$cookieStorage.get('user_token');
      wx.showLoading({
        title: "取消中",
        mask: true
      });
      this.$http.post({
        api: 'api/content/favorite/delete',
        header: {
          Authorization: token
        },
        data: {
          content_id: content_id
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
              let items = this.list[idx];
              let item = items[index];
              item.is_favorite = 0;
              this.$set(this.list, idx, items)
          } else {
            wx.showModal({
              content: res.message || '请求失败',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: res.message || '请求失败',
            showCancel: false
          });
        }

        wx.hideLoading();
      }).catch(rej => {
        wx.hideLoading();
        wx.showModal({
          content: res.message || '请求失败',
          showCancel: false
        });
      });
    },

    favoriteClick(e) {
      let token = this.$cookieStorage.get('user_token');

      if (token) {
        let islike = e.currentTarget.dataset.islike;
        let idx = e.currentTarget.dataset.idx;
        let index = e.currentTarget.dataset.index;
        let id = e.currentTarget.dataset.id;

        if (islike == 0) {
          this.addFavorite(id, idx, index);
        } else if (islike == 1) {
          this.deleteFavorite(id, idx, index);
        }
      } else {
        let url = getUrl();
        wx.navigateTo({
          url: "/pages/user/register/register?url=" + url
        });
      }
    },

    jumpSearch(e) {
      let keywords = e.currentTarget.dataset.key || '';
      wx.navigateTo({
        url: "/pages/user/findSearch/findSearch?keywords=" + keywords
      });
    },

    jumpfind() {
      wx.navigateTo({
        url: "/pages/user/findSearch/findSearch?keywords=" + this.keywords
      });
    },

    writePhotosAlbum(successFun, failFun) {
     // #ifdef MP-WEIXIN
     wx.getSetting({
       success(res) {
         if (!res.authSetting['scope.writePhotosAlbum']) {
           wx.authorize({
             scope: 'scope.writePhotosAlbum',
             success: function () {
               successFun && successFun();
             },
             fail: function (res) {
               wx.hideLoading();
               wx.showModal({
                 title: '提示',
                 content: "小程序需要您的微信授权保存图片，是否重新授权？",
                 showCancel: true,
                 cancelText: "否",
                 confirmText: "是",
                 success: function (res2) {
                   if (res2.confirm) {
                     //用户点击确定'
                     wx.openSetting({
                       success: res3 => {
                         if (res3.authSetting['scope.writePhotosAlbum']) {
                           //已授权
                           successFun && successFun();
                         } else {
                           failFun && failFun();
                         }
                       }
                     });
                   } else {
                     failFun && failFun();
                   }
                 }
               });
             }
           });
         } else {
           successFun && successFun();
         }
       }
     
     });
     // #endif
	 
	 // #ifdef APP-PLUS
	 var that = this;
	 uni.getSystemInfo({
	 	success(result) {
	 		if(result.platform == 'android'){
	 			that.requestAndroidPermission(successFun);
	 		} else if(result.platform == 'ios'){
	 			that.requestIosPermission(successFun)
	 		}
	 		
	 	}
	 })
	 // #endif
    },
	//ios 获取权限
	requestIosPermission(successFun){
		var result = permision.judgeIosPermission('photoLibrary');
		if(result){
			successFun && successFun();
		}else{
			//打开授权，iOS上如果没有调用过的权限，不会出现在权限设置界面。
			permision.gotoAppPermissionSetting()
		}
	},
	//安卓 app 获取权限
	async requestAndroidPermission(successFun) {
	    var result = await permision.requestAndroidPermission("android.permission.WRITE_EXTERNAL_STORAGE")
	    var strStatus
	    if (result == 1) {
	        strStatus = "已获得授权";
				 successFun && successFun();
	    } else if (result == 0) { 
	        strStatus = "未获得授权";
					void permision.gotoAppPermissionSetting()
	    } else {
	        strStatus = "被永久拒绝权限"
				  void permision.gotoAppPermissionSetting()
	    }
	},

    //下载多张图片
    downloadImgs(e) {
      // #ifdef APP-PLUS || MP-WEIXIN
      let urlsList = e.currentTarget.dataset.urls;
      
      if (urlsList && urlsList.length) {
      		  
        var _this = this; // 获取权限
      
      
        this.writePhotosAlbum(function success() {
          wx.showLoading({
            title: '加载中',
            mask: true
          });
      
          _this.queue(urlsList).then(res => {
            wx.hideLoading();
            wx.showToast({
              title: '下载完成'
            });
          }).catch(err => {
            wx.hideLoading();
          });
        }, function fail() {
          wx.showToast({
            title: '您拒绝了保存到相册',
            icon: 'none'
          });
        });
      } else {
        return;
      }
      // #endif
	  // #ifdef H5
	  wx.showModal({
	  		  content:"请长按图片进行保存",
	  		  showCancel:false
	  })
	  // #endif
    },

    // 队列
    queue(urls) {
      let promise = Promise.resolve();
      urls.forEach((url, index) => {
        promise = promise.then(() => {
          return this.download(url);
        });
      });
      return promise;
    },

    // 下载
    download(url) {
      return new Promise((resolve, reject) => {
        wx.downloadFile({
          url: url,
          success: function (res) {
            var temp = res.tempFilePath;
            wx.saveImageToPhotosAlbum({
              filePath: temp,
              success: function (res) {
                resolve(res);
              },
              fail: function (err) {
                reject(res);
              }
            });
          },
          fail: function (err) {
            reject(err);
          }
        });
      });
    },

    //预览图片
    preImage(e) {
      a = true;
      var url = e.currentTarget.dataset.url;
      var findex = e.currentTarget.dataset.idx;
      var index = e.currentTarget.dataset.index;
      wx.previewImage({
        current: url,
        // 当前显示图片的http链接
        urls: this.list[findex][index].img_list // 需要预览的图片http链接列表

      });
    },

    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];
        });
      });
    }
  }
};
</script>
<style rel="stylesheet/less" lang="less">
    @import "find";
</style>
