<template>
  <div class="productDetail">
    <cr-swipe class="my-swipe" indicator-color="white" @change="onChange">
      <template v-for="(item, index) in info.imageUrl">
        <cr-swipe-item :key="index">
          <cr-image width="100%" height="9.333333rem" :src="item" />
        </cr-swipe-item>
      </template>
      <template #indicator>
        <div class="custom-indicator">
          {{ current + 1 }}/{{ info.imageUrl && info.imageUrl.length }}
        </div>
      </template>
    </cr-swipe>
    <div class="price" :class="{ spike: info.hasStart }">
      <div class="price__num">
        <cr-image
          src="https://activitystatic.lkbang.net/mall-free-ui/img/sprike-price-bg.png"
          height="100%"
          width="100%"
          class="price__num-bg"
        />
        <cr-tag color="#fff" text-color="#ec1500" class="price__num-tag">秒杀</cr-tag>
        <div class="price__num-present">
          <span>¥</span>{{ info.hasStart ? info.activityPrice : info.presentPrice || '-' }}
        </div>
        <div v-if="info.hasStart" class="price__num-original">
          <span>¥</span>{{ info.presentPrice || '-' }}
        </div>
      </div>
      <div class="price__desc">
        <!-- <div class="price__desc-count" v-if="false">销量：{{ info.showSaleCount }}</div> -->
        <div class="price__desc-countdown">
          <h5>活动剩余时间：</h5>
          <cr-count-down
            v-if="info.remainTime"
            :time="info.remainTime"
            @finish="handleActivityOver"
          >
            <template #default="t">
              <template v-if="info.isDay">
                <span class="block">
                  {{ (t.d > 9 ? '' : '0') + t.d }}
                </span>
                <span class="colon">天</span>
              </template>
              <span class="block">
                {{ (t.h > 9 ? '' : '0') + t.h }}
              </span>
              <span class="colon">时</span>
              <span class="block">{{ (t.m > 9 ? '' : '0') + t.m }}</span>
              <span class="colon">分</span>
              <template v-if="!info.isDay">
                <span class="block">{{ (t.s > 9 ? '' : '0') + t.s }}</span>
                <span class="colon">秒</span>
              </template>
            </template>
          </cr-count-down>
        </div>
      </div>
    </div>
    <p class="title-wrap">
      <span class="title">
        <img v-if="info.goodsTypeImage" class="title_tag" :src="info.goodsTypeImage" />
        {{ info.goodsName }}
      </span>
    </p>

    <cr-cell-group class="info">
      <!-- <cr-cell title="已选" value="A套餐；1件" /> -->
      <cr-cell title="送至" @click="openAddress">
        <div class="addr-show">
          <svg-icon icon-class="location" class="address" />
          <span>{{ address || '请选择' }}</span>
          <cr-icon type="arrow" class="arrow" />
        </div>
      </cr-cell>
      <!-- <cr-cell title="运费" value="免运费" /> -->
      <cr-cell v-if="info.labelInfoList && info.labelInfoList.length > 0" title="服务">
        <template>
          <span v-for="(item, index) in info.labelInfoList" :key="index" class="service">
            {{ item.labelName }}
          </span>
        </template>
      </cr-cell>
    </cr-cell-group>
    <div v-if="info.imageUrl && info.imageUrl.length > 0">
      <cr-divider class="divider">
        宝贝详情
      </cr-divider>
      <div v-if="info.atts" class="info-detail">
        <cr-cell-group
          v-for="(item, index) in info.atts"
          :key="index"
          :title="item.groupName"
          class="info"
        >
          <cr-cell
            v-for="(it, idx) in item.groupAtts"
            :key="'it_' + idx"
            :title="it.attsName"
            :value="it.attsValue"
          />
        </cr-cell-group>
      </div>
      <!-- <cr-image
        width="100%"
        height="auto"
        :src="item"
        v-for="(item, index) in info.imageUrl"
        :key="index"
      /> -->
      <div class="info-detail-img" v-html="info.imgs" />
    </div>
    <div class="wrap-reco">
      <RecoGoods v-if="showReco" desc="猜你喜欢" :goods-id="info.skuNo" />
    </div>
    <cr-goods-action
      class="activity-good-action"
      :options="goodActCfg.options"
      :button-group="goodActCfg.btnGroup"
      :round="true"
      @click="e => handleGoodActClick('left', e)"
      @button-click="e => handleGoodActClick('right', e)"
    />

    <address-list-popup
      v-if="loadAddr"
      ref="addrList"
      v-model="showAddressPopup"
      btn-txt="确定"
      name="showAddressPopup"
      @submit="handleSelectAddress"
      @loaded="findUserAddrById"
    />
    <gift-popup
      v-model="showOverTip"
      closeable
      txt="<p>感谢您的关注</p><p>本次活动已经结束</p>"
      btn-txt="查看其他活动～"
      img-url="https://activitystatic.lkbang.net/mall-free-ui/img/gift-gray.png"
      @close="handleOverTip"
    />
    <cr-count-down
      v-if="info.willTime && info.willTime > -30"
      format=""
      :time="info.willTime"
      @finish="handleActivityStart"
    />
    <div class="demo-block">
      <cr-dialog
        v-model="showDialog"
        confirm-button-color="#ff1900"
        :show-cancel-button="false"
        @onConfirm="handleBuy"
      >
        <div>该商品每人以活动价仅限购买{{ activitySkuTotalCount }}件哦～</div>
      </cr-dialog>
    </div>
  </div>
