<!--数据源-->
<template>
  <div class="data-source-page">
    <MomTable
      ref="MomTable"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :page.sync="page"
      :query-param-item="queryFormItem"
      :mega-extend="{ rowAction: false }"
      row-key="id"
      :total="total"
      @search="searchPageData"
    >
      <template slot="objectName" slot-scope="text, record">
        <span>{{ formatData(typeOptions, record.objectName) }}</span>
      </template>
      <template slot="status" slot-scope="text, record">
        <span>{{ formatData(statusOptions, record.status) }}</span>
      </template>
      <template slot="resultFileUrl" slot-scope="text, record">
        <span
          ><a :href="record.resultFileUrl">{{ record.resultFileUrl }}</a></span
        >
      </template>
      <div slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('DATA_IMPORT:ADD')"
          icon="plus"
          @click="handleAdd"
        >
          {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('DATA_IMPORT:DOWNLOAD_TEMPLATE')"
          @click="templateVisible = true"
        >
          <Icon type="icon-cur-cloud-download" style="color: #666" :size="16" />
          {{ $t("DOWNLOAD_TEMPLATE") }}
        </a-button>
        <a-button
          v-if="hasAuth('DATA_IMPORT:REFRESH_DICTIONARY')"
          @click="handleRefreshDictionary"
        >
          <i class="el-icon-refresh icon-defult"></i>
          {{ $t("REFRESH_CACHE_DICTIONARY") }}
        </a-button>
        <a-button
          v-if="hasAuth('DATA_IMPORT:REFRESH_I18N')"
          @click="handleRefreshI18n"
        >
          <i class="el-icon-refresh icon-defult"></i>
          {{ $t("REFRESH_CACHE_I18N") }}
        </a-button>
      </div>
    </MomTable>
    <MegaDrawer
      :visible.sync="drawerVisible"
      :title="$t('ADD')"
      width="520"
      @close="drawerVisible = false"
    >
      <a-form-model
        slot="main"
        ref="dataSource"
        layout="vertical"
        :model="form"
        :rules="rules"
        label-width="110px"
      >
        <a-form-model-item :label="$t('TYPE')" prop="objectName">
          <a-select
            v-model="form.objectName"
            allow-clear
            show-search
            :placeholder="$t('PLACESELECT')"
          >
            <a-select-option
              v-for="item in typeOptions"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
        <a-form-model-item :label="$t('DATA_FILE')" prop="fileName">
          <a-input v-model="form.fileName" style="display: none"></a-input>
          <Uploader ref="upload" :options="options" @fileSuccess="uploadChange">
            <a-button size="small" type="primary">
              {{ $t("UPLOAD") }}
            </a-button>
            <span style="color: #666; font-size: 12px"
              >{{ $t("UPLOAD_ONLY") }}500kb</span
            >
          </Uploader>
        </a-form-model-item>
      </a-form-model>
      <div slot="footer" class="drawer-footer">
        <a-button type="primary" @click="save">
          <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
        </a-button>
        <a-button @click="close">
          <Icon type="icon-dir-f-rollback" :size="18" /> {{ $t("CANCEL") }}
        </a-button>
      </div>
    </MegaDrawer>
    <Modal
      :visible="templateVisible"
      :title="$t('DOWNLOAD')"
      :footer="null"
      @cancel="templateVisible = false"
    >
      <a-form-model
        ref="downloadTemplateForm"
        :model="downloadTemplateForm"
        :rules="downloadTemplateRules"
        inline
      >
        <a-form-model-item
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 16 }"
          :label="$t('TYPE')"
          prop="objectName"
        >
          <a-select
            v-model="downloadTemplateForm.objectName"
            allow-clear
            show-search
            :placeholder="$t('PLACESELECT')"
          >
            <a-select-option
              v-for="item in typeOptions"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</a-select-option
            >
          </a-select>
          <a-button
            :disabled="!downloadTemplateForm.objectName"
            @click="handleDownload"
          >
            <Icon
              type="icon-cur-cloud-download"
              style="color: #666"
              :size="16"
            />
            {{ $t("DOWNLOAD") }}
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </Modal>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { chain } from "lodash";
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import { getToken } from "@/utils/auth";
import { fetchFileUrl } from "@/utils/file";
import ApiConstant from "@/api/ApiConstant";

