import { mapState } from "vuex";
import {
  Drawer as MegaDrawer,
  Uploader as MegaUploader,
  Icon,
} from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  name: "MomDrawerUploader",
  components: { Icon },
  props: {
    objectName: String,
  },
  data() {
    return {
      drawerVisible: false,
      typeOptions: [],
      form: {
        objectName: "",
        fileName: "",
      },
      options: {
        target: `${ApiConstant.PREFIX_CORE}/api/sys/file/upload/chunk`,
        headers: {
          Authorization: this.$auth.getToken("local"),
          tenantId:
            this.$store.state.app.systemConfig.TENANT_OPEN === "true"
              ? this.$store.state.account.tenantId
              : "",
        },
        testChunks: true,
        chunkSize: 10 * 1024 * 1024,
        singleFile: true,
        showUploadList: true,
      },
      fileFormData: null,
      fileList: [],

      timer: null,
      cycleData: null,
      loading: false,
    };
  },
  computed: {
    ...mapState({
      locale: (state) => state.app.locale,
    }),
    rules() {
      return {
        objectName: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        fileName: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
      };
    },
  },
  created() {
    this.getDictByCode(`DIC:CORE:DATA_IMPORT_TYPE`).then((res) => {
      this.typeOptions = res.data.data;
    });
  },
  methods: {
    handleImport() {
      if (this.objectName) {
        this.form.objectName = this.objectName;
      }
      this.drawerVisible = true;
    },
    handleImportCancel() {
      this.$refs.upload?.sFileList.forEach((file) => {
        this.$refs.upload.handleRemove(file);
      });
      this.$refs.upload?.uploader.fileList.forEach((file) => {
        file.cancel();
      });
      this.drawerVisible = false;
      this.fileList = [];
    },
    uploadChange(file) {
      this.form.fileName = file.name;
      this.fileFormData = file;

      this.$refs.importDrawerForm.validateField("fileName");
    },
    objectNameChange(val) {
      this.form.objectName = val;
    },
    handleImportSave() {
      this.$refs.importDrawerForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/file/merge-chunks/${this.fileFormData.name}/${this.fileFormData.size}`
            )
            .then((res) => {
              this.$axios
                .post(`${ApiConstant.PREFIX_CORE}/api/data-import`, {
                  objectName: this.form.objectName,
                  fileCode: res.data.data.fileCode,
                  fileUrl: res.data.data.fileUrl,
                  language: this.locale || "zh_CN",
                })
                .then((dataImportRes) => {
                  this.cycleData = null;
                  this.handleCycle(dataImportRes.data.data).then((r) => {
                    this.loading = false;
                    this.handleImportCancel();

                    this.$emit("cycleComplete", r);
                  });
                });
            });
        }
      });
    },
    handleCycle(id) {
      return new Promise((resolve, reject) => {
        this.timer = setInterval(async () => {
          if (["EXCEPTION", "SUCCESS"].includes(this.cycleData?.status)) {
            clearInterval(this.timer);
            resolve(this.cycleData);
          } else {
            try {
              const res = await this.$axios.get(
                `${ApiConstant.PREFIX_CORE}/api/data-import/get-status/${id}`
              );
              this.cycleData = res.data.data;
            } catch (_err) {}
          }
        }, 2000);
      });
    },
    renderButton() {
      return (
        <a-button>
          <a-icon type="cloud-upload" />
          {this.$t("UPLOAD")}
        </a-button>
      );
    },
  },
  render() {
    const formModelProps = {
      props: {
        model: this.form,
        rules: this.rules,
      },
    };

    const defaultButton = this.$scopedSlots.default
      ? this.$scopedSlots.default()
      : this.renderButton();
    return (
      <span>
        <span onClick={this.handleImport}>{defaultButton}</span>
        <MegaDrawer
          width="520"
          wrapClassName="uploader-drawer"
          title={this.$t("UPLOAD")}
          visible={this.drawerVisible}
          maskClosable={false}
          onClose={this.handleImportCancel}
          onCancel={this.handleImportCancel}
          onOk={this.handleImportSave}>
          <div slot="main">
            <a-form-model {...formModelProps} ref="importDrawerForm">
              <a-form-model-item
                label={this.$t("TYPE")}
                prop="objectName"
                key="objectName">
                <a-select
                  value={this.form.objectName}
                  filterable={true}
                  allowClear={true}
                  disabled={!!this.objectName}
                  placeholder={this.$t("PLACESELECT")}
                  onChange={this.objectNameChange}>
                  {this.typeOptions.map((item) => {
                    return (
                      <a-select-option key={item.value} value={item.value}>
                        {item.label}
                      </a-select-option>
                    );
                  })}
                </a-select>
              </a-form-model-item>
              <a-form-model-item
                label={this.$t("DATA_FILE")}
                prop="fileName"
                key="fileName">
                <a-input value={this.form.fileName} style="display:none" />
                <MegaUploader
                  ref="upload"
                  options={this.options}
                  onFileSuccess={this.uploadChange}>
                  <a-button>
                    <Icon type="icon-dir-f-download" size={16}></Icon>
                    <span>{this.$t("UPLOAD") + this.$t("FILE")}</span>
                  </a-button>
                  <div style="color: #666;font-size:12px">
                    {this.$t("UPLOAD_ONLY")}500kb
                  </div>
                </MegaUploader>
              </a-form-model-item>
            </a-form-model>
            <div
              class="db-parsing"
              style={{ display: this.loading ? "block" : "none" }}>
              <div class="db-parsing-loading">
                <svg-icon
                  icon-class="loading"
                  class="db-parsing-loading-icon"
                />
                <br />
                <span class="db-parsing-loading-text">
                  {this.$t("LOADING")}
                </span>
              </div>
            </div>
          </div>
        </MegaDrawer>
      </span>
    );
  },
};
