<template>
  <div class="pass_maker">
    <div class="maker_header">
      <div @click="goBack" class="back_btn">
        <Icon1
          iconName="iconsuyuanxiangqing-fanhui"
          color="#1c2323"
          size="16px"
          class="icon-back"
        ></Icon1>
        <span>发行藏品</span>
      </div>
    </div>
    <div class="maker_content" ref="submit">
      <div class="content_header">发行藏品</div>
      <syMenu
        v-model="activedMenu"
        :menu-list="menuList"
        style="margin-bottom: 15px"
      ></syMenu>

      <div style="margin-top: 26px"></div>
      <ElForm
        :rules="rules"
        :model="formData"
        class="elForm"
        ref="elFormRef"
        label-position="top"
      >
        <CustomizeFormItem prop="fileData">
          <UploadBoxFormControl
            :activedMenu="activedMenu"
            :fileData="formData.fileData"
            :clearCollectionMsg="clearCollectionMsg"
            @select-album="visibleOfAlbumDialog = true"
            @uploadCollection="
              ({ formData: fd }) => {
                formData = fd;
                uploadStatus = UploadStatusType.SUCCESS;
                fee = feeCalcu(fd.fileData.size);
                $nextTick(()=>{
                  ($refs as any).elFormRef.validateField('name');
                })
              }
            "
          ></UploadBoxFormControl>
        </CustomizeFormItem>
        <CustomizeFormItem
          label="藏品名称"
          prop="name"
          v-if="
            activedMenu ===
              eCollectionType.copyright + eCollectionType.derivatives &&
            formData.fileData &&
            formData.fileData.name
          "
        >
          <syDialogInput
            class="w-full"
            v-model:value="formData.name"
            @change=" ($refs as any).elFormRef.validateField('name');"
            :maxlength="30"
            placeholder="请输入藏品名称"
          ></syDialogInput>
        </CustomizeFormItem>
        <CustomizeFormItem
          label="发行类型"
          prop="type"
          v-if="formData && formData.fileData && formData.fileData.name"
        >
          <sy-select
            v-model="formData.type"
            @update:model-value="formData.amount = 1"
            placeholder="请选择资产类型"
            :disabled="
              activedMenu !==
              eCollectionType.copyright + eCollectionType.derivatives
            "
          >
            <sy-option
              v-if="
                activedMenu !==
                eCollectionType.copyright + eCollectionType.derivatives
              "
              key="NFT"
              label="NFT"
              value="1"
            ></sy-option>
            <sy-option
              v-if="
                activedMenu ===
                eCollectionType.copyright + eCollectionType.derivatives
              "
              key="版权"
              label="版权"
              value="1"
            ></sy-option>
            <sy-option
              v-if="
                activedMenu ===
                eCollectionType.copyright + eCollectionType.derivatives
              "
              key="衍生品"
              label="衍生品"
              value="2"
            ></sy-option>
          </sy-select>
        </CustomizeFormItem>
        <CustomizeFormItem
          label="发行数量"
          prop="amount"
          v-if="formData.fileData?.name"
        >
          <syDialogInput
            class="w-full"
            type="number"
            :disabled="
              activedMenu === eCollectionType.album || formData.type === '1'
            "
            :value="formData.amount"
            :max="10000"
            @update:value="
              (str) => {
                parseInt(str.replaceAll('.', '')) > 10000
                  ? (formData.amount = 10000)
                  : (formData.amount = str.replaceAll('.', ''));
              }
            "
            placeholder="请输入发行数量"
          ></syDialogInput>
        </CustomizeFormItem>
      </ElForm>
      <div class="category_add">
        <div class="add_title">关联溯源</div>
        <div class="add_content">
          <img src="/images/newProductList/pass.png" />
          <span v-if="relationProof.name" class="relatived_text">已关联</span>
          <span
            class="add_btn"
            @click="showCategory"
            v-show="!relationProof.name"
          >
            关联溯源
          </span>
          <span
            class="add_btn"
            @click="handleClickProof(relationProof.hash)"
            v-show="relationProof.name"
          >
            {{ relationProof.name }}
          </span>
          <Icon
            class="recycle"
            @click="showCategory"
            v-if="relationProof.name"
            name="icon-zhongchuan"
            color="#8E8D8D"
            size="12px"
          ></Icon>
          <span v-if="relationProof.name" @click="showCategory" class="re_add"
            >重新关联</span
          >
          <div v-if="relationProof.name" class="delete_add" @click="deleteAdd">
            <img
              class="delete_icon"
              src="/images/newProductList/cancel.png"
              alt=""
            />
            <div class="tip_right">删除</div>
          </div>
        </div>
      </div>
      <div style="width: 587px">
        <syButton
          mode="elementBtn"
          class="w-full"
          style="box-sizing: border-box; height: 40px; margin-top: 30px"
          @click="submit"
          type="primary"
          :disabled="disabled"
          >确定</syButton
        >
      </div>
      <!-- <div
        class="process_tip tip_success"
        v-if="uploadStatus == UploadStatusType.SUCCESS"
      >
        <div class="tip_right">
          预计扣除次数
          <span class="fee">{{ fee }}</span> 次
        </div>
      </div> -->
    </div>
    <DialogOfSelectAlbum
      v-model:visible="visibleOfAlbumDialog"
      @select="handleSelectAlbum"
    ></DialogOfSelectAlbum>
    <DialogOfRelatedProof
      v-model:visible="dialogFormVisible"
      :checkProof="checkProof"
    ></DialogOfRelatedProof>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import {
  GO_URLS,
  syIcon,
  syBusinessForm,
  syDialogInput,
  sySelect,
  syOption,
  syButton,
  syRadio,
  syCommonDialog,
  syMenu,
  openChainBrowser,
} from "cqk-sy-ui";
import {
  ElLoading,
  ElMessage,
  ElRadio,
  ElForm,
  ElFormItem,
  ElInput,
  ElProgress,
  ElOption,
  ElButton,
  ElDialog,
} from "element-plus";
import { $ajax } from "@/service";
import UploadBoxFormControl from "./UploadBoxFormControl/index.vue";

