<template>
  <Layout-Child class="page-scroll pb-20">
    <!-- 发行的步骤条 -->
    <div class=" mx-auto my-6">
      <app-steps
        v-if="currentStep !== 4"
        :data="mySteps"
        :currentStep="currentStep"
        @stepOnChange="stepOnChange"
        @stepOnFinished="stepOnFinished"
      ></app-steps>
    </div>

    <!-- 具体每一步 -->
    <div class="w-11/12 mx-auto">
      <!-- 第一步 -->
      <div class="step-one" v-if="currentStep == 1">

        <app-cell
          v-model="createNFT.value_name"
          type="input"
          :text='fromText.nameText'
          :validate="{ maxLen: 15 }"
          :placeholder="fromText.namePlaceholder"
          class="text-font-white my-3 text-sm"
          @cellOnChange="(v) => setCreateNFT({ value_name: v })"
        ></app-cell>
        <app-cell
          :text="fromText.authorText"
          class="text-font-white my-3 text-sm text-right"
          type="showText"
          :name="createNFT.value_publisher"
        ></app-cell>
        <!-- <app-cell
          v-model="createNFT.value_publisher"
          type="showText"
          :text="fromText.authorText"
          :validate="{ maxLen: 15 }"
          :placeholder="fromText.authorPlaceholder"
          class="text-font-white my-3 text-sm"
        ></app-cell> -->
        <!-- <app-cell
          :pickValue="mySteps"
          type="pick"
          :text="fromText.themeText"
          :placeholder="fromText.themePlaceholder"
          class="text-font-white my-3"
          @click.native="$router.push({name:'NftPick',query:{text:`${getPreText()}题材`,id:categoryId}})"
        ></app-cell> -->
        <app-cell
          text="展示封面(选填)"
          class="text-font-white my-3 text-sm"
          labelIcon="icon-wenhao"
          @clickIcon="alertCoverTip"
          type="upload"
          placeholder="请上传相关封面"
          :name="coverName"
          @cellOnChange="$router.push({ name: 'NftUpload',query:{type:'封面图片'}})"
        ></app-cell>
        <div>
          <div class="my-4 text-font-gray text-sm ml-4">{{fromText.desText}}</div>
          <textarea
            v-model="createNFT.value_des"
            name="des"
            id="nft-des"
            cols="30"
            maxlength="500"
            :placeholder="fromText.desPlaceholder"
            rows="10"
            class="
              w-full
              bg-font-gray bg-opacity-20
              text-font-white
              p-3
              rounded-md
              text-sm
            "
          ></textarea>
        </div>
        <div class="fixed bottom-3 w-full left-0 z-30">
          <app-btn
            text="下一步"
            class="w-11/12 mx-auto text-font-white rounded-2xl bg-font-blue"
            :disabled="validation"
            border="none"
            @btnClicked="currentStepChange(1)"
          ></app-btn>
        </div>
      </div>

      <!-- 第二步 -->
      <div class="step-two" v-if="currentStep == 2">
        <app-cell
          :text="fromText.fileUploadText"
          class="text-font-white my-3 text-sm"
          type="upload"
          :placeholder="fromText.filePlaceholder"
          :name="fileName"
          labelIcon="icon-wenhao"
          @clickIcon="alertHashExplain"
          @cellOnChange="$router.push({ name: 'NftUpload',query:{type:getPreText()}})"
        ></app-cell>
        <app-cell
          :text="fromText.fileHashText"
          class="text-font-white my-3 text-sm"
          type="showText"
          :name="fileHash"
          @cellOnChange="getValue"
        ></app-cell>

        <!-- <app-cell
          v-if="['1','2'].indexOf(categoryId) != -1"
          text="附件上传"
          type="select"
          :selected="createNFT.archives"
          labelIcon="icon-wenhao"
          @clickIcon="alertPlatformSave"
          :list="archivesList"
          class="text-font-white my-3 text-sm"
          @cellOnChange="(v) => (createNFT.archives = v)"
        ></app-cell>
        <app-cell
          v-if="createNFT.archives === 1"
          text="授权阅读"
          type="select"
          :selected="createNFT.grant"
          labelIcon="icon-wenhao"
          @clickIcon="alertAuthorizeRead"
          :list="grantList"
          class="text-font-white my-3 text-sm"
          @cellOnChange="(v) => (createNFT.grant = v)"
        ></app-cell> -->
        <div class="fixed bottom-3 w-full left-0 flex flex-row z-30">
          <app-btn
            text="上一步"
            class="w-5/12 mx-auto text-font-white rounded-2xl bg-font-blue"
            border="none"
            @btnClicked="currentStepChange(-1)"
          ></app-btn>
          <app-btn
            text="下一步"
            class="w-5/12 mx-auto text-font-white rounded-2xl bg-font-blue"
            :disabled="validation"
            :loading="loading2"
            border="none"
            @btnClicked="currentStepChange(1)"
          ></app-btn>
        </div>
      </div>

      <!-- 第三步 -->
      <div class="step-three" v-if="currentStep == 3">
        <app-cell
          text="NFT编号"
          type="showText"
          :name="publish.nftId"
          class="text-font-white my-3 text-sm"
        ></app-cell>
        <app-cell
          :text="fromText.fileHashText"
          type="showText"
          :name="publish.fileHash"
          class="text-font-white my-3 text-sm"
          @cellOnChange="getValue"
        ></app-cell>
        <app-cell
          text="发行人地址"
          type="showText"
          :name="publish.wallet"
          class="text-font-white my-3 text-sm"
          @cellOnChange="getValue"
        ></app-cell>
        <app-cell
          key="count"
          text="数量"
          :value="1"
          :disabled="true"
          type="input-num"
          class="text-font-white my-3 text-sm"
          @cellOnChange="
            (v) => {
              publish.count = v;
            }
          "
        ></app-cell>
        <div class="fixed bottom-3 w-full left-0 flex flex-row z-30">
          <app-btn
            text="上一步"
            class="w-5/12 mx-auto text-font-white rounded-2xl bg-font-blue"
            border="none"
            @btnClicked="currentStepChange(-1)"
          ></app-btn>
          <app-btn
            text="发行NFT"
            class="w-5/12 mx-auto text-font-white rounded-2xl bg-font-blue"
            border="none"
            :disabled="validation"
            :loading="loading3"
            @btnClicked="currentStepChange(1)"
          ></app-btn>
        </div>
      </div>

      <!-- 第四步 -->
      <div v-if="currentStep == 4" class="text-font-white">
        <!-- 第四步发行中 -->
        <div
          v-if="loading4"
          class="flex flex-col items-center w-full pt-16 justify-center"
        >
          <breeding-rhombus-spinner
            :animation-duration="2000"
            :size="60"
            :color="'#0078FF'"
          />
          <div class="mt-6 text-font-white">发行中...</div>
          <div>
            <img src="@/assets/img/saveLoading.png" alt="">
          </div>
          <div class=" mt-4 text-red-500">温馨提示：</div>
          <div class=" w-72 text-center mt-4 leading-8">NFT发行成功后，需经过内容审核，审核通过后方可在平台内上架流转。</div>
        </div>
     
        <div v-else class="text-center">
          <!-- 第四步发行成功 -->
          
          <div v-if="success" class="">
              <!-- <div v-if="showOverlay"  class=" fixed left-0 right-0 top-0 bottom-0 bg-gray-800 z-50 overflow-y-scroll" >
                <div class="w-10/12 mx-auto">
                  <certificate :certificateData="certificateData" :categoryId="categoryId"/>
                  <img
                    @click='showOverlay = !showOverlay'
                    src="@/assets/icons/close_publish.png"
                    class="w-4 xs:w-6 mx-auto mt-3"
                  />
                </div>
              </div> -->
              <certificate v-if="showOverlay" :certificateData="certificateData" @hiddenCer="showOverlay = !showOverlay" :openBrowser="false"></certificate>
              <div class="w-10/12 mx-auto mt-32">
                 <img src="@/assets/img/success.png" class="w-36 mx-auto ">
                 <div class="mt-20">
                   NFT发行成功
                 </div>
                 <app-btn text="确认" class=' bg-font-blue' @click.native="$router.push('/Home')"></app-btn>
              </div>
          </div>
          <!-- 第四步发行失败 -->
          <div
            v-else
            class="flex flex-col items-center w-full pt-16 justify-center"
          >
            <img src="@/assets/img/earth.png" class="w-8/12" alt="" />
            <div class="mt-16">抱歉，NFT发布失败！</div>
            <div>失败原因：{{ errorMsg }}</div>
            <div class="republishBtn mt-6" @click="clickRepublish">
              重新发行
            </div>
          </div>
        </div>

      </div>
    </div>
  </Layout-Child>
