<template>
  <Layout-Child class="page-scroll">
    <div class="w-11/12 mx-auto mt-6 text-font-white">
      <SkeletonNftDetail v-if="showSkelton" />
      <div v-if="$route.query.officia">
        <div class="h-80">
          <img class=" max-h-72 mx-auto" :src="nftData.cover?nftData.cover:'@/assets/img/NFTCover.png'" alt="" />
          <!-- <img class=" max-h-72 mx-auto" src="@/assets/img/NFTCover.png" alt="" /> -->
        </div>
        <div>
          {{ nftData.name }}
        </div>
        <div class="flex text-sm text-font-dark-blue justify-between my-3">
          <div>全球限量发行{{ nftData.publishCount }}</div>
          <div>
            已领取 <i class="text-font-blue">{{ nftData.receiveCount }}</i> 个
          </div>
        </div>
        <div
          class="
            border border-font-dark-blue border-opacity-50
            rounded-lg
            text-sm
            p-6
            text-font-dark-blue
          "
        >
          纪念版NFT只能进行转让，不能进行交易。最终解释权归平台所有。
        </div>
      </div>
      
      <div v-else-if="nftData.isCommemorate == 1 || nftData.category == '图片'">
        <div class="h-80 flex items-center">
          <!-- <img class=" max-h-72 mx-auto" src="@/assets/img/NFTCover.png" alt="" /> -->
          <img class=" max-h-72 mx-auto" :src="nftData.cover?nftData.cover:'@/assets/img/NFTCover.png'" alt="" />
        </div>
      </div>

      <!-- <div v-else-if="nftData.category == '图片'">
        <div class="h-80 flex items-center">
          <img class=" max-h-72 mx-auto" :src="nftData.cover?nftData.cover:nftData.fileUrl" alt="" />
        </div>
      </div> -->

      <app-collectionCard :colletionData="nftData" v-else></app-collectionCard>
      <div class="app-icons mx-auto flex justify-around my-6" v-if="isOwner">
        <div
          v-for="(i, index) in (nftData.isCommemorate == 0?apps:ComApps)"
          :key="index + nftData.isCommemorate"
          class="flex justify-center "
          
        >
          <div class="flex flex-col items-center">
            <div class="flex content-center">
              <!-- <app-icon
                @click.native="appOnclick(i.action)"
                :name="i.icon"
                size="24px"
                class="p-5 bg-table-light-blue shadow-md rounded-full"
              ></app-icon> -->
              <img :src="i.icon" alt="" @click="appOnclick(i.action)" />
            </div>
            <div class="text-xs mt-3 text-font-white">
              {{ i.text }}
            </div>
          </div>
        </div>
      </div>
      <div
        class="
          text-xs
          w-full
          flex
          border-b border-font-dark-blue border-opacity-50
          items-center
        "
      >
        <div class="py-3 pr-4">
          <img
            :src="nftData.avatar ? nftData.avatar : '/img/mokeImg/avatar.png'"
            class="h-12 w-12 rounded-full"
            @click="gotoUserDetail()"
          />
        </div>
        <div>
          <div class="flex items-center">
            <div class="pr-3 text-sm">
              {{ nftData.publisher ? nftData.publisher : "匿名" }}
            </div>
            <app-tag text="发行人" :id="1" class=" bg-font-light-black" :disabled="true"></app-tag>
          </div>
          <div class="mt-1 text-font-dark-blue">{{ nftData.wallet?nftData.wallet:nftData.publishAddress }}</div>
        </div>
      </div>
      <div class="py-3">
        <div class="text-font-dark-blue">NFT信息</div>
        <app-cell
          v-if="nftData.isCommemorate == 0"
          text="编号"
          :value="nftData.nftId"
          boxType="border"
        ></app-cell>

        <app-cell
          text="NFT哈希"
          :name="nftData.nftHash?nftData.nftHash:nftData.fileHash"
          boxType="border"
          type="showText"
          :needCopy="true"
        ></app-cell>
        <app-cell
          v-if="nftData.isCommemorate == 0"
          text="文件哈希"
          :name="nftData.fileHash"
          boxType="border"
          type="showText"
          :needCopy="true"
        ></app-cell>
        <app-cell
          text="发行时间"
          :value="nftData.publishTime"
          boxType="border"
        ></app-cell>
      </div>
      <div class="py-3" v-if="nftData.isCommemorate == 0">
        <div class="text-font-dark-blue">版权信息</div>
        <!-- <app-cell
          text="版权登记号"
          value="JOYING-20210615-HONGJUREN"
          boxType="border"
        ></app-cell> -->
        <app-cell
          text="作者"
          :value="nftData.author ? nftData.author : '无'"
          boxType="border"
        ></app-cell>
        <!-- <app-cell
          text="发行人地址"
          :value="nftData.wallet ? nftData.wallet : '无'"
          boxType="border"
        ></app-cell> -->
        <!-- <app-cell
          text="著作权人"
          value="JOYING-20210615-HONGJUREN"
          boxType="border"
        ></app-cell>
        <app-cell
          text="版权登记日期"
          value="JOYING-20210615-HONGJUREN"
          boxType="border"
        ></app-cell>
        <app-cell
          text="版权HASH"
          value="JOYING-20210615-HONGJUREN"
          boxType="border"
        ></app-cell> -->
      </div>

      <div class="py-3">
        <!-- <div class="text-font-dark-blue">剧本简介</div> -->
        <div class="text-font-dark-blue" v-if="nftData.isCommemorate == 0">作品简介</div>
        <div class="text-font-dark-blue" v-if="nftData.isCommemorate == 1 || $route.query.officia">纪念版NFT简介</div>
        <div class="py-2 tracking-wide leading-6 text-sm break-all">
          {{ nftData.synopsis ? nftData.synopsis : "无" }}
        </div>
      </div>

      <div class="py-3">
        <div class="text-font-dark-blue">关于NFT</div>
        <div class="py-2 tracking-wide leading-6 text-sm break-all">
          NFT全称为Non-Fungible
          Token，也称为非同质化通证。可以通俗化理解为在区块链上的唯一凭证。电影产业中，能够为剧本、电影、花絮、剧照、音乐等作品发行NFT，链上确权、高效流转、不可替代、独一无二。能够保护编剧及电影人的知识产权，挖掘版权交易价值，提高创作收益，丰富影视行业良好生态，创造影视版权数字化经济。
        </div>
      </div>

      <div class="py-3" v-if="!$route.query.officia">
        <div class="text-font-dark-blue">流转记录</div>
        <div class="text-center py-5">暂无记录</div>
      </div>
      <van-overlay :show="showoverlay" @click="showoverlay = false" />
      <div class="scroll-padding"></div>

      <div
        class="
          fixed
          bottom-0
          w-full
          left-0
          z-30
          flex
          items-center
          px-5
           pb-7
          bg-font-black bg-opacity-80
          shadow-nav
          flex-col
        "
        v-if="!$route.query.officia"
      >
          <div class="w-10/12 pt-8" v-if="showoverlay">
          <app-cell text="NFT类型" :value="nftData.category" class="my-1"></app-cell>
          <app-cell
            text="文件名"
            :value="nftData.name || '未上传文件'"
            class="my-1"
          ></app-cell>
          <div class="flex justify-center">
            <van-image
              v-if="nftData.isCommemorate == 1 || nftData.category == '图片'"
              class="my-3 self-center text-center"
              width="180"
              lazy-load
              @click="downloadFile"
              src="/img/mokeImg/查看NFT.png"
            />
            <van-image
              v-else-if="nftData.isCommemorate == 0"
              class="my-3 self-center text-center"
              width="180"
              lazy-load
              @click="downloadFile"
              :src="nftData.fileUrl?'/img/mokeImg/已加密.png':'/img/mokeImg/暂无内容.png'"
            />
            <!-- <van-image
              v-if="nftData.isCommemorate == 0"
              class="my-3 self-center text-center"
              width="180"
              lazy-load
              :src="nftData.fileUrl?!nftData.isGrant?nftData.fileUrl:'/img/mokeImg/已加密.png':'/img/mokeImg/暂无内容.png'"
            /> -->
          </div>
        </div>
        <div class='flex w-full items-center'>
          <div class="flex-grow-0">
          <div @click="editCollection">
            <app-icon
              name="icon-heart1"
              size="25px"
              v-if="inMyCollection"
              color="#ED6F6F"
            ></app-icon>
            <app-icon name="icon-heart" size="25px" v-else></app-icon>
          </div>
        </div>
        <div class="flex-grow pl-8">
          <app-btn
            @click.native="confirmBtn"
            text="查看内容"
            class="w-full mx-auto text-font-white rounded-2xl bg-font-blue"
            border="none"
          ></app-btn>
        </div>
        </div>

      </div>



      <div
        class="
          fixed
          bottom-0
          w-full
          left-0
          z-30
          flex
          items-center
          px-5
          pb-7
          bg-font-black bg-opacity-95
          shadow-nav
          flex-col
        "
        v-else
      >
        <div class="flex-grow w-10/12">
          <app-btn
            :text="
              nftData.status === 0
                ? '已领取，去查看'
                : nftData.status === 1
                ? '立即领取'
                : '已经领完'
            "
            class="w-full mx-auto text-font-white rounded-2xl bg-font-blue"
            border="none"
            @click.native="confirmBtn"
          ></app-btn>
        </div>

      </div>
        <div class=" fixed bottom-0 left-0 right-0 top-0 bg-font-black flex items-center z-50" v-if="getOfficialNft == 'loading'">
          <div class=" w-4/6 mx-auto text-center">
            <img src="@/assets/img/saveLoading.png" alt="" class=" mx-auto">
            <div class=" mt-5">证书领取中，请稍后~~</div>
          </div>
        </div>

        <div class=" fixed bottom-0 left-0 right-0 top-0 bg-font-black flex items-center z-50 overflow-y-scroll" v-if="getOfficialNft == 'success'">
          <div class="w-10/12 mx-auto text-center">
            <certificate :categoryId="nftData.category" :certificateData="certificateData" ></certificate>
            <img
              @click="getOfficialNft=''"
              src="@/assets/icons/close_publish.png"
              class="w-4 xs:w-6 mx-auto mt-3"
              />
          </div>
        </div>

        <div class=" fixed bottom-0 left-0 right-0 top-12 bg-font-black flex items-center z-50" v-if="getOfficialNft == 'fail'">
          <div class=" w-4/6 mx-auto text-center">
            <img src="@/assets/img/earth.png" alt="" class=" mx-auto w-4/6">
            <div class=" mt-5">抱歉，NFT领取失败!</div>
            <div>
              <app-btn class=" w-2/6 mx-auto text-font-white rounded-2xl bg-font-blue" text="重新领取" @click.native="confirmBtn" border="none">
              </app-btn>
            </div>
          </div>
        </div>
        <!-- <van-overlay v-if>
          <app-cell text="NFT类型" :value="nftData.category" class="my-1"></app-cell>
          <app-cell
            text="文件名"
            :value="nftData.fileName || '未上传文件'"
            class="my-1"
          ></app-cell>
          <div class="flex justify-center">
            <van-image
              class="my-3 self-center text-center"
              width="180"
              lazy-load
              :src="nftData.fileUrl"
            />
          </div>
        </van-overlay> -->
        <div class=" fixed bottom-0 left-0 right-0 top-0 bg-font-black flex items-center z-50 overflow-y-scroll" v-if="showCertificate ">
          <div class="w-10/12 mx-auto text-center">
            <certificate :categoryId="nftData.category" :certificateData="certificateData"></certificate>
            <img
              @click="showCertificate = false"
              src="@/assets/icons/close_publish.png"
              class="w-4 xs:w-6 mx-auto mt-3"
              />
          </div>
        </div>
      <van-popup v-model="showGoSafe" class=" bg-font-light-black pt-3 pb-10 rounded-lg text-white w-3/4">
          <div class=" text-font-dark-blue pl-5 pr-5 h-10 border-b border-table-light-blue flex items-center justify-between">
            <div>温馨提示</div>
            <div>
              <img class=" w-7" src="/img/closeBtn.2ecdb438.svg" alt="" @click="showGoSafe=false">
            </div>
          </div>
          <div class=" text-sm mt-5 pl-5 pr-5">您需要通过实名认证后才能转让您的NFT哦！</div>
          <div class=" w-20 h-8 leading-8 rounded-full mx-auto bg-font-blue text-center mt-5" @click="gotoSafe()">去认证</div>
      </van-popup>
    </div>
  </Layout-Child>
