<template>
  <view class="page__view">
		<navbar title="商品详情页" leftClick @leftClick="$utils.navigateBack" color="#191919" bgColor="#FFFFFF" />

    <view class="main">
      <uv-swiper :list="bannerList" indicator indicatorMode="dot" height="680rpx" keyName="image"></uv-swiper>

      <view class="summary">
        <view class="card info">
          <view class="name">{{ detail.content || detail.name }}</view>
          <!-- todo: check key -->
          <view class="flex tags" v-if="detail.tags">
            <view class="tag" v-for="(tag, tIdx) in detail.tags" :key="tIdx">
              {{ tag }}
            </view>
          </view>
          <view class="flex price">
            <view class="flex price-val">¥<text class="highlight">{{ (detail.currentPrice || 0) }}</text><text v-if="detail.unit">/{{ detail.unit }}</text></view>
            <view class="price-bef" v-if="detail.originalPrice">¥<text>{{ detail.originalPrice }}</text><text v-if="detail.unit">/{{ detail.unit }}</text></view>
          </view>
        </view>
        <view class="card bar">
          <view class="flex row">
            <view class="flex row-content">
              <view class="label">品类：</view>
              <!-- todo: check key -->
              <view class="value">{{ typeDesc }}</view>
            </view>
          </view>
          <template v-if="detail.specs && detail.specs.length">
            <view class="flex row" @click="openPicker">
              <view class="flex row-content">
                <view class="label">规格：</view>
                  <view class="value">{{ detail.specName || '请选择规格' }}</view>
              </view>
              <uv-icon name="arrow-right" color="#C6C6C6" size="24rpx"></uv-icon>
            </view>
          </template>
          <template v-else>
            <view class="flex row">
              <view class="flex row-content">
                <view class="label">规格：</view>
                <view class="value">{{ detail.specName || '--' }}</view>
              </view>
            </view>
          </template>
          <view class="flex row">
            <view class="flex row-content">
              <view class="label">服务：</view>
              <view class="value">{{ detail.service }}</view>
            </view>
          </view>
        </view>
      </view>
      
      <view class="detail" v-if="detail.detail">
  			<uv-parse :content="detail.detail"></uv-parse>
      </view>

      <view class="comment">
        <view class="header">
          <view class="highlight">用户评价</view>
          <view>User reviews</view>
        </view>
        <view class="comment-item" v-for="item in commentList" :key="item.id">
          <commentCard :data="item"></commentCard>
        </view>
      </view>
    </view>

		<view class="flex bottom">
      <button class="flex flex-column btn btn-simple" @click="jumpToComment">
        <image class="icon" src="@/pages_order/static/product/comment.png" mode="widthFix"></image>
        <view>评价</view>
      </button>
      <button class="flex btn btn-palin" @click="onAddCart">加入购物车</button>
      <button class="flex btn btn-primary" @click="onBuy">立即购买</button>
    </view>

    <specOptionsPopup ref="specOptionsPopup" :value="detail.specId" :data="detail" :confirmText="next ? '下一步' : '确认'" @confirm="onSpecChange"></specOptionsPopup>

    <agreementPopup ref="agreementPopup" @confirm="jumpToCreateOrder"></agreementPopup>

  </view>
</template>

<script>
	import mixinsList from '@/mixins/list.js'

  import commentCard from '@/pages_order/comment/commentCard.vue'
  import specOptionsPopup from '@/pages_order/product/specOptionsPopup.vue'
  import agreementPopup from './agreementPopup.vue'
  
  // 产品类型（0营养剂，1预约，2课程）
  const TYPE_AND_DESC_MAPPING = {
    0: '营养剂',
    1: '检测',
    2: '课程',
  }

  export default {
		mixins: [mixinsList],
    components: {
      commentCard,
      specOptionsPopup,
      agreementPopup,
    },
    data() {
      return {
        id: null,
        detail: {},
        next: 'createOrder', // createOrder | addCart
				mixinsListApi: 'productEvaluate',
        mixinsListKey: 'commentList',
        commentList: [],
      }
    },
    computed: {
			bannerList() {
				const { image } = this.detail

				if (!image) {
					return []
				}

				return Array.isArray(image) ? image : image.split(',')
			},
      typeDesc() {
				const { type } = this.detail

        return  TYPE_AND_DESC_MAPPING[type]
      },
    },
    onLoad(arg) {
      console.log('onLoad', arg)

      const { id } = arg

      this.id = id

      this.fetchDetail(id)
      
      this.queryParams.productId = id
      this.getData(id)
    },
    methods: {
      async fetchDetail(id) {
        try {
          const result = await this.$fetch('getProductDetail', { id })

          const { specs } = result
          let arr = specs
          arr?.sort?.((a, b) => a.sortOrder - b.sortOrder)
          const spec = arr?.[0]
          
          this.detail = {
            ...result,
            specId: spec?.id || null,
            specName: spec?.specName || null,
          }
        } catch (err) {

        }
      },
			openPicker() {
        this.next = null
        this.$refs.specOptionsPopup.open()
			},
      onAddCart(id) {
        const { specId, specs } = this.detail

        if (!specId && specs?.length) {
          this.next = 'addCart'
          this.$refs.specOptionsPopup.open()
          return
        }

				this.$store.dispatch('addCart', this.detail)
      },
      onBuy() {

        const { specId, specs, isCrossBorder } = this.detail

        console.log('specId', specId, 'specs', specs, !specId && specs?.length)

        if (!specId && specs?.length) {
          this.next = 'createOrder'
          this.$refs.specOptionsPopup.open()
          return
        }

        if (isCrossBorder == 'Y') {
          this.$refs.agreementPopup.open()
          return
        }

				this.$store.commit('createOrder', [this.detail])
      },
      onSpecChange(obj) {
        console.log('onSpecChange', obj)
        this.detail.specId = obj.id
        this.detail.specName = obj.specName
        this.detail.currentPrice = obj.price

        console.log('detail', this.detail)

        switch(this.next) {
          case 'createOrder': 
            this.onBuy()
            break;
          case 'addCart': 
            this.onAddCart()
            break;
          default:
            break;
        }
      },
      jumpToComment() {
        this.$utils.navigateTo(`/pages_order/comment/commentRecordsOfProduct?productId=${this.id}`)
      },
      jumpToCreateOrder() {
				this.$store.commit('createOrder', [this.detail])
      },
    },
  }
