<template>
  <view>
    <loading-view v-if="isFirstLoading"></loading-view>
    <view class="h-400rpx relative">
      <cu-swiper indicator-pos="bottomRight" mode="number" height="400" border-radius="0" :list="activity_images"></cu-swiper>
      <!-- 暂时不要 -->
      <view class="absolute right-40rpx top-50rpx" v-if="false">
        <!-- #ifdef APP-PLUS -->
        <u-icon name="share" :size="60" @click="shareWchart"></u-icon>
        <!-- #endif -->
        <!-- #ifdef MP-WEIXIN -->
        <button hover-class="none" open-type="share" class="cu-btn">
          <u-icon name="share" :size="60" @click="shareWchart"></u-icon>
        </button>
        <!-- #endif -->
      </view>
    </view>
    <view class="bg-white p-20rpx">
      <view class="text-right text-28rpx text-hex-e60012" v-if="orderDetail.expire_at"
        >本次砍价结束时间：{{ orderDetail.expire_at.substring(0,16) }}</view
      >
      <view class="flex items-center" v-if="!orderDetail.is_owner && !!orderDetail">
        <u-avatar :size="88" :src="orderDetail.user_avatar"></u-avatar>
        <text class="text-28rpx ml-20rpx text-28rpx text-hex-3a3a3a">{{ orderDetail.user_nickname }} 邀请您帮TA砍一刀</text>
      </view>
      <view class="border border-hex-fcd7ba border-solid p-12px bg-hex-fff9f1 flex mt-20rpx">
        <view class="flex-none w-206rpx h-206rpx" >
          <u-image :border-radius="10" width="206rpx" height="206rpx" :src="goods.cover"></u-image>
        </view>
        <view class="ml-30rpx flex-1 w-0 flex flex-col">
          <view class="line-2 h-88rpx text-hex-3a3a3a">{{ goods.name }}</view>
          <view class="flex items-center flex-1 mt-10rpx">
            <view class="flex-1 flex flex-col justify-between h-full">
              <view class="text-hex-e60012 text-40rpx">￥{{ goods.sell_price }}</view>
              <view class="text-hex-3a3a3a text-28rpx"
                >最多砍 <text class="text-hex-e60012">{{ goodsDetail.max_bargain_price }}</text
                >元</view
              >
            </view>
            <view>
              <view v-if="isBegin" class="bg-hex-f9b076 text-white rounded-8rpx h-60rpx leading-60rpx px-20rpx" @click="$u.routeAuth('/pages/bargain/index',{id:goodsDetail.activity_id})"> 去购买 </view>
            </view>
          </view>
        </view>
      </view>
      <view class="mt-40rpx">
        <view
          class="w-470rpx mx-auto bg-hex-e60012 rounded-full h-70rpx text-white leading-70rpx text-center text-36rpx"
          @click="onInviteBargain"
          v-if="!isBegin"
        >
          邀请砍价
        </view>
        <block v-else>
          <view
            class="w-470rpx mx-auto bg-hex-e60012 rounded-full h-70rpx text-white leading-70rpx text-center text-36rpx"
            v-if="orderDetail.is_owner"
            @click="onBuy"
          >
            马上购买
          </view>
          <block v-else>
            <view
              v-if="isLogin"
              class="w-470rpx mx-auto bg-hex-e60012 rounded-full h-70rpx text-white leading-70rpx text-center text-36rpx"
              @click="onHelp"
            >
              帮朋友砍一刀
            </view>
            <block v-else>
              <!-- #ifdef MP-WEIXIN -->
              <button
                hover-class="none"
                open-type="getPhoneNumber"
                @getphonenumber="getPhoneNumber"
                class="w-470rpx mx-auto bg-hex-e60012 rounded-full h-70rpx text-white leading-70rpx text-center text-36rpx"
              >
                帮朋友砍一刀授权
              </button>
              <!-- #endif -->
              <!-- #ifndef MP-WEIXIN -->
              <view
                class="w-470rpx mx-auto bg-hex-e60012 rounded-full h-70rpx text-white leading-70rpx text-center text-36rpx"
                @click="$u.route('/pages/login/index')"
              >
                帮朋友砍一刀
              </view>
              <!-- #endif -->
            </block>
          </block>
        </block>
      </view>

      <view class="mt-20px w-full text-center" v-if="isBegin && orderDetail.is_owner">
        <!-- #ifdef APP-PLUS -->
        <view class="w-470rpx mx-auto bg-hex-e60012 rounded-full h-70rpx text-white leading-70rpx text-center text-36rpx" @click="shareWchart">分享好友</view>
        <!-- #endif -->
        <!-- #ifdef MP-WEIXIN -->
        <button hover-class="none" open-type="share" class="cu-btn w-470rpx mx-auto bg-hex-e60012 rounded-full h-70rpx text-white leading-70rpx text-center text-36rpx">
          分享好友
        </button>
        <!-- #endif -->
      </view>

      <block v-if="logs.length">
        <view class="text-center mt-50rpx">
          <view class="text-center text-hex-eb8d42 title">帮砍好友</view>
        </view>
        <view class="mt-20rpx">
          <view v-for="(item, index) in logs" :key="index" class="mt-20rpx">
            <view class="border border-hex-fcd7ba border-solid bg-hex-fff9f1 rounded-12rpx p-20rpx flex text-hex-ed9959">
              <u-avatar :size="88" :src="item.avatar"></u-avatar>
              <view class="flex-1 ml-20rpx h-full">
                <view class="h-42rpx">{{ item.nickname }}</view>
                <view>砍掉了{{ item.bargain_amount }}元</view>
              </view>
              <view>{{ item.created_at.substring(0,10) }}</view>
            </view>
          </view>
        </view>
      </block>

      <block v-if="!!qr_code && !orderDetail.is_owner && isBegin">
        <view class="text-center mt-60rpx">
          感谢助力，添加客服送您 <text class="text-hex-e60012">5元</text> 现金红包和 <text class="text-hex-e60012">10元</text> 消费抵扣券
        </view>

        <view class="w-270rpx h-270rpx mx-auto mt-30rpx shadowqr">
          <u-image width="100%" height="100%" :src="qr_code"></u-image>
        </view>

        <view class="text-center py-40rpx text-34rpx font-medium"> 截屏扫描二维码 </view>
      </block>
    </view>

    <cu-modal
      v-model="tipShow"
      :title="tipObj.title"
      confirmText="去逛逛"
      @confirm="
        $u.route({
          url: '/pages/index/index',
          type: 'switchTab',
        })
      "
      :content="tipObj.content"
    ></cu-modal>
  </view>