export default {
  name: "Index",
  components: {
    MegaDrawer,
    Icon,
  },
  data() {
    return {
      templateVisible: false,
      queryForm: {
        objectName: "",
        status: null,
        updateTime: null,
      },
      sortParams: null,
      tableData: [],
      page: 1,
      total: 0,
      drawerVisible: false,
      typeOptions: [],
      statusOptions: [],
      form: {
        objectName: "",
        fileName: "",
      },
      downloadTemplateForm: {
        objectName: "",
      },
      fileList: [],
      fileFormData: null,
      options: {
        target: `${ApiConstant.PREFIX_CORE}/api/sys/file/upload/chunk`,
        headers: {
          Authorization: getToken(),
          tenantId:
            this.$store.state.app.systemConfig.TENANT_OPEN === "true"
              ? this.$store.state.account.tenantId
              : "",
        },
        testChunks: true,
        chunkSize: 10 * 1024 * 1024,
        singleFile: true,
        showUploadList: true,
      },
    };
  },
  computed: {
    ...mapGetters("app", ["currentLang"]),
    rules() {
      return {
        objectName: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        fileName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
      };
    },
    downloadTemplateRules() {
      return {
        objectName: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
      };
    },
    // 表格查询条件
    queryFormItem() {
      return this.$observable("queryFormItem", {
        objectName: {
          label: () => this.$t("TYPE"),
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
        status: {
          label: () => this.$t("STATUS"),
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
        updateTime: {
          label: () => this.$t("UPDATE_TIME"),
          itemType: "date",
        },
      });
    },
    // 表格配置项
    tableColumns() {
      return [
        {
          dataIndex: "appName", // 所属应用
          title: () => this.$t("BELONG_APPLICATION"),
          width: 180,
        },
        {
          key: "objectName", // 类型
          title: () => this.$t("TYPE"),
          scopedSlots: { customRender: "objectName" },
          width: 100,
          type: "object",
          options: [],
        },
        {
          dataIndex: "fileUrl", // 数据文件
          ellipsis: true,
          title: () => this.$t("DATA_FILE"),
          width: 260,
        },
        {
          key: "status", // 状态
          title: () => this.$t("STATUS"),
          scopedSlots: { customRender: "status" },
          width: 100,
          type: "object",
          options: [],
        },
        {
          dataIndex: "resultFileUrl", // 结果文件
          ellipsis: true,
          title: () => this.$t("RESULT_FILE"),
          scopedSlots: { customRender: "resultFileUrl" },
          width: 260,
        },
        {
          dataIndex: "executeTimes", // 执行次数
          title: () => this.$t("RESULT_FILE"),
          width: 120,
        },
        {
          dataIndex: "remark",
          ellipsis: true,
          title: () => this.$t("REMARK"),
          minWidth: 300,
        },
        {
          dataIndex: "updateBy", // 更新人员
          title: () => this.$t("UPDATE_BY"),
          width: 120,
        },
        {
          dataIndex: "updateTime", // 更新时间
          title: () => this.$t("UPDATE_TIME"),
          width: 168,
        },
      ];
    },
  },
  async created() {
    await this.queryDictData();
  },
  methods: {
    handleRefreshDictionary() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/dict-data/refresh`)
        .then((res) => {
          this.$message.success(this.$t("REFRESH_SUCCESS"));
        });
    },
    handleRefreshI18n() {
      const languages = chain(this.$store.state.app.languages)
        .map("value")
        .value();
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/i18n/refresh`)
        .then((res) => {
          chain(languages)
            .map((lang) => {
              const key = lang;
              const reg = new RegExp(`_${key}$`);
              const value = chain(res.data.data)
                // eslint-disable-next-line
                .pickBy((value, key) => reg.test(key))
                // eslint-disable-next-line
                .mapKeys((value, key) => key.replace(reg, ""))
                .value();
              return [key, value];
            })
            .fromPairs()
            .value();
        })
        .then((res) => {
          chain(languages)
            .forEach((lang) => {
              this.$i18n.setLocaleMessage(lang, {
                ...this.$i18n.messages[lang],
                ...res[lang],
                // 合并本地国际化
              });
            })
            .value();
          this.$store.commit("app/SET_I18N_JSON", {
            system: process.env.SYSTEM_CODE,
            json: res,
          });
          this.$message.success(this.$t("REFRESH_SUCCESS"));
        });
    },
    handleDownload() {
      const a = document.createElement("a");
      a.href = `/template/${this.downloadTemplateForm.objectName}.xlsx`;
      a.download = "";
      a.click();
      this.templateVisible = false;
    },
    uploadChange(file) {
      this.form.fileName = file.name;
      this.fileFormData = file;
    },

    handleAdd() {
      this.drawerType = "add";
      this.$set(this, "form", {
        objectName: "",
        fileName: "",
      });
      this.drawerVisible = true;
      this.$nextTick(() => {
        this.$refs.dataSource.clearValidate();
      });
    },
    queryDictData() {
      return Promise.all([
        this.getDictByCode(`DIC:CORE:DATA_IMPORT_TYPE`),
        this.getDictByCode(`DIC:CORE:IMPORT_STATUS`),
      ]).then(([res, res2]) => {
        this.typeOptions = res.data.data;
        this.queryFormItem.objectName.options = res.data.data;
        this.tableColumns[1].options = res.data.data;
        this.statusOptions = res2.data.data;
        this.queryFormItem.status.options = res2.data.data;
        this.tableColumns[3].options = res2.data.data;
      });
    },
    formatDate(value) {
      const date = new Date(value);
      const y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? `0${MM}` : MM;
      let d = date.getDate();
      d = d < 10 ? `0${d}` : d;
      return `${y}-${MM}-${d}`;
    },
    searchPageData(data) {
      // eslint-disable-next-line
      data.updateTime = data.updateTime
        ? this.formatDate(data.updateTime)
        : null;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/data-import/search`, {
          params: data,
        })
        .then((res) => {
          if (res.data.data.records && res.data.data.records.length > 0) {
            res.data.data.records.forEach((item) => {
              if (item.fileUrl) {
                // eslint-disable-next-line
                item.fileUrl = fetchFileUrl(item.fileUrl, this);
              }
              if (item.resultFileUrl) {
                // eslint-disable-next-line
                item.resultFileUrl = fetchFileUrl(item.resultFileUrl, this);
              }
            });
          }
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    save() {
      this.$refs.dataSource.validate((valid) => {
        if (valid) {
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/sys/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.currentLang && this.currentLang.lang) || "zh_CN",
                })
                .then((data) => {
                  this.$message.success(this.$t("ADD_SUCCESS"));
                  this.$refs.MomTable?.query();
                  this.close();
                });
            });
        }
      });
    },
    close() {
      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 = [];
    },
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-drawer {
  width: 25% !important;
  min-width: 480px;
  max-width: 700px;
}
/deep/ .el-drawer__header {
  padding: 15px 16px 15px 30px;
}
/deep/ .i-form .form-row {
  padding: 0 !important;
}
/deep/ .mega-design-drawer__footer {
  border: none;
}
</style>