let service = null as any;

enum UploadStatusType {
  INIT = 1,
  LOADING,
  SUCCESS,
  FAIL,
}

const proofInfo = {
  id: "",
  user_id: 1,
  name: "name",
  hash: "hash",
  detail: "detail",
  note: "note",
  ext: "ext",
  increment_num: 1,
  status: 1,
  is_valid: 1,
  abandon_remark: "abandon_remark",
  proof_version: "proof_version",
  pass_hash: "pass_hash",
  pass_id: 1,
  create_time: 1609430400,
  update_time: 1609430400,
};
type ProofInfoType = typeof proofInfo;

import { eCollectionType } from "./types";
import Icon1 from "@/components/Icon/index.vue";
import CustomizeFormItem from "@/components/Form/CustomizeFormItem.vue";
import DialogOfSelectAlbum from "./DialogOfSelectAlbum/index.vue";
import DialogOfRelatedProof from "./DialogOfRelatedProof/index.vue";
import { matchChineseCharsNumbersEnglishAlphabets } from "@/utils/match";
import { URLS } from "@/service/URL";
import { globalState } from "@/store/state";

export default defineComponent({
  name: "",
  components: {
    Icon: syIcon,
    ElRadio,
    ElForm,
    ElFormItem,
    UploadBoxFormControl,
    ElInput,
    ElProgress,
    ElOption,
    ElButton,
    syButton,
    ElDialog,
    syBusinessForm,
    syCommonDialog,
    syDialogInput,
    sySelect,
    syOption,
    syRadio,
    syMenu,
    Icon1,
    CustomizeFormItem,
    DialogOfSelectAlbum,
    DialogOfRelatedProof,
  },
  data() {
    return {
      eCollectionType,
      activedMenu: eCollectionType.copyright + eCollectionType.derivatives,
      menuList: [
        {
          value: eCollectionType.copyright + eCollectionType.derivatives,
          label: "上传图片",
        },
        {
          value: eCollectionType.album,
          label: "关联专辑",
        },
      ],
      visibleOfAlbumDialog: false,
      uploadProcessCount: 0,
      UploadStatusType,
      uploadStatus: 1,
      fee: 1,
      chainSelected: 1,
      chainSelectAction: [
        {
          value: 1,
          text: "Chain33",
          disabled: false,
        },
        {
          value: 2,
          text: "IPFS",
          disabled: true,
        },
      ],
      categoryId: null as null | number,
      formData: {
        name: "",
        type: "",
        amount: "" as any,
        fileData: null as any,
      },
      rules: {
        name: [
          { required: true, message: "请输入藏品名称" },
          {
            max: 30,
            message: "请输入长度不大于30的藏品名称",
            trigger: "change",
          },
          {
            validator: (rule: any, value: string, cb: any) => {
              matchChineseCharsNumbersEnglishAlphabets(value)
                ? cb()
                : cb("藏品名称不支持特殊符号，请检查并重新输入");
            },
            trigger: "change",
          },
        ],
        type: [{ required: true, message: "请选择资产类型", trigger: "blur" }],
        amount: [
          { required: true, message: "请输入资产数量", trigger: "blur" },
        ],
        fileData: [
          {
            validator: (rule: any, value: any, callback: any) => {
              if (value) {
                callback && callback();
              } else {
                callback &&
                  callback(
                    (this as any).activedMenu ===
                      eCollectionType.copyright + eCollectionType.derivatives
                      ? "请上传藏品"
                      : "请选择专辑"
                  );
              }
            },
            trigger: "change",
          },
        ],
      },
      relationProof: {} as ProofInfoType,
      dialogFormVisible: false,
      proofList: [] as ProofInfoType[],
      page: 1,
      total: 0,
      searchKeywords: "",
      fileHash: "",
      fileUrl: "",
      inSubmit: false,
    };
  },
  computed: {
    disabled(): boolean {
      if (
        this.activedMenu ===
        eCollectionType.copyright + eCollectionType.derivatives
      ) {
        return (
          this.formData.name === "" ||
          this.formData.type === "" ||
          Number(this.formData.amount) <= 0 ||
          isNaN(Number(this.formData.amount)) ||
          this.formData.amount === ""
        );
      } else {
        return (
          this.formData.type === "" ||
          Number(this.formData.amount) <= 0 ||
          isNaN(Number(this.formData.amount)) ||
          this.formData.amount === ""
        );
      }
    },
  },
  watch: {
    activedMenu(newV) {
      this.clearCollectionMsg();
      (this.$refs as any).elFormRef.clearValidate();
    },
    inSubmit(newV) {
      if (newV === true) {
        service = ElLoading.service({
          target: this.$refs.submit as HTMLElement,
        });
      } else {
        service.close();
      }
    },
  },
  setup() {
    return {
      console: console,
    };
  },
  methods: {
    handleClickProof(hash: string) {
      openChainBrowser(hash, globalState.urlList.chain_browser_url);
    },
    async handleSelectAlbum(album: any) {
      this.categoryId = album.id;
      const res = await $ajax({
        url: URLS.category,
        type: "get",
        params: {
          id: album.id,
        },
      });
      if (!res) return;
      this.formData.fileData = {
        name: album.name,
      };
      this.formData.amount = res.data.total_file_count;
      this.formData.type = "1";
      this.uploadStatus = UploadStatusType.SUCCESS;
      this.fee = this.feeCalcu(1000 * 100);
    },
    clearCollectionMsg() {
      this.formData.amount = "0";
      this.formData.name = "";
      this.formData.type = "";
      this.formData.fileData = null;
      this.relationProof = {} as ProofInfoType;
      this.uploadStatus = UploadStatusType.INIT;
    },
    /**删除溯源 */
    deleteAdd() {
      this.relationProof = {} as ProofInfoType;
    },
    goBack() {
      history.go(-1);
    },
    /**
     * 根据文件大小计算费用fee
     * @param size 文件大小
     */
    feeCalcu(size: number) {
      return Math.ceil(size / (0.2 * 1024 * 1024)) + 1;
    },
    /**
     * 格式化文件名
     * @param text 文件名
     */
    getFileType(text: string): string {
      return text
        .slice(text.lastIndexOf(".") + 1, text.length + 1)
        .toLocaleLowerCase();
    },
    /**
     * 格式化文件大小单位
     * @param size 文件大小
     */
    mapFileSize(size: number): string {
      if (size / 1024 < 100) {
        return (size / 1024).toFixed(2) + "K";
      } else {
        return (size / 1024 / 1024).toFixed(2) + "M";
      }
    },
    /**
     * 弹出溯源选择框
     */
    showCategory() {
      this.dialogFormVisible = true;
    },
    checkProof(proofInfo: ProofInfoType) {
      this.dialogFormVisible = false;
      this.relationProof = proofInfo;
    },
    /**
     * 最终提交
     */
    async submit() {
      if (this.inSubmit) return;
      (this.$refs as any).elFormRef.validate(async (isValid: boolean) => {
        if (!isValid) return;
        this.inSubmit = true;

        if (
          this.activedMenu ===
          eCollectionType.copyright + eCollectionType.derivatives
        ) {
          /**如果有文件，则先文件上链 */
          if (this.formData.fileData.name) {
            const fd = new FormData();
            fd.append(
              "file_type",
              this.getFileType(this.formData.fileData.name)
            );
            fd.append("chain_type", this.chainSelected.toString());
            fd.append("file_data", this.formData.fileData);
            const res = await $ajax({
              type: "post",
              url: GO_URLS.upload,
              params: fd,
            });
            if (!res) {
              this.inSubmit = false;
              return;
            } else {
              this.fileUrl = res.data.url;
              this.fileHash = res.data.hash;
            }
          }
          /**文件上链成功后再创建数字资产 */
          if (this.formData.type === "1") {
            const params = {
              type: Number(this.formData.type),
              name: this.formData.name,
              amount: this.formData.amount,
              proof_id: this.relationProof.id,
              file_type: "",
              file_url: "",
            };
            if (this.formData.fileData.name) {
              params.file_type = this.getFileType(this.formData.fileData.name);
              params.file_url = this.fileUrl;
            }
            const res = await $ajax({
              type: "post",
              url: GO_URLS.pass,
              params,
            });
            this.inSubmit = false;
            if (!res) return;
          } else if (this.formData.type === "2") {
            const res = await $ajax({
              type: "post",
              url: URLS.derivative,
              params: {
                proof_id: this.relationProof.id,
                name: this.formData.name,
                amount: Number(this.formData.amount),
                file_hash: this.fileHash,
              },
            });
            this.inSubmit = false;
            if (!res) return;
          }
        } else if (this.activedMenu === eCollectionType.album) {
          const res = await $ajax({
            url: URLS.batch,
            type: "post",
            params: {
              proof_id: this.relationProof.id,
              name: this.formData.fileData.name,
              amount: this.formData.amount,
              file_category_id: this.categoryId,
            },
          });
          this.inSubmit = false;
          if (!res) return;
        }
        this.$emit("update");
        ElMessage.success("创建数字资产成功");
        this.$emit("closePopup");
        this.inSubmit = false;
        this.$router.push("/collectionManagement");
      });
    },
  },
});
</script>
<style></style>