</template>
<script>
import { mapGetters, mapMutations } from 'vuex';
import { getWxCode } from '@/utils/login';
export default {
  data() {
    return {
      ads: [],
      tipShow: false,
      tipObj: {
        title: '已结束',
        content: '该活动已结束',
      },
      btnLoading: false,
      isFirstLoading: true,
      id: null,
      skuId: null,
      orderDetail: {},
      goodsDetail: {},
    };
  },
  computed: {
    ...mapGetters(['isLogin']),
    isBegin() {
      return !!this.orderDetail?.id;
    },
    goods() {
      return this.goodsDetail?.sku ?? {};
    },
    logs() {
      return this.orderDetail?.logs ?? [];
    },
    qr_code() {
      const data = this.ads?.customer_service_qr_code_banner ?? [];
      return data.length > 0 ? data[0]?.image : '';
    },
    activity_images() {
      return this.goodsDetail?.activity_images ?? [];
    },
    user() {
      return this.$store.getters.user ?? {};
    },
  },
  //微信分享
  onShareAppMessage(res) {
    let shareObj = {
      title: this.goodsDetail?.activity_share_title,
      path: `/pages/bargain/invite?skuId=${this.skuId}&id=${this.orderDetail.id}`,
      imageUrl: this.goodsDetail?.activity_share_image ?? '/static/images/share/logs.png',
    };
    return shareObj;
  },
  async onLoad({ id, skuId }) {
    this.skuId = skuId;
    this.id = id;
  },
 async onShow(){
    this.getAds();
    await this.init();
    this.getGoodsDetail();
  },
  methods: {
    ...mapMutations({
      LOGIN: 'user/LOGIN',
    }),
    async init() {
      if (this.id) {
        await this.getDetailByOrder();
      } else {
        await this.getDetailOrderBySku();
      }
    },
    shareWchart() {
      /* #ifdef APP-PLUS */
      let code = this.user.code ? this.user.code : '';
      uni.share({
        provider: 'weixin',
        scene: 'WXSceneSession',
        type: 5,
        title: this.goodsDetail?.activity_share_title,
        miniProgram: {
          id: 'gh_261a68e68e45',
          path: `/pages/bargain/invite?skuId=${this.skuId}&id=${this.orderDetail.id}`,
          type: 0,
          webUrl: `https://wap.zichunsheng.cn/register?code=${code}`,
        },
        summary: '邀请你砍一刀！！',
        imageUrl: this.goodsDetail?.activity_share_image ?? '/static/images/share/logs.png',
        success: (res) => {
          console.log(res);
        },
        fail: (err) => {
          console.log(err);
        },
      });
      /* #endif */
    },
    //去购买
    onBuy() {
      const params = {
        goods: [
          {
            sku_id: this.skuId,
            num: 1,
          },
        ],
        type: 'bargains',
        cuId: this.orderDetail.id,
      };
      this.$u.routeAuth('/pages/confirm_order/confirm_order?data=' + encodeURIComponent(JSON.stringify(params)));
    },
    async getAds() {
      const resData = await this.$api.get('/v1/ads', {
        params: {
          keys: ['customer_service_qr_code_banner'],
        },
      });
      this.ads = resData;
    },
    //根据订单查看
    async getDetailByOrder() {
      try {
        const data = await this.$api.get(`/v1/bargain-order/order/${this.id}`);
        if (!!data) {
          this.orderDetail = data;
        } else {
          this.tipObj = {
            title: '已结束',
            content: '该活动已结束',
          };
          this.tipShow = true;
          this.orderDetail = null
        }
      } catch (error) {
        console.log(error);
      }
    },
    //查看自己邀请的人
    async getDetailOrderBySku() {
      try {
        const data = await this.$api.get(`/v1/bargain-order/sku/${this.skuId}`);
        this.orderDetail = data;
      } catch (error) {
        console.log(error);
      }
    },
    //获取砍价商品
    async getGoodsDetail() {
      try {
        const resData = await this.$api.get(`/v1/bargain-sku/${this.skuId}`);
        this.goodsDetail = resData;
      } catch (error) {
      } finally {
        this.isFirstLoading = false;
      }
    },
    // 邀请朋友砍价
    async onInviteBargain() {
      const resData = await this.$api.post(`/v1/bargains/create-order/${this.skuId}`);
      this.getDetailOrderBySku();
    },
    //帮砍
    async onHelp() {
      if (this.btnLoading) return;
      this.btnLoading = true;
      try {
        await this.$api.post(`/v1/bargains/bargain/${this.id}`, {}, { custom: { toast: false } });
        this.$u.toast('砍价成功');
        this.init();
      } catch (error) {
        this.tipObj = {
          title: '提示',
          content: error.message,
        };
        this.tipShow = true;
      } finally {
        this.btnLoading = false;
      }
    },
    //微信快捷登录
    async getPhoneNumber(e) {
      const { encryptedData, iv } = e.detail;
      if (!iv) return;
      const invite_code = uni.getStorageSync('INVITE_CODE');
      const code = await getWxCode();
      const params = {};
      if (!!invite_code) params.inviter_code = invite_code;
      const resData = await this.$api.post('/v1/socialite/code-bind-user/wechat-mini', {
        type: 'wechat-mini',
        code,
        iv,
        data: encryptedData,
        ...params,
      });
      this.LOGIN(resData.token);
      uni.navigateBack({
        delta: 1,
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.mx-auto{
  margin-left: auto;
  margin-right: auto;
}
.title {
  position: relative;
  display: inline-block;
  &::after,
  &::before {
    content: '';
    height: 1px;
    width: 14px;
    background: #eb8d42;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
  }
  &::after {
    right: -30px;
  }
  &::before {
    left: -30px;
  }
}

.shadowqr {
  box-shadow: 0px 0px 10px #f9b1767a;
}
</style>