</template>

<script lang="ts">
import { iSaveData } from "@/service/nftService/types";
import { BreedingRhombusSpinner } from "epic-spinners";

import { Overlay } from 'vant'
import { Dialog } from "vant";
import Vue from "vue";
import { mapMutations, mapState } from "vuex";
Vue.use(Overlay)
export default Vue.extend({
  data() {
    return {
      a: "",
      createNFT: {
        value_name: "",
        value_publisher: JSON.parse(localStorage.getItem('KEY_USER') as string).authPerson.name,
        value_picker: [],
        value_des: "",
        archives: 0,
        grant: 1,
        categoryType: NaN,
      },
      fromText:{
        nameText:'',
        namePlaceholder:'',
        authorText:'',
        authorPlaceholder:'',
        themeText:'',
        themePlaceholder:'',
        desText:'',
        desPlaceholder:'',
        fileUploadText:'',
        filePlaceholder:'',
        fileHashText:''
      },
      publish: {
        nftId: "",
        id: NaN,
        fileHash: "",
        wallet: "",
        count: 1,
      },
      archivesList: [
        { value: 0, name: "不上传" },
        { value: 1, name: "加密上传" },
      ],
      grantList: [
        { value: 0, name: "不需要授权" },
        { value: 1, name: "需要授权" },
      ],
      categoryTypes: [] as any[],
      categoryId:this.$route.query.id as string,

      currentStep: 1,
      showOverlay:true,
      loading2: false,
      loading3: false,
      loading4: false,
      success: true,
      errorMsg: "",
      certificateData:{},
    };
  },
  components: {
    "Layout-Child": () => import("@/layout/Child.vue"),
    "app-steps": () => import("@/components/common/Steps.vue"),
    "app-cell": () => import("@/components/common/Cell.vue"),
    "app-btn": () => import("@/components/common/Btn.vue"),
    // certificate: () => import("./components/certificate/index.vue"),
    certificate: () => import("@/components/common/Certificate.vue"),
    BreedingRhombusSpinner
  },
  async mounted() {
    const data = await this.getPreText()
    this.fromText = this.concatFormText(data)
    const list = await this.$service.nftService.getCategory();
    this.categoryTypes = list;
    this.createNFT.categoryType = (list.length !== 0 && list[0].id) || NaN;
    this.setState({
      pickedList: [],
    });
  },
  destroyed() {
    this.setState({
      pickedList: [],
      fileHash: "",
      fileName: "",
      file: undefined,
      coverName: '',
      coverFile: undefined
    });
  },
  computed: {
    ...mapState("create", {
      fileHash: "fileHash",
      fileName: "fileName",
      file: "file",
      pickedList: "pickedList",
      coverName: 'coverName',
      coverFile: "coverFile"
    }),
    validation(): boolean {
      let disabled = true;
      const { value_name, value_publisher, value_des } = this.createNFT;
      if (this.currentStep === 1) {
        //这里多判断还需要作品题材
        // if (value_name && value_publisher && value_des && this.$store.state.create.pickedList.length !== 0
        if (value_name && value_publisher && value_des
        ) {
          disabled = false;
        }
      } else if (this.currentStep === 2) {
        if (this.fileHash && this.fileName) {
          disabled = false;
        }
      } else if (this.currentStep === 3) {
        disabled = !(this.publish.count > 0);
      }
      return disabled;
    },
    categoryTypes2(): any[] {
      return this.categoryTypes.map((item: any) => {
        return {
          name: item.categoryName,
          value: item.id,
        };
      });
    },
    mySteps():Array<any>{
      return [
        {
          text: "基本信息",
        },
        {
          text: this.categoryId == '5'?'信息上链':"加密上链",
        },
        {
          text: "NFT发行",
        },
      ]
    }
  },
  methods: {
    ...mapMutations("create", {
      setState: "SET_STATE",
    }),
    getPreText():string{
      switch (this.categoryId) {
        case '1':
          return '剧本'
        case '2':
          return '视频'
        case '3':
          return '电影'
        case '4':
          return '音频'
        case '5':
          return '图片'
        case '6':
          return '衍生品'
        case '7':
          return '文件'
        default:
          return ''
      }
    },
    concatFormText(text: string){
       let obj ={
            nameText:`${text}名称`,
            namePlaceholder:`请填写${text}名称`,
            authorText:`${text}作者`,
            authorPlaceholder:`请填写${text}作者`,
            themeText:`${text}题材`,
            themePlaceholder:`请选择${text}题材`,
            desText:`${text}简介`,
            desPlaceholder:`请输入${text}简介，限500字`,
            fileUploadText:this.categoryId != '5'?`${text}HASH计算`:'图片上传',
            filePlaceholder:`请选择${text}文件`,
            fileHashText:`${text}HASH` 
       }
       return obj
    },
    setCreateNFT(obj: any) {
      this.createNFT = {
        ...this.createNFT,
        ...obj,
      };
    },
    alertPlatformSave() {
      Dialog.alert({
        title: "提示",
        message: `1、选择"加密上传"，附件将会加密存储到平台。没有您的授权，任何人无法查看；
          2、选择"不上传"，附件将不会上传平台，您可以私下发送给需要查看的用户；`,
      });
    },
    alertAuthorizeRead() {
      Dialog.alert({
        title: "提示",
        message: `1、选择作者授权阅读，${this.getPreText()}需要您本人授权后方可查看；
        2、选择无需授权，${this.getPreText()}可公开阅读。`,
      });
    },
    alertHashExplain(){
      Dialog.alert({
        title: '什么是文件HASH？',
        message: "通过算法可以计算出文件的HASH。当文件内容改动，HASH也会随之变化。文件HASH可以作为文件在区块链上的唯一数字身份。"
      })
    },
    alertCoverTip(){
      Dialog.alert({
        title: "提示",
        message: "封面将作为NFT的形象在大厅等位置进行展示，不上传封面则使用官方默认图进行展示。",
      }); 
    },
    addStep() {
      this.currentStep++;
    },
    stepOnFinished(e: boolean) {
      console.log(e, "finished");
    },
    stepOnChange(e: string) {
      console.log(e, "change");
    },
    getValue(val: string) {
      console.log(val);
    },
    what() {
      this.$router.push("/Nft/create/pick");
    },
    async publishNft() {
      this.loading4 = true;
      /**发行NFT */
      const result = this.$service.nftService.publish({
        fileHash: this.fileHash,
        id: this.publish.id,
        wallet: this.publish.wallet,
        nftId: this.publish.nftId,
      });
      /**发行成功后，获取证书 */
      result.then((ret: any) => {
          console.log(ret)
          const result2 = this.$service.nftService.getCertificate(ret)
          result2.then((res:any)=>{
            this.success = true;
            this.loading4 = false;
            // this.certificateData = Object.assign({},this.createNFT,this.publish,{nftName:res.name,nftHash:res.nftHash,nftPublisher:res.publisher,nftPublishTime:res.publishTime,qrUrl:window.location.href})
            this.certificateData = {
              nftName:res.name,
              nftHash:res.nftHash,
              nftPublisher:this.createNFT.value_publisher,
              // nftPublisher:res.publisher,
              nftPublishTime:res.publishTime,
              qrUrl:window.location.origin+'/Nft/'+res.nftHash}
          })
        })
        .catch((err) => {
          this.loading4 = false;
          this.success = false;
          this.errorMsg = err;
        });
    },

    async uploadFileToOss(file: File): Promise<string> {
      const ossRet = (await this.$service.nftService.ossPolicy()) as any;
      await this.$service.nftService.uploadFileToOss(file, ossRet);
      const { dir, host } = ossRet;
      return `${host}/${dir}${file.name}`;
    },

    /**上传NFT文件和保存NFT信息 */
    async encryptAndPushToChain() {
      this.loading2 = true;
      let data = {
        author: this.createNFT.value_publisher,
        categoryId: parseInt(this.categoryId) ,
        name: this.createNFT.value_name,
        synopsis: this.createNFT.value_des,
        fileHash: this.fileHash,
        // theme: this.pickedList.map((i: any) => i.text as string).toString(),//主题
      } as iSaveData;
      // if (this.createNFT.archives === 0) {
      //   data = {
      //     ...data,
      //     fileHash: this.fileHash,
      //     isArchives: this.createNFT.archives,
      //   };
      // } 
      // else if (this.createNFT.archives === 1) {
      //   //需要加密上传
      //   const fileUrl = await this.uploadFileToOss(this.file);
      //   data = {
      //     ...data,
      //     isArchives: this.createNFT.archives,
      //     fileHash: this.fileHash,
      //     fileUrl: fileUrl,
      //     fileName: this.file.name,
      //     isGrant: this.createNFT.grant,
      //   };
      // }
      //当NFT类型为图片时上传图片
      // if(this.categoryId == '5'){
      //   const imgUrl = await this.$service.nftService.fileUpload(this.file)
      //   data = {
      //     ...data,
      //     fileUrl: imgUrl,
      //     fileName: this.file.name,
      //   }
      // }
      //上传封面
      if(this.coverFile){
        const coverImgUrl = await this.$service.nftService.fileUpload(this.coverFile)
        data = {
          ...data,
          cover: coverImgUrl
        }
      }
      // else if(this.categoryId == '5'){
      //   data = {
      //     ...data,
      //     cover: data.fileUrl
      //   }
      // }
      
      /**保存NFT信息 */
      const { id, nftId, wallet, fileHash } = await this.$service.nftService.save(data);
      this.publish.fileHash = fileHash;
      this.publish.nftId = nftId;
      this.publish.id = id;
      this.publish.wallet = wallet;

      this.loading2 = false;
    },

    
    async currentStepChange(val: number) {
      try{
        if (this.currentStep === 2 && val === 1) {
          await this.encryptAndPushToChain();
        } else if (this.currentStep === 3 && val === 1) {
          let canPublish = false
          await Dialog.confirm({
            title:'发行须知',
            message: `1、发行的NFT存证作品，权利必须归本人（单位）所有，存证作品必须真实、合法。如有不实，需承担一切法律责任，<br>2、点击我已知晓，则视为已阅读并了解发行须知。`,
            confirmButtonText: "我已知晓",
          }).then(async ()=>{
            canPublish = true
          }).catch(()=>{
            return '取消'
          })
          if(canPublish){
            await this.publishNft()
          } else {
            return
          };
        }
      }catch(err){
        this.loading2 = false
        
        this.$toast('上传失败，请稍后再试~')
        return 
      }
      if (this.currentStep < this.mySteps.length + 1) {
        this.currentStep += val;
      }
    },

    clickRepublish() {
      this.currentStep = 1;
    },
  },
});
</script>
<style scoped>
.republishBtn {
  width: 100px;
  height: 34px;
  background: #0078ff;
  box-shadow: 0px 1px 6px 0px #252836;
  border-radius: 29px;
  line-height: 34px;
}
</style>