<!--
  @description:搜索导航
  @Modifier：qk
  @date：  2019-12/16-14:46
-->
<template>
  <div class="search-wrap">
    <div class="middle_width1190 shopmall_home">
      <div class="logo_wrap clearfix">
        <div class="title_guoxin fl">
          <router-link to="/shop/shopHome">
            <!-- <img src="@assets/img/shopmall/bannerLogo.png" class="logo"> -->
            <div class="logo">
              <img :src="WebConfig.imgMajor">
            </div>
            <h2>网上商城</h2>
          </router-link>
        </div>
        <!--搜索-->
        <div class="search_inline fl">
          <el-input v-model="searchForm.keywords" placeholder="请输入商品名称、品牌" size="medium" @keyup.13.native="searchGood">
            <el-button slot="append" @click="searchGood">
              搜索
            </el-button>
          </el-input>
        </div>
        <!--购物车-->
        <div v-if="roleCode==='19'" class="shopcar_box fr" @mouseenter="showGoods" @mouseleave="hideGoods">
          <div class="cart_btn_wrap" @click="goToShopCar">
            <i class="iconfont icon-xingzhuang8" />
            <span
              v-if="shopcarList && shopcarList.length"
              class="ci-count"
            >{{ totalShopLen }}</span>
            <span class="cart">我的购物车</span>
          </div>
          <div v-if="show" class="new_goods">
            <div v-if="resultList.length" class="new_title">
              最新加入的商品
            </div>
            <div v-else style="padding:10px 0">
              <img src="@/assets/img/shopmall/isLogin.png" style="margin-right: 10px;" alt>
              购物车中还没有商品，赶紧挑选吧！
            </div>
            <template>
              <dl
                v-for="(item,index) in resultList"
                :key="index"
                class="item_goods"
                @click="goDetail(item)"
              >
                <dt>
                  <img :src="item.productPicture">
                </dt>
                <dd class="goods_name goods_item_title_two">
                  <p>{{ item.goodsName }}</p>
                </dd>
                <dd class="action_goods">
                  <div class="price">
                    ￥{{ item.unitPrice }}
                    <span>x {{ item.number }}</span>
                  </div>
                  <span class="del_goods" @click.stop="delGoods(item)">删除</span>
                </dd>
              </dl>
            </template>
          </div>
        </div>
      </div>
      <section class="nav middle_width1190 cursor">
        <!--全部分类按钮-->
        <div
          ref="categorys"
          :class="{fixed:navFixed}"
          class="dorpdown clearfix"
          @mouseenter="enter(searchChildrenData.current)"
          @mouseleave="leave(searchChildrenData.current)"
        >
          <p class="title fl">
            全部商品分类
          </p>
          <!--全部商品分类楼层导航-->
          <div :class="searchChildrenData.seen?'active':''" class="grid_c1" style="cursor:pointer;" @mouseleave="hideDetail">
            <div class="nav_li" :style="{'top':isDorpdown?'0px':'10px'}">
              <ul id="nav_left" class="cate_menu" style="padding:0;height:400px;">
                <li
                  v-for="(item,index) in goodsListData"
                  :key="index"
                  :class="[currentIndex==index?'hover_active':'']"
                  class="cursor"
                  @mouseenter="showDetail(item,index)"
                  @click="goToGoodsClassList(item)"
                >
                  <i :class="'icon_'+index" />
                  {{ item.name }}
                </li>
              </ul>
              <el-scrollbar :class="activeClass ?'active':''" class="hover_box scrollbar">
                <div v-for="(item,k) in goodsTwoLevelList" :key="k" class="itema">
                  <div class="item_atitle clearfix">
                    <span class="fl cate_detail_tit" @click="more(item)">{{ item.name }}</span>
                    <span class="fr cate_detail_more" @click="more(item)">更多</span>
                  </div>
                  <ul class="item_acontent clearfix">
                    <li
                      v-for="(row,i) in goodsTwoLevelList[k].children"
                      :key="i"
                      @click="reclassify(row,item)"
                    >
                      {{ row.name }}
                    </li>
                  </ul>
                </div>
              </el-scrollbar>
            </div>
          </div>
        </div>
        <!--供应商导航列表-->
        <ul class="navitems_group" style="padding-left: 230px">
          <li v-for="(item,index) in navList" :key="index" :class="activeLi === index?'actives':''" class="pointer nav-btn" @click="goodsCategorys(item,index)">
            <img :src="item.image">
          </li>
        </ul>
      </section>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/assets/js/utils/auth'
