<template>
  <div class="cards">
    <div class="card-top" v-if="nftData" @click="toDetail">
      <div class="card-img">
        <ImgCard :nftData="nftData.nft" />
      </div>
      <div class="card-name">
        <div>Cotnesford park</div>
        <div>{{nftData.nft.name}}</div>
      </div>
      <div class="card-price">
        <div>
          <span>
            {{ price }}
          </span>
          <img :src="icon" alt="图片">
        </div>
        <div class="card-address">{{ nftData.nft.owner_address.substr(0,4) }}...{{ nftData.nft.owner_address.substr(-4) }}</div>
      </div>
    </div>
    <div class="card-btn" v-if="nftData.nft.owner_address != localWalletStore.address">
      <div class="card-buy" @click="localWalletStore.address == '' ? cardLogin() : buyNft(nftData)">Buy Now</div>
      <div v-if="nftData.in_shopcart == 0" class="card-cat" @click.stop="localWalletStore.address == '' ? cardLogin() : addCart(nftData)">
        <img src="@/assets/img/marketplace/Add shopping cart.png" alt="">
      </div>
      <div v-else class="card-cat" @click.stop="clearCart(nftData)">
        <img src="@/assets/img/marketplace/Move out.png" alt="">
      </div>
    </div>
    <div class="card-btn" v-else>
      <div class="card-cancel" @click="cancelNft(nftData)">Off the shelves</div>
    </div>
  </div>
</template>

<script setup>
import { ref, toRaw, onMounted, getCurrentInstance, defineEmits,inject } from "vue"
const message = inject('$message')
import BuyDialog from "@/components/Dialogs/buyDialog.vue"
import ImgCard from "@/components/common/imgCard.vue"
import {priceCalculated} from "@/configs/priceCalculate.js"
import {walletStore} from "@/store/wallet";
import { BlockChain } from "@/components/chain/BlockChain"
import {
  useMarketplaceStore
} from "@/store/marketplace"
const localWalletStore = walletStore()
const marketplaceList = useMarketplaceStore()
import {createModal} from "@/utils/model.util";
import {formatPrice} from "@/components/chain/utils"
const emit = defineEmits(['renewNft'])
import { useRouter } from "vue-router";
const router = useRouter();
const icon = ref('')
const price = ref('-')
const { proxy } = getCurrentInstance();
const props = defineProps({
  nftData: {
    type: Object,
    required: true,
  },
});

const buyDataArr = ref([])

// 确认购买弹窗
const buyNft = async (val) => {
  buyDataArr.value = []
  buyDataArr.value.push(val)
  const buyResult = await createModal(BuyDialog, {
    buyDataArr: buyDataArr.value,
  }).show()
  if(buyResult.errcode) {
    console.log('buy fail')
    message.success('buy fail')
    return 
  }
}

// 取消售卖
const cancelNft = async (val) => {
  try {
    const bc = new BlockChain()
    let res = await bc.market.cancelOrder([val.event.data.id])
    console.log(res,[val.event.data.id])
    if(res.result) {
      message.success('Your item has been unlisted.')
      emit('renewNft')
    }
  } catch (e) {
    console.log(e)
    message.error('Your item has failed to be unlisted.')
  }
}

// 去详情页面
const toDetail = () => {
  const _data = toRaw(props.nftData)
  router.push(`/detail/${_data.nft.contract_address}/${_data.nft.token_id}`)
}

// 添加购物车
const addCart = async (val) => {
  console.log('-',val.nft)
  const data = {
    net_id: import.meta.env.VUE_APP_NET_ID,
    tokens: [
      {
        token_id: val.nft.token_id,
        contract_address: val.nft.contract_address,
      }
    ]
  }
  
  try {
    
    let res = await marketplaceList.getCartListState()
    if (res.data && res.data.length) {
      const currency = res.data[0].event?.data?.buy[0].contract_address || ''
      const type = res.data[0].event?.data?.buy[0].item_type || ''
      const currentCurrency = val.event?.data?.buy[0].contract_address || ''
      const currentType = val.event?.data?.buy[0].item_type || ''
      if (currency != currentCurrency || type != currentType) {
        // TODO: 提示用户添加相同类型的商品
        alert('Please add the same type of item to the shopping cart')
        return
      }
    }

    const { errcode, errmsg } = await marketplaceList.addCartListState(data)
    console.log(errcode, errmsg)
    if(errcode == 0) {
      message.success('success! Add from cart')
      marketplaceList.getCartList = await marketplaceList.getCartListState()
    }
  } catch (e) {
    message.error('fail! Add from cart')
  }
}

// 移除购物车
const clearCart = async (val) => {

}

// 登录
const cardLogin = async () => {
  await new BlockChain().connect()
}

onMounted(() => {
  // console.log(JSON.parse(JSON.stringify(props.nftData)), "-=-=-");
  if (props.nftData?.event?.data) {
    const data = formatPrice(props.nftData?.event?.data)
    icon.value = data.icon
    price.value = priceCalculated(data.amount.toString())
  }
});
</script>

<style lang="scss" scoped>
.cards {
  background: #2d2738;
  border-radius: 20px;
  color: #fff;
  // padding: 20px;
  overflow: hidden;
  .card-top {
    padding: 30px 30px 20px 30px;
    .card-img {
      width: 240px;
      height: 360px;
      margin: 0 auto;
      :deep(.card-img-common) {
        .img-top {
          width: 100px;
          height: 30px;
          top: 20px;
          left: 20px;
        }
        .img-btm {
          bottom: 12px;
          left: 20px;
          >div {
            width: 80px;
            height: 30px;
          }
          div:nth-child(2) {
            margin-left: 8px;
          }
        }
      }
    }
    .card-name {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 20px 0;
    }
    .card-price {
      display: flex;
      justify-content: space-between;
      align-items: center;
      div {
        display: flex;
        justify-content: space-between;
        align-items: center;
        img {
          width: 25px;
          height: 25px;
          margin-left: 10px;
        }
      }
      .card-address {
        justify-content: center;
        background: #101019;
        width: 160px;
        height: 33px;
        border-radius: 16px;
        font-family: 'Poppins';
        font-weight: 400;
        font-size: 20px;
        color: #F3F0FF;
      }
    }
  }
  .card-btn {
    width: 95%;
    height: 50px;
    margin: 0 auto;
    margin-bottom: 5px;
    border-radius: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 5px;
    >div {
      height: 57px;
      line-height: 57px;
      background: #1778f1;
      border-radius: 12px;
      text-align: center;
      color: #fff;
      font-weight: 700;
      font-size: 28px;
    }
    .card-buy {
      width: 272px;
    }
    .card-cat {
      width: 71px;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 3px;
      img {
        width: 43px;
        height: 39px;
      }
    }
    .card-cancel {
      width: 100%;
      background: #ff6271;
    }
  }
}
</style>