</template>
<script>
import RecoGoods from '@/components/RecoGoods/RecoGoods.vue';
import GiftPopup from './components/GiftPopup';
import Cookies from '@/service/cookieStorage.service';
import AddressListPopup from '@/components/AddressListPopup';
import { spike } from '@/api/activity';
// import { shopCart, common } from '@/api/common';
import { goodAdd, getCartCount } from '@/api/shopCart.api';
import goods from '@/api/goods.api';
import { isXYQB } from '@/service/validation.service';
import { handleRemainTime, handleDateFormat } from './components/utils';
import localStorage from '@/service/localStorage.service';
import config from '@/config';
import { isApp } from '@/service/validation.service';
export default {
  name: 'Detail',
  components: {
    RecoGoods,
    AddressListPopup,
    GiftPopup
  },
  data() {
    return {
      showDialog: false,
      showOverTip: false,
      loadAddr: false,
      current: 0,
      typeList: ['正品保证', '极速发货', '服务保证', '30天质保', '七天无理由退款'],
      showAddressPopup: false,
      goodsId: '',
      info: {},
      address: '',
      selectId: '',
      queryInfo: {},
      showReco: false,
      activitySkuTotalCount: 0,
      canBuyCount: 0,
      goodActCfg: {
        options: [
          {
            icon: 'https://activitystatic.lkbang.net/mall-free-ui/img/icon/home.png',
            text: '首页'
          },
          {
            icon: 'https://activitystatic.lkbang.net/mall-free-ui/img/icon/shopcart.png',
            text: '购物车',
            info: 0
          }
        ],
        btnGroup: [
          {
            text: '加入购物车',
            type: 'danger'
          },
          {
            text: '立即购买',
            type: 'danger'
          }
        ]
      }
    };
  },
  mounted() {
    isXYQB &&
      this.nativeBridge.run({
        event: 'resetNavigationBarColor',
        data: {
          isDarkContent: false,
          colors: ['ffffff', 'ffffff']
        }
      });
    this.queryInfo = this.$route.query;
    this.getDetail();
    this.loadAddr = !!Cookies.get('vccToken');
    this.loadAddr && this.getCartCount();
  },
  methods: {
    onChange(index) {
      this.current = index;
    },
    openAddress() {
      if (!Cookies.get('vccToken')) {
        this.getToken();
        return;
      }
      this.showAddressPopup = true;
    },
    handleOverTip(e) {
      this.showOverTip = false;
      if (e === 2) {
        if (isXYQB) {
          this.$router.go(-1);
        } else {
          this.navToDlApp();
        }
      }
    },
    handleSelectAddress(info) {
      this.selectId = info.addrReceiverId;
      this.address = info.addrFullName;
    },
    getToken() {
      const that = this;
      window.xyqbNativeEvent = function(res) {
        const json = typeof res === 'string' ? JSON.parse(res) : res;
        if (json.event === 'getTokenSuccess') {
          const appData = json.data || {};
          if (appData && appData.token) {
            Cookies.set('vccToken', appData.token);
            that.loadAddr = true;
            this.getCartCount();
            this.getDetail();
          }
        }
      };
      this.nativeBridge.getToken();
    },
    handleGoodActClick(pos, e) {
      if (pos === 'left') {
        if (e.index === 0) {
          this.$router.push({ name: 'Home' });
        } else {
          if (isApp) {
            this.nativeBridge.openNewUrl({
              event: 'openNewUrl',
              data: {
                newUrl: 'xyqb://shoppingCart'
              }
            });
          } else {
            this.$router.push({ name: 'Cart' });
          }
        }
      } else if (pos === 'right') {
        if (!Cookies.get('vccToken')) {
          this.getToken();
          return;
        }
        if (this.info.hasStop) {
          this.showOverTip = true;
          return;
        }
        if (e.index === 0) {
          this.addCart();
        } else {
          this.handleIsActivity();
        }
      }
    },
    handleActivityOver() {
      if (this.info.remainTime > -30) {
        this.showOverTip = true;
        this.getDetail();
      }
    },
    handleActivityStart() {
      this.getDetail();
    },
    findUserAddrById(addrReceiverList) {
      const selectAddr = addrReceiverList.find(item => item.addrDefault == 1);
      if (selectAddr) {
        this.address = selectAddr.addrFullName;
        this.selectId = selectAddr.addrReceiverId;
      }
    },
    navToDlApp() {
      const nextPage = document.createElement('a');
      nextPage.setAttribute('href', config.appDownUrl);
      nextPage.click();
    },
    async getDetail() {
      let [res] = await spike.detail(this.queryInfo);
      const { endTime, startTime, limitCount, canBuyCount } = res;
      this.activitySkuTotalCount = limitCount;
      this.canBuyCount = canBuyCount;
      res.remainTime = handleRemainTime('', endTime)[0];
      res.willTime = handleRemainTime('', startTime)[0];
      res.hasStart = handleRemainTime(startTime, '')[0] > 0;
      res.hasStop = res.remainTime < 1;
      res = { ...res, ...handleDateFormat(startTime, endTime) };
      if (res.hasStop) {
        this.showOverTip = true;
      }
      this.info = res || {};
      const imgs = await goods.getDetailPic(this.info.contentDetailUrl);
      this.info.imgs = imgs;
      this.showReco = true;
    },
    handleOriginalPrice() {
      this.showDialog = true;
    },
    handleIsActivity() {
      if (!this.canBuyCount && this.info.hasStart) {
        this.handleOriginalPrice();
        return;
      }
      const channelId = this.$route.query.channelShareId || '';
      if (channelId) {
        this.$track.registeredEvents('H5_SeckillActivityPageBuyNowBtnClick', {
          Private_domain_channel_id: channelId
        });
      }
      this.handleBuy();
    },
    async handleBuy() {
      const { hasStop, skuNo, skuSource } = this.info;
      const { activityId, templateDetailId, templateId } = this.$route.query || {};
      if (hasStop) {
        this.showOverTip = true;
        return;
      }
      const order = {
        addrReceiverId: String(this.selectId) || '',
        selectedSkuList: [
          {
            skuNum: 1,
            skuNo: +skuNo,
            skuSource
          }
        ]
      };
      localStorage.set('orderData', order);
      this.$router.push({
        name: 'createOrder',
        query: { activityId, templateDetailId, templateId }
      });
    },
    async getCartCount() {
      if (!Cookies.get('vccToken')) return;
      const [res] = await getCartCount();
      this.$set(this.goodActCfg.options[1], 'info', res.count);
    },
    async addCart() {
      const { skuNo, skuSource } = this.info;
      const [data] = await goodAdd({
        shopCartBaseList: [
          {
            skuId: skuNo,
            skuNum: 1,
            skuSource,
            type: 1
          }
        ],
        selected: true
      });
      if (isApp) {
        this.nativeBridge.run({
          event: 'shopCarAddGoodsNotification',
          data: {
            count: data.count
          }
        });
      }
      this.$toast('购物车添加成功！');
      this.getCartCount();
    }
  }
};
</script>
<style lang="less" src="./detail.less" scoped></style>