</script>

<style scoped lang="scss">
  .page__view {
    width: 100vw;
    min-height: 100vh;
    background-color: $uni-bg-color;
    position: relative;
  
    /deep/ .nav-bar__view {
      position: fixed;
      top: 0;
      left: 0;
    }
    
  }

  .main {
    width: 100vw;
    padding: calc(var(--status-bar-height) + 120rpx) 0 198rpx 0;
    box-sizing: border-box;
	}

  .summary {
    width: 100%;
    padding: 40rpx 32rpx;
    box-sizing: border-box;
  }

  .card {
    border-radius: 24rpx;

    & + & {
      margin-top: 40rpx;
    }

    &.info {
      width: 100%;
      padding: 32rpx;
      box-sizing: border-box;
      background: #FFFFFF;

      .name {
        font-family: PingFang SC;
        font-weight: 400;
        font-size: 32rpx;
        line-height: 1.4;
        color: #181818;
      }

      .tags {
        margin-top: 16rpx;
        justify-content: flex-start;
        flex-wrap: wrap;
        gap: 16rpx;

        .tag {
          padding: 2rpx 14rpx;
          font-family: PingFang SC;
          font-weight: 400;
          font-size: 24rpx;
          line-height: 1.4;
          color: #7451DE;
          background: #EFEAFF;
          border: 2rpx solid #7451DE;
          border-radius: 8rpx;
        }
      }

      .price {
        margin-top: 32rpx;
        justify-content: flex-start;
        column-gap: 20rpx;

        &-val {
          font-family: PingFang SC;
          font-weight: 500;
          font-size: 24rpx;
          line-height: 1.4;
          color: #7451DE;

          .highlight {
            margin: 0 8rpx;
            font-size: 48rpx;
          }
        }

        &-bef {
          font-family: PingFang SC;
          text-decoration: line-through;
          font-weight: 400;
          font-size: 28rpx;
          line-height: 1;
          color: #8B8B8B;
        }
      }
    }

    &.bar {
      width: 100%;
      padding: 20rpx 32rpx;
      box-sizing: border-box;
      background: #FAFAFF;
      box-shadow: -4rpx -4rpx 20rpx 0 #FFFFFFC4,
                  4rpx 4rpx 20rpx 0 #AAAACC1F,
                  2rpx 2rpx 4rpx 0 #AAAACC40,
                  -2rpx -2rpx 4rpx 0 #FFFFFF;

      .row {
        padding: 8rpx 0;

        &-content {
          flex: 1;
          justify-content: flex-start;
          column-gap: 4rpx;
          font-family: PingFang SC;
          font-weight: 400;
          font-size: 28rpx;
          line-height: 1.4;

          .label {
            color: #8B8B8B;
          }

          .value {
            color: #393939;
          }
        }
      }

      .row + .row {
        margin-top: 24rpx;
      }
    }
  }

  .comment {
    padding: 40rpx 32rpx;

    .header {
      margin-bottom: 24rpx;
      font-family: PingFang SC;
      font-weight: 400;
      font-size: 26rpx;
      line-height: 1.4;
      color: #252545;

      .highlight {
        font-weight: 600;
        font-size: 48rpx;
      }

    }

    &-item {
      & + & {
        margin-top: 32rpx;
      }
    }
  }

	.bottom {
		position: fixed;
		left: 0;
		bottom: 0;

    align-items: flex-start;
    column-gap: 32rpx;

		width: 100vw;
		// height: 198rpx;
		padding: 24rpx 40rpx 0 40rpx;
		padding-bottom: calc(env(safe-area-inset-bottom) + 24rpx);
		background: #FFFFFF;
		box-sizing: border-box;

    .btn {
      font-family: PingFang SC;

      &-simple {
        font-weight: 400;
        font-size: 22rpx;
        line-height: 1.1;
        color: #999999;

        .icon {
          width: 52rpx;
          height: auto;
        }
      }

      &-palin {
        flex: 1;
        padding: 14rpx 0;
        font-weight: 500;
        font-size: 36rpx;
        line-height: 1.4;
        color: #252545;
        border: 2rpx solid #252545;
        border-radius: 41rpx;
      }

      &-primary {
        flex: 1;
        padding: 16rpx 0;
        font-weight: 500;
        font-size: 36rpx;
        line-height: 1.4;
        color: #FFFFFF;
        background-image: linear-gradient(to right, #4B348F, #845CFA);
        border-radius: 41rpx;
      }
    }
	}

</style>