<style scoped lang="scss">
* {
  box-sizing: content-box;
}

.pass_maker {
  :deep(.el-input__inner) {
    height: 40px;
  }

  .maker_header {
    display: flex;
    align-items: center;
    height: 50px;
    background-color: #ffffff;
    border: 1px solid #efefef;
    color: var(--sy-black);
    font-size: 16px;
    padding: 0 47px;
    .back_btn {
      display: flex;
      align-items: center;
      cursor: pointer;
      .icon-back {
        margin-right: 24px;
      }
    }
  }
  .maker_content {
    min-height: calc(100vh - 50px);
    width: 587px;
    margin: 0 auto;
    padding: 37px 0 50px 0;
    .content_header {
      color: #292929;
      font-size: 22px;
    }
    .content_tip {
      color: #8b8b8b;
      font-size: 12px;
      margin-top: 2px;
    }
    .category_add {
      .add_content {
        display: flex;
        align-items: center;
        margin-top: 8px;
        img {
          width: 30px;
          height: 30px;
          margin-right: 11px;
        }
        .relatived_text {
          color: var(--sy-black);
          font-size: 14px;
          margin-right: 11px;
        }
        .add_btn {
          color: var(--sy-blue);
          font-size: 14px;
          cursor: pointer;
        }
        .recycle {
          margin-left: 10px;
        }
        .re_add {
          color: #8e8d8d;
          font-size: 12px;
          margin-left: 2px;
          cursor: pointer;
        }
        .delete_add {
          margin-left: auto;
          display: flex;
          align-items: center;
          color: #8e8d8d;
          font-size: 14px;
          cursor: pointer;
          img {
            width: 14px;
            height: 14px;
            margin-right: 4px;
          }
        }
      }
    }

    .tip_success {
      margin-top: 13px;
      color: #1c2323;
      font-size: 12px;
      text-align: center;
      .fee {
        color: #f6ad00;
        font-size: 16px;
      }
    }
  }
  :deep(.el-select) {
    width: 100%;
  }
}
</style>
