<template>
  <div class="shop-index">
    <div class="shop-head">
      <div class="shop-logo">
        <div class="img">
          <img :src="this.shopInfo.shopLogo" alt />
        </div>
        <div class="text">
          <div class="name">{{ this.shopInfo.shopName }}</div>
          <div class="operation">
            <div class="self" v-if="this.shopInfo.shopId == 1">
              {{ $t('shopInfo.selfShop') }}
            </div>
            <div class="self" v-else>
              {{ this.shopInfo.type == 1 ? $t('shopInfo.preferredStores') : $t('shopInfo.generalStore') }}
            </div>
            <div
              class="favourite"
              :class="{ active: this.isCollection }"
              @click="shopCollection()"
            >
              <i class="icon"></i>
              {{ this.isCollection ? $t('shopInfo.followed') : $t('shopInfo.follow') }}
            </div>
          </div>
        </div>
      </div>
      <div class="shop-news">
        <div class="news-tit">
          <div class="tit">{{$t('storeAnnouncement')}}</div>
          <div class="more" @click="toNewsList" v-if="noticeList.length">
            {{$t('more')}}&nbsp;&nbsp;
          </div>
        </div>
        <div class="news-list-con" v-if="noticeList.length">
          <div
            class="news-item"
            v-for="(news, index) in noticeList"
            :key="index"
            @click="toNewsDet(news.id)"
          >
            {{ news.title }}
          </div>
        </div>
        <div class="news-empty" v-else>
          {{$t('shopInfo.noAnnouncement')}}
        </div>
      </div>
    </div>
    <div class="shop-menu">
      <div class="menu-box">
        <div class="menu-list">
          <div class="menu">
            <a href="javascript:void(0);" @click="homePage" class="menu-link"
              >{{$t('shopInfo.homePage')}}</a
            >
          </div>
          <div class="menu all-category">
            <a
              href="javascript:void(0);"
              class="menu-link"
              @click="getProdListByCategory()"
              >{{$t('shopInfo.allCategories')}}</a
            >
            <div class="menu-wrap">
              <div
                class="wrap-item"
                v-for="category in this.categoryList"
                :key="category.categoryId"
                v-show='category.categoryId'
              >
                <div class="item-tit">
                  <a
                    href="javascript:void(0);"
                    @click="getProdListByCategory(category.categoryId)"
                    >{{ category.categoryName }}</a
                  >
                </div>
              </div>
              <div class='item-tit-no' v-show='this.categoryList.length===0'>{{$t('shopInfo.noData')}}</div>
            </div>
          </div>
          <div
            class="menu"
            v-for="category in categoryList"
            :key="category.categoryId"
          >
            <a
              href="javascript:void(0);"
              @click="getProdListByCategory(category.categoryId)"
              class="menu-link"
              >{{ category.categoryName }}</a
            >
          </div>
          <!-- <div class="menu">
            <a href="javascript:void(0)" class="menu-link">热卖排行</a>
          </div>
          <div class="menu">
            <a href="javascript:void(0)" class="menu-link">臻美配饰</a>
          </div>
          <div class="menu">
            <a href="javascript:void(0)" class="menu-link">绅士男表</a>
          </div>
          <div class="menu">
            <a href="javascript:void(0)" class="menu-link">优雅女表</a>
          </div>
          <div class="menu">
            <a href="javascript:void(0)" class="menu-link">表白礼物</a>
          </div>-->
        </div>
        <div class="shop-search">
          <input type="text" class="s-input" v-model="prodName" />
          <input
            type="button"
            :value="$t('shopInfo.search')"
            class="s-btn"
            @click="getSearchProdPage(1)"
          />
        </div>
      </div>
    </div>
    <!--
    <div class="shop-banner">
      <img src="~/assets/img/banner.png" alt />
    </div>-->
    <!-- banner -->
    <div class="banner" v-if="banners.length > 0">
      <el-carousel height="450px" style="overflow-y: hidden;">
        <el-carousel-item v-for="banner in banners" :key="banner.imgUrl">
          <img
            :src="banner.imgUrl"
            style="width:100%;height:100%;"
            @click="imgToProd(banner)"
          />
        </el-carousel-item>
      </el-carousel>
    </div>
    <!-- /banner -->
    <div class="content">
      <div class="shop-content">
        <div class="tit" v-if="prodList.length > 0">
          <span class="bg-l"></span>
          {{ this.categoryName ? this.categoryName : $t('shopInfo.hotProducts') }}
          <span class="bg-r"></span>
        </div>
        <div class="goods-list">
          <div class="list-con">
            <!-- 商品 -->
            <div class="item" v-for="prod in prodList" :key="prod.prodId">
              <div class="goods-img" @click="toProdDetail(prod.prodId)">
                <img v-if="prod.pic" :src="prod.pic" alt />
                <img v-else src="~/assets/img/def.png" alt />
              </div>
              <div class="goods-msg" @click="toProdDetail(prod.prodId)">
                <div class="goods-name">{{ prod.prodName }}</div>
                <div class="goods-price">
                  <div class="price">
                    ￥
                    <span class="big"
                      >{{ parsePrice(prod.price)[0] }}.{{
                        parsePrice(prod.price)[1]
                      }}</span
                    >
                  </div>
                </div>
              </div>
            </div>
            <!-- 商品 -->
            <div class="empty" v-if="prodList.length < 1">
              <div class="img">
                <img src="~/assets/images/emptyPic/not-found.png" alt />
              </div>
              <div v-if="prodList.length < 1 && shopInfo.shopStatus === 1" class="action">
                <div class="text">{{$t('sorryNoRelatedProducts')}}</div>
                <nuxt-link :to="Object.getOwnPropertyNames($route.query).length==1?'/':'/shopIndex?sid=' + shopId" class="btn">{{$t('lookAtOther')}}</nuxt-link>
                <nuxt-link to="/" class="btn-r">{{$t('shopInfo.mallHome')}}</nuxt-link>
              </div>
              <div v-if="shopInfo.shopStatus !== 1" class="action">
                <div class="text">{{$t('collection.storeReviewTips4')}}</div>
                <nuxt-link to="/" class="btn">{{$t('shopInfo.mallHome')}}</nuxt-link>
              </div>
            </div>
          </div>
        </div>
        <!-- 全部 -->
        <br />
        <div class="goods-list">
          <!-- 页码 -->
          <pagination
            v-model="current"
            :pages="pages"
            @changePage="getSearchProdPage"
          ></pagination>
          <!-- /页码 -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Cookie from 'js-cookie'
