<template>
  <div class="con-box uc-collection">
    <!-- 头部标题-->
    <div class="footprint-head">
      <div class="head-tit">{{$t('history.history')}}</div>

      <!-- 是否批量管理 -->
      <div v-if="!isBatchEdit" class="batch-btn" @click="openBatchEdit()">{{$t('collection.batchManagement')}}</div>
      <div v-if="isBatchEdit" class="action-btn-box">
        <span class="batch-box">
          <span class="check" @click="selectAllItem()">
            <input
              type="checkbox"
              class="checkbox default"
              :checked="isSelectedAll"
              :class="{ checked: isSelectedAll, default: !isSelectedAll }"
            >
            <span class="text">{{$t('collection.selectAll')}}</span>
          </span>
          <span class="delete-collection" @click="showPopup()">
            <i class="icon" />
            <span class="text">{{$t('cart.deleteSelectedProducts')}}</span>
          </span>
          <span class="cancel-btn" @click="cancelBatchEdit">{{$t('cancel')}}</span>
        </span>
      </div>
    </div>
    <!-- 头部标题 end-->

    <!-- 收藏列表 -->
    <div
      v-for="(item, index) in browseLogData"
      :key="index"
      class="history-item"
    >
      <div class="time">{{ item.time.substr(0,10) }}</div>
      <div class="goods-list">
        <div class="list-con">
          <div
            v-for="(prodItem, prodIndex) in item.spuList"
            :key="prodIndex"
            :class="[
              'item',
              isBatchEdit ? 'batch-edit' : '',
              prodItem.isCheck ? 'checked' : ''
            ]"
            @click="selectProdItem(prodItem.prodBrowseLogId)"
          >
            <div class="goods-img" @click="toProdDetailPage(prodItem.prodId)">
              <img v-if="prodItem.pic" :src="config.picDomain + prodItem.pic" alt="" @error="handlePicError">
              <img v-else src="~/assets/img/def.png" alt />
              <!-- <img v-if="!prodItem.mainImgUrl" src="~/assets/images/def.png"> -->
            </div>
            <div class="goods-msg" @click="toProdDetailPage(prodItem)">
              <div class="goods-name">{{ prodItem.prodName }}</div>
              <!-- <div v-if="prodItem.spuType === 3" class="goods-price">
                <div class="price">{{ prodItem.scoreFee }}积分
                  <span v-if="prodItem.priceFee">+ {{ '￥' + util.parsePrice(prodItem.priceFee)[0] + '.' + util.parsePrice(prodItem.priceFee)[1] }}</span>
                </div>
              </div> -->
              <div class="goods-price">
                <div class="price">{{ '￥' + prodItem.price }}</div>
              </div>
            </div>
            <div class="goods-action">
              <div class="action-a a1" @click="toProdDetailPage(prodItem.prodId)"><i class="icon" />{{$t('collection.goToBuy')}}</div>
              <div class="action-a a2" @click="showPopup(prodItem.prodBrowseLogId, prodItem.prodId)"><i class="icon" />{{$t('history.deleteHistory')}}</div>
            </div>
            <div class="item-mask">
              <i class="icon" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- /收藏列表 -->

    <!-- 页码 -->
    <pagination
      v-if="pages > 1"
      v-model="pageNum"
      :pages="pages"
      @changePage="getBrowseProdList"
    />

    <!-- 空列表提示 -->
    <div v-if="!browseLogList.length" class="empty">
      <div class="img">
        <img src="~/assets/images/emptyPic/not-found.png" alt>
      </div>
      <div class="action">
        <div class="text">{{$t('history.historyEmpty')}}</div>
        <nuxt-link to="/" class="btn">{{ $t('lookAtOther') }}</nuxt-link>
      </div>
    </div>
    <!-- /空列表提示 -->

    <!-- 提示弹窗 -->
    <div v-if="isPopupVisible" class="popup-mask" />
    <div v-if="isPopupVisible" class="popup-box">
      <div class="tit">
        <div class="text">{{$t('tips')}}</div>
        <div class="close" @click="closePopup()" />
      </div>
      <div class="con">
        <div class="tip">
          <div class="tip-icon warning" />
          <div class="tip-info">
            <div class="result">
              {{$t('userCenter.deleteTheSelected')}}
            </div>
            <div class="date">
              {{$t('userCenter.deleteTheSelected')}}
            </div>
            <div class="btns">
              <a
                href="JavaScript:;"
                class="btn-r"
                @click="deleteBrowseLog()"
              >{{$t('userCenter.confirm')}}</a>
              <a
                href="JavaScript:;"
                class="btn-g"
                @click="closePopup()"
              >{{$t('userCenter.close')}}</a>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- /提示弹窗 -->
  </div>
</template>

