<template>
  <div class="con-box home">
    <!-- 账户信息 -->
    <div class="my-info">
      <div class="info-box">
        <div class="portrait-box">
          <div class="portrait">
            <img :src="hadAvatar?userAvatar:defaultAvatar" alt />
          </div>
          <div class="edit" @click="uploadPic()">{{$t('userIndex.editProfile')}}</div>
        </div>
        <div class="name-box">
          <div class="name">
            <div class="text">{{ nickName }}</div>
            <div v-if="memberInfo.levelType === 1"  class="vip"><img src="@/assets/images/vip.png" alt=""></div>
          </div>
          <div class="level-box">
            <div class="text">{{$t('userIndex.level')}}：</div>
            <div
            >{{userLevel.levelName}}</div>
          </div>
          <div class="level-box">
            <div class="text">{{ $t('userIndex.balance') }}：</div>
            <div @click="toBalance()" class="to-balance">
              {{ currentBalance }}{{$t('myBalance.yuan')}}
            </div>
          </div>
          <div class="level-box">
            <div class="text">{{$t('userIndex.growthValue')}}：</div>
            <div
              class="number"
              v-if="memberInfo.nextGrowth"
            >{{memberInfo.growth}}<span class="text">/{{memberInfo.nextGrowth}}</span></div>
            <div class="number" v-if="!memberInfo.nextGrowth">{{memberInfo.growth}}</div>
          </div>
        </div>
      </div>
      <div class="order-tab">
        <div class="item" @click="toOrderList(1)">
          <div class="img unpaid"></div>
          <div class="text">
            {{$t('obligation')}}
            <span class="number">{{orderCountData.unPay}}</span>
          </div>
        </div>
        <div class="item" @click="toOrderList(2)">
          <div class="img no-shipped"></div>
          <div class="text">
            {{$t('pendingDelivery')}}
            <span class="number">{{orderCountData.payed}}</span>
          </div>
        </div>
        <div class="item" @click="toOrderList(3)">
          <div class="img shipped"></div>
          <div class="text">
            {{$t('shipped')}}
            <span class="number">{{orderCountData.consignment}}</span>
          </div>
        </div>
        <div class="item" @click="toOrderList(5)">
          <div class="img no-reviewed"></div>
          <div class="text">
            {{$t('completed')}}
            <span class="number">{{orderCountData.success}}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- /账户信息 -->
    <div :class="['buy-member',this.$store.state.locale == 'en'?'en':'']" @click="buyMember">
      <div class="text" :style="{marginLeft:this.$store.state.locale =='en'?'297px':''}">
        <div class="big">{{$t('userIndex.privileges')}}</div>
        <div
          class="small"
        >{{$t('userIndex.openMembership')}}￥{{memberPrice.needAmount}}/{{['',$t('dayRi'),$t('week'),$t('month'),$t('season'),$t('year')][memberPrice.termType]}}{{$t('userIndex.valueOffer')}}</div>
      </div>
      <div class="btn" :style="{marginLeft:this.$store.state.locale =='en'?'-12px':''}">{{$t('userIndex.openNow')}}</div>
    </div>
    <!-- 我的订单 -->
    <div class="order-list">
      <div class="order-head">
        <span class="text">{{$t('userIndex.myOrders')}}</span>
        <nuxt-link :to="{path:'/user-center/uc-order',params:{status:0}}" class="all">{{$t('userIndex.viewAllOrders')}}</nuxt-link>
      </div>
      <div class="order-table" v-if="orderList.length">
        <table cellspacing="0" cellpadding="0" class="box">
          <tbody>
            <tr class="box-tr" v-for="(order,index) in orderList" :key="index">
              <td v-if="order.orderItemDtos.length === 1">
                <div class="goods-info">
                  <nuxt-link
                    :to="(order.orderType==3?'member-center/integral-det/':'/detail/')+order.orderItemDtos[0].prodId"
                    class="img"
                  >
                    <img v-if="order.orderItemDtos[0].pic" :src="order.orderItemDtos[0].pic" :alt="order.orderItemDtos[0].prodName" @error="handlePicError" />
                    <img v-else src="~/assets/img/def.png" alt />
                  </nuxt-link>
                  <div class="name-sku">
                    <nuxt-link
                      :to="(order.orderType==3?'member-center/integral-det/':'/detail/')+order.orderItemDtos[0].prodId"
                      class="name"
                    >{{order.orderItemDtos[0].prodName}}</nuxt-link>
                    <span class="sku">{{order.orderItemDtos[0].skuName}}</span>
                  </div>
                </div>
              </td>
              <td v-else>
                <div :class="['goods-info multi-good-info', order.orderItemDtos.length < 8 ? 'hide-scrollbar': '']">
                  <span v-for="(orderItem, orderItemIndex) in order.orderItemDtos"
                    :key="orderItemIndex">
                      <nuxt-link
                        :to="(order.orderType==3?'member-center/integral-det/':'/detail/')+order.orderItemDtos[orderItemIndex].prodId"
                        class="img"
                    >
                      <img v-if="orderItem.pic" :src="orderItem.pic" :alt="orderItem.spuName">
                      <img v-else src="~/assets/img/def.png" alt />
                      <div class="nums-con">x{{ orderItem.prodCount }}</div>
                    </nuxt-link>
                  </span>
                </div>
              </td>
              <td class="br" width="117">
                <div class="goods-number">{{$t('total')}} {{order.totalCounts}} {{$t('items')}}</div>
              </td>
              <td class="br" width="117">
                <div class="amount">
                  <span
                    class="price"
                  >￥{{parsePrice(order.actualTotal)[0]}}.{{parsePrice(order.actualTotal)[1]}}</span>
                </div>
              </td>
              <td class="br" width="117">
                <div class="status">
                  <div
                    class="text no-finish"
                  >{{['',$t('obligation'),$t('pendingDelivery'),$t('pendingReceipt'),$t('pendinEvaluation'),$t('completed'),$t('canceled'),$t('grouping')][order.status]}}</div>
                </div>
              </td>
              <td width="117">
                <div class="action">
                  <a
                    href="javascript:void(0)"
                    @click="toOrderDetail(order.orderNumber)"
                    class="action-a"
                  >{{$t('userIndex.viewOrders')}}</a>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <!-- 空列表提示 -->
      <div class="order-table" v-if="!orderList.length">
        <table cellspacing="0" cellpadding="0" class="box">
          <tr class="box-tr">
            <div class="empty" v-if="!orderList.length">
              <div class="img">
                <img src="~/assets/images/emptyPic/order-empty.png" alt />
              </div>
              <div class="action">
                <div class="text">{{$t('userIndex.noRelatedOrders')}}</div>
                <nuxt-link to="/" class="btn">{{$t('userIndex.goShopping')}}</nuxt-link>
              </div>
            </div>
          </tr>
        </table>
      </div>
      <!-- /空列表提示 -->
    </div>
    <!-- /我的订单 -->
    <!-- 猜你喜欢 -->
    <!-- <div class="goods-list guess-like">
      <div class="guess-like-tit">
        <div class="text">猜你喜欢</div>
        <div class="swiper-controls">
          <i class="arrow limit">
            &lt;</i> <i class="arrow">>
          </i>
        </div>
      </div>
      <div class="list-con">
        <div class="item">
          <div class="goods-img"><img src="~/assets/img/goods-01.jpg"
                 alt=""></div>
          <div class="goods-msg">
            <div class="goods-name">自然共和国 芦荟舒缓保湿四件套</div>
            <div class="goods-price">
              <div class="price">￥<span class="big">159</span>.00</div>
              <div class="old-price">￥189.00</div>
            </div>
          </div>
        </div>
      </div>

    </div>-->
    <!-- /猜你喜欢 -->
  </div>