import { searchProduct, searchScreen } from '@/api/shoppingmall/products'
import { deleteShoppingCart } from '@/api/shoppingmall/order'
import { mapGetters } from 'vuex'
// import $ from 'jquery'
export default {
  name: 'Search',
  props: {
    searchChildrenData: {
      type: Object,
      default: function() {
        return {}
      }
    },
    goodsListData: {
      type: Array,
      default: function() {
        return []
      }
    },
    // 是否可以下拉列表
    isDorpdown: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      type: 2,
      active: -1, // 导航高亮
      activeLi: -1,
      flg: false,
      navFixed: false, // 是否固定
      isLogin: false, // 是否登录
      activeClass: false, // 动态添加class 是否显示二级分类面板
      currentIndex: null, // 当前选择分类
      seen: false, // 动态添加class 是否显示一级全部分类列表
      show: false, // 是否显示购物车三件商品
      shopcarList: [], // 三件商品列表
      totalShopLen: 0, // 购物车总数
      // 搜索
      searchForm: {
        stock: '1',
        departmentType: '',
        keywords: '',
        brandId: '',
        pageNo: 0, // 当前页
        pageSize: 25, // 每页条数
        sort: 0, // 复杂搜索时使用： 排序字段:0->按相关度；1->按新品；2->按销量从高到低 3-> 按销量从低到高；4->价格从低到高；5->价格从高到低 默认请赋0
        productClassifies: '', // this.$route.query.id ? this.$route.query.id : ''
        priceEnd: 0, // 复杂搜索时使用： 最大价格
        priceStart: 0 // 复杂搜索时使用： 最小价格
      },
      // 导航 供应商列表
      navList: [
        {
          name: '晨光科力普',
          dataName: 'chenguang',
          index: 0,
          image: require('@/assets/img/shopmall/nav-btn-02.png')
        },
        // {
        //   name: '史泰博',
        //   dataName: 'oms',
        //   index: 1
        // },
        // {
        //   name: '京东',
        //   dataName: 'jd',
        //   index: 2
        // },
        // {
        //   name: '固安捷',
        //   dataName: 'guanjie',
        //   index: 3
        // }, {
        //   name: '震坤行',
        //   dataName: 'zhenkunhang',
        //   index: 4
        // },
        // {
        //   name: '自营超市',
        //   dataName: 'self',
        //   index: 5
        // },
        {
          name: '得力',
          dataName: 'deli',
          index: 6,
          image: require('@/assets/img/shopmall/nav-btn-01.png')
        }
      ],
      // goodsList: [], // 商品分类列表
      goodsTwoLevelList: [], // 分类对应二级列表
      // 删除购物车商品
      delGoodsData: {
        ids: []
      },
      resultList: [],
      roleCode: '' // 当前登录人的code
    }
  },
  computed: {
    ...mapGetters(['getNewShoppingCart', 'activesa', 'WebConfig'])
  },
  watch: {
    getNewShoppingCart(val) {
      this.shopcarList = val.records
      this.totalShopLen = val.total
      this.resultList = val.records.slice(0, 3)
    },
    // 解决刷新时，roleCode undefined报错
    '$store.getters.info'() {
      this.roleCode = this.$store.getters.info.currentRol.roleCode
    }
  },
  created() {
    // 初始化
    this.init()
  },
  mounted() {
    // 初始化
    this.initMount()
  },
  methods: {
    init() {
      if (this.$route.query.keywords === 'chenguang') {
        this.activeLi = 0
      }
      // if (this.$route.query.keywords === 'oms') {
      //   this.activeLi = 1
      // }
      // if (this.$route.query.keywords === 'jd') {
      //   this.activeLi = 1
      // }
      // if (this.$route.query.keywords === 'guanjie') {
      //   this.activeLi = 3
      // }
      // if (this.$route.query.keywords === 'zhenkunhang') {
      //   this.activeLi = 4
      // }
      // if (this.$route.query.keywords === 'self') {
      //   this.activeLi = 2
      // }
      if (this.$route.query.keywords === 'deli') {
        this.activeLi = 1
      }
      // 校验是否登录
      this.isLogin = !!getToken()
      if (getToken()) {
        this.isLogin = true
        // 获取购物车列表
        this.getShoppingCart()
      }
    },
    initMount() {
      // 解决刷新时，roleCode undefined报错
      this.roleCode = this.$store.getters.info.currentRol?.roleCode
      window.addEventListener('scroll', this.handleScroll, true)
      // // 查询分类json树
      // const pid = ''
      // getgoodsclassTree(pid).then(response => {
      //   this.goodsList = response.data
      //   this.$emit('goodsCategory', this.goodsList)
      // }).catch(() => {

      // })
      if (this.$route.query.keywordsa) {
        this.searchForm.keywords = this.$route.query.keywordsa
        this.searchForm.departmentType = this.$route.query.keywords
      }
      // if (this.$route.query.keywordsa) {
      //   this.searchForm.keywords = this.$route.query.keywordsa
      // }
    },
    // 点击一级分类主页去商品列表
    goToGoodsClassList(item) {
      this.searchForm.keywords = ''
      this.$emit('watchData', item)
      sessionStorage.setItem('firstClassNames', JSON.stringify(item.name))
      sessionStorage.removeItem('secondClassName')
      sessionStorage.removeItem('threeClassName')
      if (this.$route.query.keywords) {
        const keys = this.$route.query.keywords
        let firstTtile = ''
        this.navList.forEach((item) => {
          if (item.dataName === keys) {
            firstTtile = item.name
          }
        })
        sessionStorage.setItem('firstClassNames', firstTtile)
        sessionStorage.setItem('secondClassName', JSON.stringify(item))
        this.$store.commit('SET_BREAD_NAV', firstTtile)
        this.$store.commit('SET_BREAD_NAVA', item)
        this.$store.commit('SET_BREAD_NAVB', 0)
        this.searchChildrenData.seen = false
        this.$router.push({
          path: '/shop/goodsClassList',
          query: {
            keywords: keys,
            id: item.classifyNo
          }
        })
      } else {
        if (this.$route.query.keywordsa) {
          this.searchForm.keywords = ''
          this.$store.commit('SET_BREAD_NAVA', 0)
          this.$store.commit('SET_BREAD_NAVB', item)
          this.searchChildrenData.seen = false
          this.$router.push({
            path: '/shop/goodsClassList',
            query: {
              id: item.classifyNo
            }
          })
        } else {
          this.$store.commit('SET_BREAD_NAVA', 0)
          this.$store.commit('SET_BREAD_NAVB', 0)
          this.$store.commit('SET_BREAD_NAV', item)
          this.searchChildrenData.seen = false
          this.$router.push({
            path: '/shop/goodsClassList',
            query: {
              id: item.classifyNo
            }
          })
        }
      }
      // this.$store.commit('SET_BREAD_NAV', item)
      // this.$store.commit('SET_BREAD_NAVA', 0)
      // this.$store.commit('SET_BREAD_NAVB', 0)
      // this.searchChildrenData.seen = false
      // this.$router.push({
      //   path: '/shop/goodsClassList',
      //   query: {
      //     id: item.classifyNo
      //   }
      // })
      this.searchChildrenData.seen = false
    },
    // 点击更多二级分类主页去商品列表
    more(item) {
      this.searchForm.keywords = ''
      if (this.$route.query.keywords) {
        const keys = this.$route.query.keywords
        let firstTtile = ''
        this.navList.forEach((item) => {
          if (item.dataName === keys) {
            firstTtile = item.name
          }
        })
        sessionStorage.setItem('firstClassNames', firstTtile)
        sessionStorage.setItem('secondClassName', JSON.stringify(item))
        sessionStorage.removeItem('threeClassName')
        this.$store.commit('SET_BREAD_NAV', firstTtile)
        this.$store.commit('SET_BREAD_NAVA', item)
        this.$store.commit('SET_BREAD_NAVB', 0)
        this.searchChildrenData.seen = false
        this.$emit('watchData', item)
        this.$router.push({
          path: '/shop/goodsClassList',
          query: {
            keywords: keys,
            id: item.classifyNo
          }
        })
      } else {
        if (this.$route.query.keywordsa) {
          this.searchForm.keywords = ''
          this.$store.commit('SET_BREAD_NAVA', 0)
          this.$store.commit('SET_BREAD_NAVB', item)
          this.searchChildrenData.seen = false
          this.$emit('watchData', item)
          this.$router.push({
            path: '/shop/goodsClassList',
            query: {
              id: item.classifyNo
            }
          })
        } else {
          sessionStorage.removeItem('firstClassNames')
          sessionStorage.removeItem('threeClassName')
          this.$store.commit('SET_BREAD_NAVA', item)
          this.$emit('watchData', item)
          this.$store.commit('SET_BREAD_NAVB', 0)
          sessionStorage.setItem('secondClassName', JSON.stringify(item))
          this.$router.push({
            path: '/shop/goodsClassList',
            query: {
              id: item.classifyNo
            }
          })
        }
      }

      this.searchChildrenData.seen = false
    },
    // 点击更多三级分类主页去商品列表
    reclassify(row, item) {
      this.searchForm.keywords = ''
      this.$emit('watchData', row)
      if (this.$route.query.keywords) {
        const keys = this.$route.query.keywords
        let firstTtile = ''
        this.navList.forEach((item) => {
          if (item.dataName === keys) {
            firstTtile = item.name
          }
        })
        sessionStorage.setItem('firstClassNames', firstTtile)
        sessionStorage.setItem('secondClassName', JSON.stringify(item))
        sessionStorage.setItem('threeClassName', JSON.stringify(row))
        this.$store.commit('SET_BREAD_NAV', firstTtile)
        this.$store.commit('SET_BREAD_NAVA', item)
        this.$store.commit('SET_BREAD_NAVB', row)
        this.searchChildrenData.seen = false
        this.$emit('watchData', row)
        this.$router.push({
          path: '/shop/goodsClassList',
          query: {
            keywords: keys,
            id: row.classifyNo
          }
        })
      } else {
        if (this.$route.query.keywordsa) {
          this.searchForm.keywords = ''
          this.$store.commit('SET_BREAD_NAVA', item)
          this.$store.commit('SET_BREAD_NAV', 0)
          this.$store.commit('SET_BREAD_NAVB', row)
          this.searchChildrenData.seen = false
          this.$emit('watchData', row)
          this.$router.push({
            path: '/shop/goodsClassList',
            query: {
              id: row.classifyNo
            }
          })
        } else {
          sessionStorage.removeItem('secondClassName')
          sessionStorage.setItem('threeClassName', JSON.stringify(row))
          sessionStorage.setItem('firstClassNames', JSON.stringify(item))
          this.$store.commit('SET_BREAD_NAVB', row)
          // this.$store.commit('SET_BREAD_NAVA', 0)
          this.$store.commit('SET_BREAD_NAV', item)
          this.$router.push({
            path: '/shop/goodsClassList',
            query: {
              id: row.classifyNo
            }
          })
        }
      }

      this.searchChildrenData.seen = false
    },
    // 鼠标移入全部商品分类
    enter() {
      this.searchChildrenData.seen = true
    },
    // 鼠标移出全部商品分类
    leave(isShowSeen) {
      // 判断离开全部分类是否显示导航
      if (isShowSeen) {
        this.searchChildrenData.seen = true
      } else {
        this.searchChildrenData.seen = false
      }
    },
    // 左侧商品类别
    showDetail(item, index) {
      // sessionStorage.setItem('firstClassName', JSON.stringify(item))
      // if (this.$route.query.keywords) {
      //   this.$store.commit('SET_BREAD_NAVA', 0)
      //   this.$store.commit('SET_BREAD_NAVB', item)
      // } else {
      //   if (this.$route.query.keywordsa) {
      //     this.$store.commit('SET_BREAD_NAVA', 0)
      //     this.$store.commit('SET_BREAD_NAVB', item)
      //   } else {
      //     this.$store.commit('SET_BREAD_NAVA', 0)
      //     this.$store.commit('SET_BREAD_NAVB', 0)
      //     this.$store.commit('SET_BREAD_NAV', item)
      //     sessionStorage.setItem('firstClassNames', JSON.stringify(item))
      //   }
      // }
      this.goodsTwoLevelList = item.children
      this.activeClass = true
      this.currentIndex = index
    },
    hideDetail() {
      this.activeClass = false
      this.currentIndex = null
    },
    // 楼层滚动
    handleScroll() {
      // const scrollTop = document.getElementById('layout').scrollTop
      // scrollTop >= 100 ? this.st = true : this.st = false
      /*      let offsetTop = document.querySelector('#searchBar').offsetTop
      if (scrollTop <= 200) {
        offsetTop = 300 - Number(scrollTop)
        document.querySelector('#searchBar').style.top = offsetTop + 'px'
      } else {
        document.querySelector('#searchBar').style.top = '100px'
      }*/
      /*
      const eTop = $('.index_goods').eq(0).offset().top
      const sTop = $('.container').scrollTop()
      $('.index_goods').each(function(index, val) {
        const loutitop = $(val).offset().top + 1000
        if (loutitop > sTop) {
          $('.nav_fixed li').removeClass('active')
          $('.nav_fixed li').eq(index).addClass('active')
          return false
        }
      })
      if (eTop <= sTop) {
        this.fixed = true
      } else {
        this.fixed = false
      }
*/
    },
    // 获取购物车三件商品
    getShoppingCart() {
      // 调用vuex获取购物车列表方法
      const data = {
        pageNo: 1,
        pageSize: 3
      }
      this.$store.dispatch('loadShoppingCart', data).then(() => {
      }).catch(() => {

      })
    },
    // 显示购物车三件商品
    showGoods() {
      this.show = true
      /*   const number = $('#number').text() * 1 >= 1
      if (number) {
        this.show = true
      }*/
    },
    // 隐藏购物车三件商品
    hideGoods() {
      this.show = false
    },
    // 进入购物车
    goToShopCar() {
      if (!this.isLogin) {
        this.$message({
          type: 'warning',
          message: '请先登录！'
        })
      } else {
        this.$router.push('/shop/myshoppingCart')
      }
    },
    // 搜索商品
    searchGood() {
      if (this.$route.query.keywords) {
        this.searchForm.departmentType = this.$route.query.keywords
      } else {
        this.searchForm.departmentType = ''
        if (!this.searchForm.keywords) {
          this.$router.push('/shop/shopHome')
          return
        }
      }
      /*  this.searchForm.departmentType = ''*/
      // this.activeLi = -1
      if (this.$route.query.keywords) {
        this.$store.commit('SET_BREAD_NAVA', this.searchForm.keywords)
        this.$store.commit('SET_BREAD_NAVB', 0)
      } else {
        this.$store.commit('SET_BREAD_NAV', this.searchForm.keywords)
        sessionStorage.setItem('firstClassNames', this.searchForm.keywords)
        sessionStorage.removeItem('secondClassName')
        sessionStorage.removeItem('threeClassName')
        this.$store.commit('SET_BREAD_NAVB', 0)
        this.$store.commit('SET_BREAD_NAVA', 0)
      }
      if (this.$route.query.id) {
        this.$store.commit('SET_BREAD_NAVB', 0)
        this.$store.commit('SET_BREAD_NAVA', 0)
      }
      this.$emit('watchKeys', this.searchForm.keywords)
      this.searchForm.pageNo = 0
      searchProduct(this.searchForm).then(res => {
        this.$emit('watchDatas', res.data)
      }).catch(() => {
      })
      searchScreen(this.searchForm).then(res => {
        this.$emit('watchDataeny', res.data)
      })
      this.$router.push({
        path: '/shop/goodsClassList',
        query: { keywordsa: this.searchForm.keywords, keywords: this.$route.query.keywords }
      })
    },
    // 点击导航去商品列表
    goodsCategorys(item, index) {
      // this.searchForm.keywords = ''
      this.$store.commit('SET_ACTIVE_CLASS', index - 1)
      this.$store.commit('SET_BREAD_NAV', item.name)
      this.$store.commit('SET_BREAD_NAVA', 0)
      this.$store.commit('SET_BREAD_NAVB', 0)
      sessionStorage.removeItem('secondClassName')
      sessionStorage.removeItem('threeClassName')
      sessionStorage.setItem('firstClassNames', item.name)
      this.activeLi = index
      this.$emit('tabSearch', item)
      this.$router.push({
        path: '/shop/goodsClassList',
        query: {
          keywords: item.dataName,
          keywordsa: this.searchForm.keywords
        }
      })
      // this.activeLi = -1
    },
    // 删除购物车商品
    delGoods(item) {
      this.$confirm('确定将该商品移出购物车吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        // 调用删除购物车商品接口
        this.delGoodsData.ids.push(item.id)
        deleteShoppingCart(this.delGoodsData).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getShoppingCart()
        }).catch(() => {

        })
      }).catch(() => {
      })
    },
    // 去商品详情
    goDetail(item) {
      if (this.$route.path === '/shop/goodsClassDetail') {
        this.$router.push({
          path: '/shop/goodsClassDetail',
          query: {
            id: item.goodsId
          }
        })
        location.reload()
      } else {
        this.$router.push({
          path: '/shop/goodsClassDetail',
          query: {
            id: item.goodsId
          }
        })
      }
    }
  }
}
</script>

<style scoped lang="less">
.search-wrap{
  background-color: #fff;
}
.del_goods {
  font-size: 12px;
}
.actives{
  color:#FF6600;
  font-weight: 600;
}
//.title_guoxin{
//  margin-top: 15px;
//}
.logo{
  display: inline-block;
  height: 30px;
  img{
    width: 100%;
  }
}
</style>
