<template>
  <div class="pass_maker">
    <div class="maker_header">
      <div @click="goBack" class="back_btn">
        <Icon
          name="iconsuyuanxiangqing-fanhui"
          color="#1c2323"
          size="16px"
          class="icon-back"
        ></Icon>
        <span>创建数字资产</span>
      </div>
    </div>
    <div class="maker_content" ref="submit">
      <div class="content_header">创建数字资产</div>
      <div class="content_tip">
        支持视频、音频、图像、文件……支持各类型源文件上链
      </div>
      <div
        class="upload_layout"
        @click="initFileUpload"
        v-if="uploadStatus == UploadStatusType.INIT"
      >
        <img
          class="layout_icon"
          src="/images/newProductList/upload.png"
        />
        <div class="layout_status">上传源文件</div>
        <div class="layout_tip">
          源文件支持图片、文件、音频、视频、Word、Excel等…
        </div>
        <div class="layout_tip">文件大小不超过10M</div>
      </div>
      <div
        class="upload_process"
        v-if="fileData.name && uploadStatus != UploadStatusType.INIT"
      >
        <div class="process_info">
          <div class="process_img">
            <img
              v-if="
                ['mp3', 'wma', 'wav', 'amr', 'm4a'].includes(
                  uploadFileType(fileData.name)
                )
              "
              class="layout_icon"
              src="/images/newProductList/audio_icon.png"
            />
            <img
              v-else-if="
                [
                  'wmv',
                  'asf',
                  'asx',
                  'rm',
                  'rmvb',
                  'mpg',
                  'mpeg',
                  'mp4',
                  '3gp',
                  'mov',
                  'm4v',
                  'avi',
                  'mkv',
                  'flv',
                  'vob',
                ].includes(uploadFileType(fileData.name))
              "
              class="layout_icon"
              src="/images/newProductList/video_icon.png"
            />
            <img
              v-else-if="
                ['doc', 'docx'].includes(uploadFileType(fileData.name))
              "
              class="layout_icon"
              src="/images/newProductList/word_icon.png"
            />
            <img
              v-else-if="
                ['png', 'jpg', 'jpeg', 'gif'].includes(
                  uploadFileType(fileData.name)
                )
              "
              class="layout_icon"
              src="/images/newProductList/img_icon.png"
            />
            <img
              v-else-if="
                ['xls', 'xlsx'].includes(uploadFileType(fileData.name))
              "
              class="layout_icon"
              src="/images/newProductList/excel_icon.png"
            />
            <img
              v-else-if="['pdf'].includes(uploadFileType(fileData.name))"
              class="layout_icon"
              src="/images/newProductList/pdf_icon.png"
            />
            <img
              v-else-if="
                ['ppt', 'pptx'].includes(uploadFileType(fileData.name))
              "
              class="layout_icon"
              src="/images/newProductList/ppt_icon.png"
            />
            <img
              v-else-if="['txt'].includes(uploadFileType(fileData.name))"
              class="layout_icon"
              src="/images/newProductList/txt_icon.png"
              alt=""
            />
            <img
              v-else
              class="layout_icon"
              src="/images/newProductList/pass.png"
            />
          </div>
          <div class="process_content">
            <div class="content_info">
              <div class="file_name">{{ fileData.name }}</div>
              <div class="file_size">{{ mapFileSize(fileData.size) }}</div>
              <div class="process_text">已完成 {{ uploadProcessCount }} %</div>
            </div>
            <el-progress
              :percentage="uploadProcessCount"
              :show-text="false"
            ></el-progress>
          </div>
          <div class="process_icon">
            <img
              v-if="uploadStatus == UploadStatusType.LOADING"
              class="layout_icon"
              src="/images/newProductList/cancel.png"
            />
            <img
              v-if="uploadStatus == UploadStatusType.SUCCESS"
              class="layout_icon"
              src="/images/newProductList/success.png"
            />
            <img
              v-if="uploadStatus == UploadStatusType.FAIL"
              class="layout_icon"
              src="/images/newProductList/fail.png"
            />
          </div>
        </div>
      </div>
      <div class="chain_select">
        <div>
          <syRadio
            v-for="item in chainSelectAction"
            :key="item.value"
            :label="item.value"
            v-model="chainSelected"
            :disabled="item.disabled"
            >{{ item.text }}</syRadio
          >
        </div>
        <div
          class="delete_upload"
          v-if="uploadStatus == UploadStatusType.SUCCESS"
          @click="deleteUpload"
        >
          <img
            class="delete_icon"
            src="/images/newProductList/cancel.png"
          />
          <div class="tip_right">删除</div>
        </div>
      </div>
      <el-form
        :rules="rules"
        :model="formData"
        class="elForm"
        label-position="top"
      >
        <el-form-item label="资产名称" prop="name">
          <syDialogInput
            class="w-full"
            v-model:value="formData.name"
            placeholder="请输入资产名称"
          ></syDialogInput>
        </el-form-item>
        <el-form-item label="资产类型" prop="type">
          <sy-select v-model="formData.type" placeholder="请选择资产类型">
            <sy-option key="NFT" label="NFT" value="1"></sy-option>
          </sy-select>
        </el-form-item>
        <el-form-item label="资产数量" prop="amount">
          <syDialogInput
            class="w-full"
            type="number"
            :disabled="amountDisable"
            v-model:value.number="formData.amount"
            placeholder="请输入资产数量"
          ></syDialogInput>
        </el-form-item>
      </el-form>
      <br />
      <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">
            {{ 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>

    <input type="file" ref="fileUpload" hidden @change="onInputUpload" />
    <el-dialog
      title="关联溯源"
      v-model="dialogFormVisible"
      custom-class="category_dialog"
      @closed="clearProofList"
    >
      <div class="category_input_box">
        <div @click="searchByKeyWords">
          <Icon
            name="iconzuzhigoujia-chengyuanguanli-chaxunchengyuan"
            color="#1c2323"
            size="14px"
            class="search_icon"
          ></Icon>
        </div>
        <input
          class="category_input"
          type="text"
          placeholder="输入溯源名称"
          v-model="searchKeywords"
          @keydown.enter="searchByKeyWords"
        />
      </div>
      <div class="floderList">
        <ul
          v-if="proofList.length >= 1"
          class="infinite-list"
          v-infinite-scroll="pagechange"
          infinite-scroll-delay="100"
          style="overflow: auto"
        >
          <li
            v-for="i in proofList"
            class="infinite-list-item"
            @click="checkProof(i)"
          >
            {{ i.name }}
          </li>
        </ul>
        <div v-else class="search_empty">搜索无结果</div>
      </div>
    </el-dialog>
  </div>
</template>

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

let service = null as any;

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

const proofInfo = {
  id: "0",
  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;

export default defineComponent({
  name: "",
  components: {
    Icon: syIcon,
    ElRadio,
    ElForm,
    ElFormItem,
    ElInput,
    ElProgress,
    ElOption,
    ElButton,
    syButton,
    ElDialog,
    syBusinessForm,
    syDialogInput,
    sySelect,
    syOption,
    syRadio,
  },
  data() {
    return {
      uploadProcessCount: 0,
      UploadStatusType,
      uploadStatus: 1,
      fileData: {} as File,
      fee: 1,
      chainSelected: 1,
      chainSelectAction: [
        {
          value: 1,
          text: "Chain33",
          disabled: false,
        },
        {
          value: 2,
          text: "IPFS",
          disabled: true,
        },
      ],
      formData: {
        name: "",
        type: "",
        amount: "" as any,
      },
      rules: {
        name: [{ required: true, message: "请输入资产名称", trigger: "blur" }],
        type: [{ required: true, message: "请选择资产类型", trigger: "blur" }],
        amount: [
          { required: true, message: "请输入资产数量", trigger: "blur" },
        ],
        fileUpload: [{ required: false, message: "点击上传", trigger: "blur" }],
      },
      amountDisable: false,
      relationProof: {} as ProofInfoType,
      dialogFormVisible: false,
      proofList: [] as ProofInfoType[],
      page: 1,
      total: 0,
      searchKeywords: "",
      fileHash: "",
      fileUrl: "",
      inSubmit: false,
    };
  },
  computed: {
    disabled(): boolean {
      return (
        this.formData.name === "" ||
        this.formData.type === "" ||
        Number(this.formData.amount) <= 0 ||
        isNaN(Number(this.formData.amount)) ||
        this.formData.amount === ""
      );
      //    || !this.relationProof.id
    },
  },
  watch: {
    "formData.type": {
      handler(val) {
        if (Number(val) === 1) {
          this.formData = {
            ...this.formData,
            amount: 1,
          };
          this.amountDisable = true;
        } else {
          this.formData = {
            ...this.formData,
            amount: "",
          };
          this.amountDisable = false;
        }
      },
    },
    inSubmit(newV) {
      if (newV === true) {
        service = ElLoading.service({
          target: this.$refs.submit as HTMLElement,
        });
      } else {
        service.close();
      }
    },
  },
  methods: {
    /**删除溯源 */
    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 文件名
     */
    uploadFileType(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";
      }
    },
    /**
     * 触发文件上传
     */
    initFileUpload() {
      (this.$refs.fileUpload as HTMLInputElement).click();
    },
    /**
     * 文件上传后
     * @param e 事件对象
     */
    onInputUpload(e?: any) {
      if (e) {
        if (e.target.files[0].size > 10 * 1024 * 1024) {
          ElMessage.warning(`文件最大不能超过10M`);
          return;
        }
        if (
          ![
            "mp3",
            "wma",
            "wav",
            "amr",
            "m4a",
            "wmv",
            "asf",
            "asx",
            "rm",
            "rmvb",
            "mpg",
            "mpeg",
            "mp4",
            "3gp",
            "mov",
            "m4v",
            "avi",
            "mkv",
            "flv",
            "vob",
            "doc",
            "docx",
            "png",
            "jpg",
            "jpeg",
            "gif",
            "xls",
            "xlsx",
            "pdf",
            "ppt",
            "pptx",
            "txt",
          ].includes(this.uploadFileType(e.target.files[0].name))
        ) {
          ElMessage.warning(`不支持此类型文件上传`);
          return;
        }
        this.uploadProcessCount = 100;
        this.fileData = e.target.files[0];
        this.uploadStatus = UploadStatusType.LOADING;
        this.uploadStatus = UploadStatusType.SUCCESS;
        this.fee = this.feeCalcu(e.target.files[0].size);
        e.target.value = "";
      }
    },
    /**
     * 删除文件
     */
    deleteUpload() {
      this.fileData = {} as File;
      this.uploadStatus = this.UploadStatusType.INIT;
    },
    /**
     * 弹出溯源选择框
     */
    showCategory() {
      this.getCateGoryList(this.page, "");
      this.dialogFormVisible = true;
    },
    async getCateGoryList(page: number, key_words?: string) {
      const res = await $ajax({
        type: "post",
        url: GO_URLS.list,
        params: {
          is_valid: 0,
          page,
          page_size: 15,
          status: [2],
          key_words,
        },
      });
      if (res && res.data.results) {
        this.proofList = this.proofList.concat(res.data.results);
      }
    },
    /**
     * 关键词查找溯源
     */
    async searchByKeyWords() {
      this.page = 1;
      this.proofList = [];
      await this.getCateGoryList(this.page, this.searchKeywords);
    },
    pagechange() {
      this.page++;
      this.getCateGoryList(this.page, this.searchKeywords);
    },
    clearProofList() {
      this.searchKeywords = "";
      (this.page = 1), (this.proofList = []);
    },
    checkProof(proofInfo: ProofInfoType) {
      this.dialogFormVisible = false;
      this.relationProof = proofInfo;
    },
    /**
     * 最终提交
     */
    async submit() {
      if (this.inSubmit) return;
      this.inSubmit = true;
      /**如果有文件，则先文件上链 */
      if (this.fileData.name) {
        const fd = new FormData();
        fd.append("file_type", this.uploadFileType(this.fileData.name));
        fd.append("chain_type", this.chainSelected.toString());
        fd.append("file_data", this.fileData);
        const res = await $ajax({
          type: "post",
          url: GO_URLS.uploadChain,
          params: fd,
        });
        if (!res) {
          this.inSubmit = false;
          return;
        } else {
          this.fileUrl = res.data.url;
          this.fileHash = res.data.hash;
        }
      }
      /**文件上链成功后再创建数字资产 */
      const params = Object.assign(
        {},
        {
          type: Number(this.formData.type),
          name: this.formData.name,
          amount: this.formData.amount,
        },
        { proof_id: this.relationProof.id },
        { file_type: "", file_url: "" }
      );
      if (this.fileData.name) {
        params.file_type = this.uploadFileType(this.fileData.name);
        params.file_url = this.fileUrl;
      }
      const res = await $ajax({
        type: "post",
        url: GO_URLS.pass,
        params,
      });
      this.inSubmit = false;
      if (!res) return;
      this.$emit("update");
      ElMessage.success("创建数字资产成功");
      this.$emit("closePopup");
      this.inSubmit = false;
      this.$router.push("/passList");
    },
  },
});
</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: #353535;
    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;
    }
    .upload_layout {
      width: 100%;
      height: 158px;
      border: 1px dashed #e2e2e2;
      border-radius: 10px;
      color: #8b8b8b;
      text-align: center;
      background-color: #f7f7f7;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin-top: 20px;
      cursor: pointer;
      .layout_icon {
        margin-bottom: 5px;
      }
      .layout_status {
        color: var(--sy-blue);
        font-weight: bold;
        font-size: 14px;
        line-height: 20px;
        margin-bottom: 5px;
      }
      .layout_tip {
        transform: scale(0.9);
        font-size: 12px;
        line-height: 17px;
      }
    }
    .upload_process {
      margin: 20px 0 20px 0;
      .process_info {
        display: flex;
        align-items: center;
        padding: 15px 18px;
        box-shadow: 0px 2px 15px 0px #e7eef3;
        .process_img {
          img {
            width: 24px;
            height: 24px;
          }
        }
        .process_content {
          flex: 1;
          margin: 0 25px;
          .content_info {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            margin-bottom: 5px;
            color: #8b8b8b;
            .file_name {
              color: #353535;
              width: 33.3%;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
        }
      }
      .process_tip {
        margin-top: 10px;
        display: flex;
        justify-content: space-between;
        font-size: 12px;
      }
      .tip_fail {
        .tip_left {
          color: #ff4848;
        }
        .tip_right {
          color: var(--sy-blue);
          cursor: pointer;
        }
      }
    }
    .chain_select {
      display: flex;
      justify-content: space-between;
      margin: 15px 0 15px 0;
      .delete_upload {
        color: #8e8d8d;
        display: flex;
        align-items: center;
        font-size: 14px;
        cursor: pointer;
        .delete_icon {
          width: 17px;
          height: 17px;
          margin-right: 7px;
        }
      }
    }
    .category_add {
      .add_content {
        display: flex;
        align-items: center;
        margin-top: 8px;
        img {
          width: 30px;
          height: 30px;
          margin-right: 11px;
        }
        .relatived_text {
          color: #353535;
          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%;
  }
  :deep(.category_dialog) {
    width: 486px;
    background-color: #fff;
    .el-dialog__header {
      margin-right: 0;
      text-align: center;
      border: 1px solid #f0f1f5;
    }
    .category_input_box {
      position: relative;
      height: 30px;
      line-height: 30px;
      border-radius: 4px;
      background-color: #f7f9fb;
      .search_icon {
        position: absolute;
        left: 15px;
        cursor: pointer;
        top: 8px;
      }
      .category_input {
        box-sizing: border-box;
        height: 30px;
        line-height: 30px;
        font-size: 14px;
        width: 100%;
        border: none;
        outline: none;
        padding: 0 38px;
        border-radius: 4px;
        background-color: #f7f9fb;
      }
      input::-webkit-input-placeholder {
        color: #b9b9b9;
      }
    }
    .floderList {
      margin-top: 15px;
      .infinite-list {
        height: 300px;
        padding: 0 15px;
        list-style: none;
        .infinite-list-item {
          height: 30px;
          line-height: 30px;
          font-size: 14px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: normal;
          cursor: pointer;
          &:hover {
            background-color: #f7f9fb;
            color: var(--sy-blue);
          }
        }
      }
      .search_empty {
        box-sizing: border-box;
        height: 300px;
        padding-top: 10px;
        text-align: center;
        color: #c0c4cc;
      }
    }
  }
  :deep(.el-tree-node__label) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  :deep(.el-input) {
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      -webkit-appearance: none;
    }
    input[type="number"] {
      -moz-appearance: textfield;
    }
  }
}
</style>