import PageUtil from '~/plugins/pageUtil'
import { mapState } from 'vuex'
import Pagination from '~/components/pagination'
export default {
  components: {
    Pagination
  },
  data() {
    return {
      shopId: null //店铺id
    }
  },
  /**
   * pn: 商品名称
   * cid: 店铺分类id
   * sid: 店铺id
   * sort: 根据默认(0)/销量(1)/价格(2)排序
   * size: 每页的数据数量
   * ob: 0正序 1倒序
   * c: 当前第几页
   * @param query
   */

  async asyncData({ app, query, store }) {
    let [prodPage, categoryList, shopInfo, banners, shopNews] = await Promise.all([
      app.$axios.get(
        // query.st == 4 ? '/coupon/prodListByCouponId' : '/search/searchProdPage',
        query.st == 4 ? '/coupon/prodListByCouponId' : '/search/page',
        {
          //商品列表
          params: {
            sort: 12,
            size: 20,
            // orderBy: parseInt(query.ob) || 0,
            current: query.c ? query.c : 1,
            shopId: query.sid,
            couponId: query.couponId || '',
            keyword: query.pn || null,
            shopCategoryId: query.cid || '',
            isAllProdType: true,
            isActive: query.st != 4 ? 1 : undefined // 过滤掉活动商品
          }
        }
      ),
      app.$axios.get('/category/categoryInfo', {
        //店铺商品分类
        params: {
          shopId: query.sid,
          parentId: 0
        }
      }),
      app.$axios.get('/shop/headInfo', {
        //店铺头部信息
        params: {
          shopId: query.sid
        }
      }),
      app.$axios.get('/indexImgs/' + query.sid, {
        //轮播图
        params: {
          imgType: 1
        }
      }),
      app.$axios.get('/shop/notice/noticeList/' + query.sid, {
        //店铺公告
        params: {
          current: 1, //当前页
          size: 2
        }
      })
    ])
    var colled = null
    if (Cookie.get('token')) {
      colled = await app.$axios.get('/p/shop/collection/isCollection', {
        params: {
          shopId: query.sid
        }
      })
    }
    store.commit('shopCategory/SET_SHOPCATEGROY', categoryList.data)
    const curShopCategroy = categoryList.data.find(el => el.categoryId == query.cid)
    return {
      prodPage: prodPage.data,
      categoryList: categoryList.data,
      shopInfo: shopInfo.data,
      noticeList: shopNews.data.records,
      banners: banners.data,
      isCollection: colled?colled.data:colled,
      categoryId: query.cid ? query.cid : '',
      prodName: query.pn,
      current: query.c ? query.c : 1,
      categoryName: curShopCategroy ? curShopCategroy.categoryName : ''
    }
  },
  data() {
    return {
      shopId: this.$route.query.sid || 0,
      categoryId: '',
      prodName: '',
      page: {
        pages: 0, // 总页数
        rainbow: [] // 分页条
      },
      // pages: 0,
      categoryList: [],
      // prodList: [],
      prodPage: [],
      banners: [],
      isCollection: false,
      noticeList: []
    }
  },
  // 监听路径参数，监听的几个参数，若某一个值改变，则触发asyncData事件
  watchQuery: ['sid', 'cid', 'c', 'pn'],
  computed: {
    prodList() {
      console.log(this.prodPage)
      return  this.$route.query.st == 4 ? this.prodPage.records : this.prodPage.records[0].products
    },
    pages() {
      return this.prodPage.pages
    }
  },
  mounted() {
    document.title = this.$i18n.t('shopInfo.storeHome')
    this.handleShopStatus()
    this.getInfo()
    this.getUserCollection()
    if(!this.shopId){

      this.$message({
        message: this.$t('userCenter.theStoreOffline'),
        duration: 1000,
        type: 'warning'

      });

      return
    }
  },
  methods: {
    /**
     * 店铺状态处理
     */
    handleShopStatus() {
      const shopStatus = this.shopInfo.shopStatus
      // 未开通/已删除
      if (shopStatus === -1) {
        this.$message({
          type: 'warning',
          message: this.$i18n.t('collection.storeReviewTips2'),
          duration: 1000,
          onClose: () => {
            this.$router.push({ path: '/' })
          }
        })
        return
      }
      // 停业中
      if (shopStatus === 0) {
        const contractStartTime = new Date(data.contractStartTime).getTime()
        const contractEndTime = new Date(data.contractEndTime).getTime()
        const today = new Date().getTime()
        // 1、店铺状态为0(停业中)时，当店铺未到签约开始时间，用户进入店铺提示：商家尚未营业
        if (today < contractStartTime) {
          this.$message({
            type: 'warning',
            message: this.$i18n.t('collection.storeReviewTips4'),
            duration: 1000,
            onClose: () => {
              this.$router.push({ path: '/' })
            }
          })
          return
        }
        // 2、店铺状态为0(停业中)时，当店铺超过签约有效期，用户进入店铺提示：商家已暂停未营业
        if (today > contractEndTime) {
          this.$message({
            type: 'warning',
            message: this.$i18n.t('collection.storeReviewTips5'),
            duration: 1000,
            onClose: () => {
              this.$router.push({ path: '/' })
            }
          })
          return
        }
      }
      // 已下线
      if (shopStatus === 2 || shopStatus === 3) {
        this.$message({
          type: 'warning',
          message: this.$i18n.t('collection.storeReviewTips3'),
          duration: 1000,
          onClose: () => {
            this.$router.push({ path: '/' })
          }
        })
        return
      }
    },

    /**
     * 跳转公告详情
     */
    toNewsDet(id) {
      this.$router.push({
        path: '/notice-detail',
        query: { id: id, shopId: this.shopId, shopName: this.shopInfo.shopName }
      })
    },
    /**
     * 跳转公告列表
     */
    toNewsList() {
      this.$router.push({
        path: '/notice-list',
        query: { shopId: this.shopId, shopName: this.shopInfo.shopName  }
      })
    },
    /**
     * 获取店铺公告
     */
    getShopNews() {

      if(!this.shopId){

        this.$message({

          message: this.$t('userCenter.theStoreOffline'),
          duration: 1000,
          type: 'warning'

        });

        return
      }

      this.$axios
        .get('/shop/notice/noticeList/' + this.shopId, {
          params: {
            current: 1, //当前页
            size: 2
          }
        })
        .then(({ data }) => {
          this.noticeList = data.records
        })

    },
    /**
     * 获取店铺信息
     */
    getInfo() {
      if (!this.$route.query.sid) {
        this.shopId = this.shopInfo.shopId
      }
      // this.pages = this.prodPage.pages
      // this.prodList = this.prodPage.records
      // this.current = this.prodPage.current
      if (this.categoryId) {
        this.categoryList.forEach(category => {
          if (this.categoryId === category.categoryId.toString()) {
            this.categoryName = category.categoryName
          }
        })
      }
    },
    /**
     * 获取用户是否收藏此店铺
     */
    getUserCollection() {
      this.$axios
        .get('/p/shop/collection/isCollection', {
          params: {
            shopId: this.shopId
          }
        })
        .then(({ data }) => {
          this.isCollection = data
        })
    },
    /**
     * 收藏店铺/取消收藏
     */
    shopCollection() {
      this.$axios
        .post('/p/shop/collection/addOrCancel', this.shopId)
        .then(({ data }) => {
          if (data) {
            this.$message({
              message: this.$t('prodDetail.collectionSuccess'),
              type: 'success',
              duration: 1000
            })
          } else {
            this.$message({
              message: this.$t('prodDetail.uncollected'),
              duration: 1000
            })
          }
          this.getUserCollection()
        })
    },
    /**
     * 去到首页
     */
    homePage(){
      if(this.shopId){
        this.$router.push({ path: `/shopIndex?sid=${this.shopId}` })
      }else {
        this.$message({
            type: 'warning',
            message:this.$t('userCenter.theStoreOffline')
        })
      }
    },
    /**
     * 查询该分类下的商品
     */
    getProdListByCategory(categoryId) {
      if(this.shopId){
        if (!categoryId) {
          this.$router.push(`/shopIndex?sid=${this.shopId}`)
        } else {
          this.$router.push(`/shopIndex?sid=${this.shopId}&cid=${categoryId}`)
        }
      }else {
        this.$message({
            type: 'warning',
            message:this.$t('userCenter.theStoreOffline')
        })
      }

    },
    /**
     * 搜索商品/查询指定分页下的商品
     */
    getSearchProdPage(current) {
      let prodName = this.prodName ? this.prodName.trim() : ''
      var url = '/shopIndex?sid=' + this.shopId + '&c=' + current
      //通过商品名称搜索
      if (prodName) {
        url = url + '&pn=' + prodName
      }
      //在分类查询的基础上查询/分页
      if (this.categoryId) {
        url = url + '&cid=' + this.categoryId
      }
      // window.location.href = url
      this.$router.push( url )
    },
    /**
     * 轮播图跳转到商品
     */
    imgToProd(banner) {
      if(banner.type !== 0) {
        return
      }
      let prodId = banner.relation
      // 兼容火狐浏览器打开新窗口
      const newWindow = window.open()
      this.$axios
        .get('/prod/isStatus', {
          params: {
            prodId: prodId
          }
        })
        .then(({ data }) => {
          if (data) {
            this.toProdDetail(prodId, newWindow)
          }
        })
    },
    /**
     * 跳转到商品
     */
    toProdDetail(prodId, newWindow) {
      const params = {
        prodId,
        lang: this.$store.state.locale
      }
      const newPage = this.$router.resolve({ name: 'detail-prodId', query: params, params })
      if (newWindow) {
        newWindow.location.href = newPage.href
      } else {
        window.open(newPage.href, '_blank')
      }
    },
    /**
     * 价格处理
     */
    parsePrice: value => {
      var val = Number(value)
      if (!val) {
        val = 0
      }
      // 截取小数点后两位，并以小数点为切割点将val转化为数组
      return val.toFixed(2).split('.')
    }


  },

  // 监听id，要是发生变化就重新请求数据
  watch: {
    $route:(to, from)=>{
      // //要处理的操作
      // // console.log(this.queryId)
      // // let routeId = this.$route.query.sid
      // this.getShop(to.query.sid)
      // console.log(to.query.sid)
      // 路由变话页面刷新
      if(to.query.sid===from.query.sid) return
      location.reload()
    }
  }
}
</script>

<style scoped src='~/assets/css/shop-index.css'></style>
<style scoped>
.el-pagination {
  text-align: right;
  padding: 0 30px;
  padding-top: 20px;
}
.pagination .el-pagination button,
.el-pagination span:not([class*='suffix']) {
  padding: 0 8px !important;
}
.pagination .el-pagination.is-background .btn-next,
.el-pagination.is-background .btn-prev,
.el-pagination.is-background .el-pager li {
  background-color: #fff !important;
}
.pagination .el-pagination__editor.el-input .el-input__inner {
  width: 30px !important;
}

.empty .action .btn-r {
  display: inline-block;
  padding: 6px 18px;
  border: 1px solid #ddd;
  background: #f9f9f9;
  border-radius: 30px;
  margin-top: 20px;
  margin-left: 10px;
  color: #666;
}

.empty .action .btn-r:hover {
  background: #fff;
}
.goods-list .list-con .item .goods-msg .goods-name{
  height: 18px;
}
</style>