</template>

<script>
import Cookie from 'js-cookie'
export default {
  data () {
    return {
      orderCountData: {}, // 订单详情数据
      nickName: '',
      current: 1,
      size: 10,
      orderList: [],
      hadAvatar: false,
      userAvatar: '',
      defaultAvatar: require('~/assets/images/buyer-img.png'),
      memberInfo: {},  // 会员信息
      userLevel: {},  // 会员等级
      memberPrice: {},  //  付费会员价
      currentBalance: {}  //余额信息
    }
  },
  methods: {
    /**
     * 加载默认图片
     */
    handlePicError(e){
       e.target.src=require('@/assets/img/def.png')
    },

    //获取会员信息
    getUserLevel () {
      this.$axios.get('/p/score/scoreLevel/page?levelType=' + 0).then(({ data }) => {
        this.memberInfo = data
        this.userLevel = data.userLevel
      })
    },

    //获取付费会员价格
    getMemberPrice () {
      // this.$axios.get('/p/score/scoreLevel/page?levelType=' + 1).then(({ data }) => {
      //   this.memberPrice = parseInt(data.userLevels[0].needAmount / data.userLevels[0].term)
      // })
      this.$axios.get('/p/score/scoreLevel/minAmountLevel').then(({ data }) => {
        this.memberPrice = data
      })
    },

    //去购买会员
    buyMember () {
      this.$router.push({ path: '/member-center/buy-member' })
    },

    /**
     * 获取订单数量
     */
    getUserInfo () {
      this.$axios.get('/p/user/centerInfo').then(({ data }) => {
        this.orderCountData = data.orderCountData
      })
    },

    //获取余额信息
    getBalanceInfo () {
      this.$axios.get('/p/userBalance/getBalanceInfo').then(({ data }) => {
        this.currentBalance = data
      })
    },

    /**
     * 获取订单列表
     */
    getOrderList () {
      let params = {
        current: 1,
        size: 10,
        status: 0
      }
      this.$axios.get('/p/myOrder/myOrder', { params }).then(({ data }) => {
        data.records.forEach(el => {
          el.totalCounts = 0
          el.orderItemDtos.forEach(prodItem=> {
            el.totalCounts += prodItem.prodCount
          })
        })
        this.orderList = data.records
      })
    },
    /**
     * 跳转订单详情
     */
    toOrderDetail (orderNumber) {
      this.$router.push({ path: '/order-detail', query: { orderNumber: orderNumber } })
    },
    /**
     * 跳转订单列表
     */
    toOrderList (status) {
      this.$router.push({ path: '/user-center/uc-order', query: { status: status } })
    },
    /**
     * 跳转到账户信息
     */
    uploadPic () {
      this.$router.push({ path: '/user-center/uc-account', query: { status: status } })
    },

    //去我的余额
    toBalance (){
      this.$router.push({ path: '/user-center/uc-balance' })
    },
    /**
     * 价格处理
     */
    parsePrice: (value) => {
      var val = Number(value)
      if (!val) {
        val = 0;
      }
      // 截取小数点后两位，并以小数点为切割点将val转化为数组
      return val.toFixed(2).split(".");
    },
  },
  mounted () {
    // 修改用户信息后刷新页面
    if (location.href.indexOf("#reloaded") == -1 && this.$route.query.refresh) {
        location.href = location.href + "#reloaded";
        location.reload();
    }
    // 设置网页标题
    document.title = this.$i18n.t('userIndex.personalCenter')
    this.getUserLevel()
    this.getMemberPrice()
    this.getUserInfo()
    this.getOrderList()
    this.getBalanceInfo()
    this.nickName = this.$store.state.user.nickName
    this.userAvatar = this.$store.state.user.userAvatar

    this.hadAvatar = !!this.userAvatar
    console.log(this.userAvatar)
    console.log(this.hadAvatar)
  }
}
</script>

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