</template>

<script lang="ts">
import Vue from "vue";
import SkeletonNftDetail from "@/components/common/Skeleton/SkeletonNftDetail.vue";
import { token } from "@/util/userInfoUtils";
import anquanzhongxin89 from "@/assets/img/check.png";
import chakan from "@/assets/img/upload.png";
import atupian from "@/assets/img/transfer.png";
import BOSSyingyetingchushi from "@/assets/img/certigicate.png";
import { Overlay,Popup } from "vant";
import download from "downloadjs";

Vue.use(Overlay);
Vue.use(Popup);
const apps = [
  {
    text: "版权认证",
    icon: anquanzhongxin89,
  },
  {
    text: "大厅下架",
    icon: chakan,
  },
  {
    text: "NFT转让",
    icon: atupian,
    action: "pushToTransfer",
  },
  {
    text: "查看证书",
    icon: BOSSyingyetingchushi,
    action: "showCertificate",
  },
];

const ComApps = [
  {
    text: "NFT转让",
    icon: atupian,
    action: "pushToTransfer",
  },
  {
    text: "查看证书",
    icon: BOSSyingyetingchushi,
    action: "showCertificate",
  },
];

export default Vue.extend({
  data() {
    return {
      id: this.$route.params.id,
      apps,
      ComApps,
      showoverlay: false,
      showSkelton: true,
      nftData: {} as any,
      collectionData: {},
      inMyCollection: false,
      isOwner: false,
      user: this.$util.userMsg.getUserMsg() as any,
      getOfficialNft: '',
      showCertificate: false,
      // loading:true
      showGoSafe:false
    };
  },
  computed:{
    certificateData():any{
      return {
        NFTHash:this.nftData.nftHash,
        value_name: this.nftData.name,
        wallet: this.nftData.publishAddress || this.nftData.wallet,
        publisher: this.nftData.publisher,
        cover: this.nftData.cover,
        publishTime: this.nftData.publishTime,
        fileHash: this.nftData.fileHash
      }
    }
  },
  async created() {
    console.log(this.$route.query.officia);
    if (this.$route.query.officia) {
      this.nftData = await this.$service.nftService.officialNFTDetail(
        parseInt(this.id)
      );
      console.log(this.nftData);
      
    }else{
      this.nftData =await this.$service.nftService.getNFTdetail(this.id)
      this.nftData.userId == this.user.id? this.isOwner=true:this.isOwner=false
      if(!token.getToken()) {
          this.showSkelton = false
          return 
      }
      /**
       * 这个注释后面要去掉
       */
       await this.setMyCollection();
    }

    this.showSkelton = false;
  },

  components: {
    "Layout-Child": () => import("@/layout/Child.vue"),
    "app-icon": () => import("@/components/common/Icon.vue"),
    "app-tag": () => import("@/components/common/Tag.vue"),
    "app-cell": () => import("@/components/common/Cell.vue"),
    "app-btn": () => import("@/components/common/Btn.vue"),
    //  'app-scrollbar':()=>import('@/components/common/ScrollBar.vue'),
    "app-collectionCard": () => import("@/components/CollectionCard.vue"),
    "certificate": () => import("@/view/NFT/Create/components/certificate/index.vue"),
    SkeletonNftDetail,
  },
  methods: {
    appOnclick(action: any) {
      const auth = localStorage.getItem('isCertificate')
      switch (action) {
        case "pushToTransfer":
          if(auth != 'true') {
            this.showGoSafe = true
            break;
          }
          this.$router.push({
            name: "NftTransfer",
            query: {
              nftId: this.nftData.id,
              from: this.nftData.wallet,
              avatar: this.nftData.avatar,
              nftName: this.nftData.name,
              ownerName: this.nftData.publisher,
            },
          });
          break;
        case "showCertificate":
          this.showCertificate = true;
          break;

        default:
          break;
      }
    },
    async downloadFile(){
      if(this.nftData.fileUrl && this.isOwner){
        this.$toast.loading('NFT下载中。。。')
        const downloadByUrl = (url:string)=>{
            const link = document.createElement('a')
            link.download = this.nftData.fileName
            link.style.display = 'none'
            link.href = url
            document.body.appendChild(link)
            link.click()
            URL.revokeObjectURL(link.href)
            document.body.removeChild(link)
        }
        if(this.nftData.category == '图片'){
          const url = this.nftData.fileUrl
          downloadByUrl(url)
        }else {
          const res = await this.$service.nftService.downloadNFTFile(this.nftData.id)
          if(res.type !== 'application/json') {
            const blob = new Blob([res]);
            const url = window.URL.createObjectURL(blob)
            downloadByUrl(url)
          }
        }
        this.$toast.success('NFT下载完成')
      }
    },
    async confirmBtn() {
      if(!this.$route.query.officia) {
        this.showoverlay = true
        if(!this.nftData.fileUrl && this.nftData.isCommemorate == 0) {
          this.$toast('NFT没有上传过附件，不可查看')
        }
      }
      if (this.nftData.status === 1) {
            this.getOfficialNft='loading'
            this.$service.nftService
            .applyOfficialNft(Number(this.$route.params.id))
            .then((res) => {
              if (res) {
                this.getOfficialNft='success'
                download(this.nftData.fileUrl);
                this.$toast("领取成功");
                // this.$router.replace("");
                this.nftData.status = 0
              }else {
                this.getOfficialNft='fail'
              }
            }).catch(()=>{
              this.getOfficialNft='fail'
            })
        // if (!this.showoverlay) {
        //   this.showoverlay = true;
        // } else {
        //   this.$service.nftService
        //     .applyOfficialNft(Number(this.$route.params.id))
        //     .then((res) => {
        //       if (res) {
        //         download(this.nftData.fileUrl);
        //         this.$toast("领取成功");
        //         this.$router.replace("");
        //       }
        //     })
        // }
      }else if(this.nftData.status == 0){
        this.$router.push({name:'myListNft',query:{category:this.nftData.category}})
      }else{
          console.log(11);
          
        //  this.showoverlay = true;
      }
    },
    async setMyCollection(): Promise<void> {
      if (!token.getToken()) {
        this.$router.push("/auth/login");
      }
      let list = await this.$service.nftService.getCollection();
      if (list.find((i) => i.id == this.id)) {
        this.inMyCollection = true;
      } else {
        this.inMyCollection = false;
      }
    },
    async editCollection() {
      if (!token.getToken()) {
        this.$router.push("/auth/login");
      }
      await this.$service.nftService
        .editCollection(parseInt(this.id))
        .then(async (res) => {
          if (res) {
            await this.setMyCollection();
            if (this.inMyCollection) {
              this.$toast.success("NFT已经收藏成功");
            } else {
              this.$toast.success("NFT已从我的收藏中移除");
            }
          }
        });
    },
    gotoUserDetail(){
      this.$router.push({
        name:'UserDetail',
        query:{
          avatar:this.nftData.avatar || '/img/mokeImg/avatar.png',
          nickName:this.nftData.publisher || "匿名",
          signature:this.nftData.signature || '暂无',
        }
      })
    },
    gotoSafe(){
      this.showGoSafe = false
      this.$router.push('/safe')
    }
  },
});
</script>
