<template>
  <Layout-Child class="page-scroll pb-32">
    <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 text-zx-blue-white">
      <div id="step_box" class=" step-one " v-if="currentStep == 1">
        <div class=" text-zx-blue-light text-2xl p-3">
          发行NFT
        </div>
        <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="5"
            class="
              w-full
               bg-white
              text-zx-blue-light
              p-3
              rounded-md
              text-sm
               mb-3
            "
          ></textarea>
        </div>

        <upload-img :fileList="fileList" :maxCount='9' @fileChange="fileChange" @deleteImg="deleteImg"></upload-img>

        <app-cell
          v-model="createNFT.value_name"
          type="input"
          :text='fromText.nameText'
          :validate="{ maxLen: 15 }"
          :placeholder="fromText.namePlaceholder"
          class=" my-3 text-sm "
          @cellOnChange="(v) => setCreateNFT({ value_name: v })"
        ></app-cell>

        <app-cell
          v-model="createNFT.value_publisher"
          type="input"
          :text="fromText.authorText"
          :validate="{ maxLen: 15 }"
          :placeholder="fromText.authorPlaceholder"
          class=" my-3 text-sm "
          @cellOnChange="(v) => setCreateNFT({ value_publisher: v })"
        ></app-cell>

        <app-cell
          type="pick"
          :text="fromText.themeText"
          :placeholder="fromText.themePlaceholder"
          class=" my-3 "
          @click.native="$router.push({name:'NftPick',query:{text:`艺术品题材`,id:categoryId}})"
        ></app-cell>

        <div class="fixed bottom-3 w-full left-0 z-30">
          <app-btn
            text="下一步"
            class="w-11/12 mx-auto text-font-white bg-zx-blue-light"
            :disabled="validation"
            border="none"
            @btnClicked="currentStepChange(1)"
            :loading="loading2"
          ></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
          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>
        <app-cell
          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=" text-zx-blue-light text-2xl p-3">
          NFT信息确认
        </div>

        <app-cell
          text="编号"
          boxType="border"
          :value="constNFTId"
          class=" my-3 text-sm"
        ></app-cell>
        <app-cell
          text="发行人地址"
          :name="publisher.wallet"
          boxType="border"
          type="showText"
          :needCopy="true"
          class=" "
        ></app-cell>
        <app-cell
          text="发行人"
          boxType="border"
          :value="publisher.nickname"
          class=" my-3 text-sm"
        ></app-cell>
        <app-cell
          text="手续费"
          boxType="border"
          :value="'限时免费'"
          class=" my-3 text-sm"
        ></app-cell>
        <app-cell
          text="数量"
          boxType="border"
          :value="1"
          class=" my-3 text-sm"
        ></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 bg-zx-blue-light"
            border="none"
            @btnClicked="currentStepChange(-1)"
          ></app-btn>
          <app-btn
            text="发行NFT"
            class="w-5/12 mx-auto text-font-white bg-zx-blue-light"
            :disabled="false"
            
            border="none"
            @btnClicked="currentStepChange(1)"
          ></app-btn>
        </div>
      </div>

      <div class="step-three" v-if="currentStep == 3">
          <div>
            <van-circle v-model="uploadRate" :rate="uploadTo" :speed="50" :text="'LODING'" class="uploadCircle" color="#2b446c" stroke-width="20" stroke-linecap="round"></van-circle>
          </div>
          <div class=" text-zx-blue-light text-center mt-5">NFT正在发行中~</div>


        <!-- <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-zx-blue-light"
            border="none"
            @btnClicked="currentStepChange(-1)"
          ></app-btn>
          <app-btn
            text="发行NFT"
            class="w-5/12 mx-auto text-font-white rounded-2xl bg-zx-blue-light"
            border="none"
            :disabled="validation"
            :loading="loading3"
            @btnClicked="currentStepChange(1)"
          ></app-btn>
        </div> -->
      </div>

      <div v-if="currentStep == 4" class=" text-zx-blue-light">
        <div v-if="success" class=" text-center mt-12">
          <img src="@/assets/img/publishSuccess.png" alt="">
          <div class=" mt-4">恭喜您，您的NFT发行成功啦！</div>
          <div class=" text-zx-blue-white mt-6 w-10/12 mx-auto">请到我的NFT中绑定艺术品溯源码，关联您的艺术品的溯源信息。</div>
          <app-btn text="立即绑定" class="w-11/12 mx-auto text-font-white bg-zx-blue-light" border="none" @btnClicked="rePublish()"></app-btn>
        </div>
        <div v-else class=" text-center mt-12">
          <img src="@/assets/img/publishFail.png" alt="">
          <div class=" mt-4">抱歉，NFT发行失败！</div>
          <div class=" text-app-red mt-6 w-10/12 mx-auto">失败原因：{{errorMsg}}</div>
          <app-btn text="重新发行" class="w-11/12 mx-auto text-font-white bg-zx-blue-light mt-4" border="none" @btnClicked="rePublish()"></app-btn>
        </div>
        <!-- <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>
              <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 { Circle } from 'vant'