<script>
import util from '~/plugins/util'
import config from '~/plugins/config'
import Pagination from '~/components/pagination'
export default {
  components: {
    Pagination
  },
  data() {
    return {
      pageNum: 1,
      browseLogList: [],
      pages: 0,
      total: 0,
      browseLogData: [], // 按时间分割后的商品游览记录列表
      isBatchEdit: false, // 是否批量修改
      isSelectedAll: false, // 是否选中全部
      isPopupVisible: false, // 弹窗是否显示
      selectedBrowseLogId: '', // 选中的商品游览记录id
      selectedBrowseLogIds: '', // 选中的商品游览记录id列表
      deleteLogType: '', // 删除类型 0:单个 1:批量
      // 在template内使用外部js的对象或者方法，需在export default内声明该对象或者方法
      util,
      config
    }
  },
  mounted() {
    document.title = this.$i18n.t('history.history')
    this.getBrowseProdList()
  },
  methods: {
    /**
     * 加载默认图片
     */
    handlePicError(e){
       e.target.src=require('@/assets/img/def.png')
    },
    // 获取足迹商品列表
    getBrowseProdList() {
      this.$axios.get('/p/prodBrowseLog/page', {
        params: {
          current: this.pageNum,
          size: 8
        }
      }).then(({ data }) => {
        this.isSelectedAll = false
        data.records.forEach((item) => {
          item.isCheck = false
        })
        const list = this.browseLogList = data.records
        this.pages = data.pages
        this.total = data.total
        // 游览记录列表转换
        if (list.length) {
          this.convertBrowseLogList(list)
        } else {
          this.browseLogData = []
        }
      })
    },

    /**
     * 商品游览记录按时间来划分商品列表
     * 格式:[{time:time1,spuList:[]}, {time:time2,spuList:[]}]
     * @param {Array} list 商品列表
     */
    convertBrowseLogList(list) {
      let currentTime = list[0].browseTime
      let tempSpuList = []
      const browseLogData = []
      for (let i = 0; i < list.length; i++) {
        if (currentTime === list[i].browseTime) {
          tempSpuList.push(list[i])
          if ((i + 1) === list.length) {
            const browseLogItem = {
              time: list[i].browseTime,
              spuList: tempSpuList
            }
            browseLogData.push(browseLogItem)
          }
        } else {
          currentTime = list[i].browseTime
          const browseLogItem = {
            time: list[i - 1].browseTime,
            spuList: tempSpuList
          }
          browseLogData.push(browseLogItem)
          tempSpuList = []
          tempSpuList.push(list[i])
          if ((i + 1) === list.length) {
            const browseLogItem = {
              time: list[i].browseTime,
              spuList: tempSpuList
            }
            browseLogData.push(browseLogItem)
          }
        }
      }
      this.browseLogData = browseLogData
    },

    // 打开批量编辑
    openBatchEdit() {
      this.isBatchEdit = !this.isBatchEdit
    },

    // 取消批量编辑
    cancelBatchEdit() {
      this.isBatchEdit = false
      this.isSelectedAll = false
      this.browseLogList.forEach((item) => {
        item.isCheck = false
      })
    },

    /**
     * 打开批量编辑，选择商品项
     * @param {Number} prodBrowseLogId 游览id
     */
    selectProdItem(prodBrowseLogId) {
      if (!this.isBatchEdit) {
        return
      }
      for (let i = 0; i < this.browseLogList.length; i++) {
        if (this.browseLogList[i].prodBrowseLogId === prodBrowseLogId) {
          this.browseLogList[i].isCheck = !this.browseLogList[i].isCheck
          break
        }
      }
      this.checkSelectedStatus()
    },

    // 选中全部选项
    selectAllItem() {
      this.isSelectedAll = !this.isSelectedAll
      this.browseLogList.forEach((item) => {
        item.isCheck = this.isSelectedAll
      })
    },

    // 检查是否全部选中
    checkSelectedStatus() {
      const prodList = this.browseLogList
      let isSelectedAll = true
      for (let i = 0; i < prodList.length; i++) {
        if (prodList[i].isCheck === false) {
          isSelectedAll = false
          break
        }
      }
      this.isSelectedAll = isSelectedAll
    },

    /**
     * 弹出提示弹窗
     * @param {number} id 商品浏览记录id
     */
    showPopup(id) {
      if (id) {
        this.selectedBrowseLogId = id
        this.deleteLogType = 0 // 单个删除
        this.isPopupVisible = true
      } else {
        this.deleteLogType = 1 // 批量删除
        // 获取到批量提交的数据
        const ids = []
        this.browseLogList.forEach((item) => {
          if (item.isCheck) {
            ids.push(item.prodBrowseLogId)
          }
        })
        this.selectedBrowseLogIds = ids
        if (ids.length > 0) {
          this.isPopupVisible = true
        } else {
          this.cancelBatchEdit() // 取消批量管理
        }
      }
    },

    // 隐藏提示弹窗
    closePopup() {
      this.isPopupVisible = false
    },

    // 删除商品游览记录
    deleteBrowseLog() {
      let params = null
      let spuBrowseLogIds = []
      if (this.deleteLogType === 0) {
        // 单个删除也用数组来传递传参
        spuBrowseLogIds.push(this.selectedBrowseLogId)
      } else {
        // 批量删除
        spuBrowseLogIds = this.selectedBrowseLogIds
      }
      params = spuBrowseLogIds
      this.deleteTheProdRecord(params)
      this.isPopupVisible = false
    },

    // 删除足迹
    deleteTheProdRecord(params) {
      console.log(params)
      this.$axios.delete('/p/prodBrowseLog', {
        data: params
      }).then(() => {
        this.pageNum = 1
        this.getBrowseProdList()
        this.cancelBatchEdit()
      })
    },

    // 跳转到商品详情页
    toProdDetailPage(prodId) {
      const url = '/detail/'
      console.log(url)
      this.$router.push({ path: url + prodId })
    }
  }
}
</script>

<style src='~/assets/css/user-center.css'></style>
<style src='~/assets/css/uc-footprint.css'></style>
