<template>
  <Layout-Child class="page-scroll">
    <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: 20 }"
          :placeholder="fromText.namePlaceholder"
          class="text-font-white my-3"
          @cellOnChange="(v) => setCreateNFT({ value_name: v })"
        ></app-cell>
        <app-cell
          v-model="createNFT.value_publisher"
          type="input"
          :text="fromText.authorText"
          :validate="{ maxLen: 20 }"
          :placeholder="fromText.authorPlaceholder"
          class="text-font-white my-3"
          @cellOnChange="(v) => setCreateNFT({ value_publisher: v })"
        ></app-cell>
        <app-cell
          :pickValue="mySteps"
          type="pick"
          :text="fromText.themeText"
          :placeholder="fromText.themePlaceholder"
          class="text-font-white my-3"
          @click.native="$router.push('/Nft/create/pick')"
        ></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="10"
            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
            "
            @input="textareaChange"
          ></textarea>
        </div>
        <div class="fixed bottom-0 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"
          type="upload"
          :placeholder="fromText.filePlaceholder"
          :name="fileName"
          @cellOnChange="$router.push({ name: 'NftUpload',params:{type:getPreText()}})"
        ></app-cell>
        <app-cell
          text="封面上传(非必填)"
          class="text-font-white my-3 "
          type="upload"
          placeholder="请上传相关封面"
          :name="coverName"
          @cellOnChange="$router.push({ name: 'NftUpload',params:{type:'封面图片'}})"
        ></app-cell>
        <app-cell
          :text="fromText.fileHashText"
          class="text-font-white my-3"
          type="showText"
          :name="fileHash"
          @cellOnChange="getValue"
        ></app-cell>
        <app-cell
          text="平台存档"
          type="select"
          :selected="createNFT.archives"
          labelIcon="icon-wenhao"
          @clickIcon="alertPlatformSave"
          :list="archivesList"
          class="text-font-white my-3"
          @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"
          @cellOnChange="(v) => (createNFT.grant = v)"
        ></app-cell>
        <div class="fixed bottom-0 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 break-all"
        ></app-cell>
        <app-cell
          :text="fromText.fileHashText"
          type="showText"
          :name="publish.fileHash"
          class="text-font-white my-3"
          @cellOnChange="getValue"
        ></app-cell>
        <app-cell
          text="发行人地址"
          type="showText"
          :name="publish.wallet"
          class="text-font-white my-3"
          @cellOnChange="getValue"
        ></app-cell>
        <app-cell
          key="count"
          text="数量"
          :value="1"
          :disabled="true"
          type="input-num"
          class="text-font-white my-3"
          @cellOnChange="
            (v) => {
              publish.count = v;
            }
          "
        ></app-cell>
        <div class="fixed bottom-0 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>

        <div v-else class="text-center">
          <div v-if="success" >
              <van-overlay :show="showOverlay"  class=" full-height flex items-center z-50" >
                <div class="w-10/12 mx-auto">
                  <certificate :certificateData="certificateData"/>
                  <img
                    @click='showOverlay = !showOverlay;'
                    src="@/assets/icons/close_publish.png"
                    class="w-4 xs:w-6 mx-auto mt-3"
                  />
                </div>
    
              </van-overlay>
              <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: "",
        value_picker: [],
        value_des: "",
        archives: 0,
        grant: 0,
        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[],
      mySteps: [
        {
          text: "基本信息",
        },
        {
          text: "加密上链",
        },
        {
          text: "NFT发行",
        },
      ],
      currentStep: 1,
      categoryId:this.$route.query.id as string,
      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"),
    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: ''
    });
  },
  computed: {
    ...mapState("create", {
      fileHash: "fileHash",
      fileName: "fileName",
      file: "file",
      pickedList: "pickedList",
      coverName: 'coverName'
    }),
    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
        ) {
          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,
        };
      });
    },
  },
  methods: {
    ...mapMutations("create", {
      setState: "SET_STATE",
    }),
    getPreText():string{
      switch (this.categoryId) {
        case '1':
          return '剧本'
        case '2':
          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:`请填写${text}名称`,
            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、选择作者授权阅读，剧本需要您本人授权后方可查看；
        2、选择无需授权，剧本可公开阅读。`,
      });
    },
    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() {
      try {
        this.loading4 = true;
        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) => {
            this.success = ret === true;
            this.loading4 = false;
            this.certificateData = Object.assign({},this.createNFT,this.publish)
            ret !== true && (this.errorMsg = ret);
          })
          .catch((err) => {
            this.loading4 = false;
            this.success = false;
            this.errorMsg = err;
          });
      } catch (err) {
        console.log(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}`;
    },
    async encryptAndPushToChain() {
      this.loading2 = true;
      let mistake = false;
      try {
        let data = {
          author: this.createNFT.value_publisher,
          categoryId: parseInt(this.categoryId) ,
          name: this.createNFT.value_name,
          synopsis: this.createNFT.value_des,
          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,
          };
        }

        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;
      } catch (err) {
        mistake = true;
      }
      this.loading2 = false;
      if (mistake) return;
    },
    async currentStepChange(val: number) {
      if (this.currentStep === 2 && val === 1) {
        await this.encryptAndPushToChain();
      } else if (this.currentStep === 3 && val === 1) {
        await this.publishNft();
      }
      if (this.currentStep < this.mySteps.length + 1) {
        this.currentStep += val;
      }
    },
    clickRepublish() {
      this.currentStep = 1;
    },
    textareaChange(e:any){
      if(e.target.value.length >= 500) {
        this.createNFT.value_des = e.target.value.slice(0,500)
      }
    }
  },
});
</script>
<style scoped>
.republishBtn {
  width: 100px;
  height: 34px;
  background: #0078ff;
  box-shadow: 0px 1px 6px 0px #252836;
  border-radius: 29px;
  line-height: 34px;
}
</style>