// import { Dialog } from "vant";
import Vue from "vue";
import { mapMutations, mapState } from "vuex";
Vue.use(Overlay)
Vue.use(Circle)
export default Vue.extend({
  data() {
    return {
      a: "",
      createNFT: {
        value_name: this.$store.state.create.tempData.name?this.$store.state.create.tempData.name:'',
        value_publisher: this.$store.state.create.tempData.author?this.$store.state.create.tempData.author:'',
        value_des: this.$store.state.create.tempData.synopsis?this.$store.state.create.tempData.synopsis:'',
        categoryType: NaN,
        // archives: 1,
        // grant: 1,
      },
      fromText:{
        nameText:'',
        namePlaceholder:'',
        authorText:'',
        authorPlaceholder:'',
        themeText:'',
        themePlaceholder:'',
        desText:'',
        desPlaceholder:'',
        fileUploadText:'',
        filePlaceholder:'',
        fileHashText:''
      },
      publish: {
        nftId: "",
        id: NaN,
        fileHash: "",
        wallet: "",
        count: 1,
      },
      categoryTypes: [] as any[],
      currentStep: 1,
      categoryId:(this.$route.query.id as string)?(this.$route.query.id as string):'1',
      showOverlay:true,
      loading2: false,
      loading3: false,
      loading4: false,
      success: true,
      errorMsg: "",
      // certificateData:{},
      fileList:this.$store.state.create.tempData.fileList?this.$store.state.create.tempData.fileList:[],
      urlList:[] as Array<any>,
      uploadRate: 0,
      uploadTo: 0,
      // mySteps: [
      //   {
      //     text: "基本信息",
      //   },
      //   {
      //     text: "加密上链",
      //   },
      //   {
      //     text: "NFT发行",
      //   },
      // ],
      // archivesList: [
      //   { value: 0, name: "不上传" },
      //   { value: 1, name: "加密上传" },
      // ],
      // grantList: [
      //   { value: 0, name: "不需要授权" },
      //   { value: 1, name: "需要授权" },
      // ],
    };
  },
  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
    'uploadImg': ()=>import('./components/uploadImg/uploadImg.vue'),

  },
  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,
      tempData: {}
    });
  },
  computed: {
    ...mapState("create", {
      fileHash: "fileHash",
      fileName: "fileName",
      file: "file",
      pickedList: "pickedList",
      coverName: 'coverName',
      coverFile: "coverFile",
      tempData: "tempData"
    }),
    constNFTId():string{
      return this.$store.state.create.tempData.nftNum?this.$store.state.create.tempData.nftNum:Number(new Date()).toString().substr(0,10)+Math.floor(Math.random()*10000+1000).toString()
    },
    //判断按钮可用性
    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 &&
          this.fileList.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;
    },
    publisher():any{
      return JSON.parse(window.localStorage.getItem('KEY_USER') as string)
    }

  },
  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 '衍生品'
        default:
          return ''
      }
    },
    concatFormText(text: string){
       let obj ={
            nameText:`${text}名称`,
            namePlaceholder:`请输入${text}名字，限15字`,
            authorText:`${text}作者`,
            authorPlaceholder:`请输入${text}名称`,
            themeText:`${text}类型`,
            themePlaceholder:`请选择${text}类型`,
            desText:`${text}简介`,
            desPlaceholder:`请输入${text}简介，限500字`,
            fileUploadText:`${text}HASH计算`,
            filePlaceholder:`请选择${text}文件`,
            fileHashText:`${text}HASH` 
       }
       return obj
    },
    setCreateNFT(obj: any) {
      this.createNFT = {
        ...this.createNFT,
        ...obj,
      };
    },
    //新增图片，最多9张
    fileChange(files:any){
      (this.fileList as any).push(...files)
      if(this.fileList.length > 9){
        const list = this.fileList.slice(-9)
        this.fileList = list
      }
    },
    //删除图片
    async deleteImg(index:number){
      //删除oss上的文件
      if(this.fileList[index].fileUrl){
        await this.$service.nftService.deleteOssFile({
          url:this.fileList[index].fileUrl
        })
      }
      this.fileList.splice(index,1)
    },
    
    async currentStepChange(val: number) {
      try{
        if (this.currentStep == 1 && val == 1) {
          // 获取NFTID
          this.currentStep += val;
        }else if(this.currentStep == 2 && val == 1){
          this.currentStep += val;
          await this.encryptAndPushToChain()
          console.log('发布')
        }else if( val == -1){
          this.currentStep += val;
          console.log('上一步')
        }
        
      }catch(err){
        this.loading2 = false
      }
    },

    //传文件
    async encryptAndPushToChain() {
      try {
        await this.uploadFileToOss(this.fileList);//上传文件
        await this.publishNft()//发行NFT
      } catch (err) {
        this.$toast('发行失败，请稍后重试~')
        return Promise.reject(err)
      }
    },

    //传文件
    async uploadFileToOss(fileList: any) {
      try{
        const ossRet = (await this.$service.nftService.ossPolicy()) as any;//获取签名
        const { dir, host } = ossRet;
        for(let item of fileList) {//循环上传并把文件对象推到urlList中,缓存的文件就不上传了
          if(!item.fileUrl) {
            await this.$service.nftService.uploadFileToOss(item, ossRet);//上传文件
            this.urlList.push({
              fileHash: await this.$util.hashComputed(item),
              fileName: item.name,
              fileUrl: `${host}/${dir}${item.name}`
            })         
          }else {
            this.urlList.push({
              fileHash: item.fileHash,
              fileName: item.fileName,
              fileUrl: item.fileUrl
            })   
          }

          this.uploadTo = this.uploadTo + 100/fileList.length 
        }
        return this.urlList
      }catch(err){
        return Promise.reject(err)
      }
    },

    //发行
    async publishNft() {
        let data = {
          author: this.createNFT.value_publisher,
          name: this.createNFT.value_name,
          synopsis: this.createNFT.value_des,
          nftNum: this.constNFTId,
          categoryId: this.pickedList[0].pid ,
          secondCategoryId: this.pickedList[0].id,
          fileList: this.urlList,
          publishCount:1,
        } as iSaveData;
        const result = await this.$service.nftService.publish(data) as any;
        if(result.code == 200) {
            this.currentStep += 1;
            this.success = true;
        }else {
            this.currentStep += 1;
            this.success = false;
            this.errorMsg = result.message;
        }
        this.uploadRate = 0
        this.uploadTo = 0
        this.urlList = []
    },

    rePublish() {
      this.currentStep = 1;
    },













    // 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");
    // },

  },
});
</script>
<style scoped lang="less">
.republishBtn {
  width: 100px;
  height: 34px;
  background: #0078ff;
  box-shadow: 0px 1px 6px 0px #252836;
  border-radius: 29px;
  line-height: 34px;
}
.uploadCircle {
  left: 50%;
  transform: translateX(-50%);
  margin-top: 130px;
}

</style>