<!--数据源-->
<template>
  <div class="data-source-page">
    <MomTable
      ref="MomTable"
      :loading="loading"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :page.sync="page"
      :query-param-item="queryFormItem"
      :action-buttons="actionButtons"
      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
          :style="
            record.status === 'SUCCESS' ? 'color: #0fd19c' : 'color: #d45f5f'
          "
          >{{ formatData(statusOptions, record.status) }}</span
        >
      </template>
      <template slot="fileUrl" slot-scope="text, record">
        <span
          ><a :href="record.fileUrl">{{ record.fileUrl }}</a></span
        >
      </template>
      <template slot="resultFileUrl" slot-scope="text, record">
        <span
          ><a :href="record.resultFileUrl">{{ record.resultFileUrl }}</a></span
        >
      </template>
      <a-row slot="toolbar" class="button-top-table">
        <a-button v-if="hasAuth('DATA_IMPORT:ADD')" @click="handleAdd">
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
      </a-row>
    </MomTable>
    <MegaModal
      :visible="templateVisible"
      :title="$t('BATCH_IMPORT')"
      :footer="null"
      width="650px"
      @cancel="templateVisible = false"
    >
      <a-form-model
        ref="form"
        :model="form"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-form-model-item :label="$t('TYPE')" prop="objectName">
          <a-row>
            <a-col :span="16">
              <a-select
                v-model="form.objectName"
                filterable
                clearable
                :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-col>
            <a-col :span="4" :offset="1">
              <MomImportButton
                v-show="form.objectName"
                :object-name="form.objectName"
                :title="$t('CONFIRM')"
              />
            </a-col>
          </a-row>
        </a-form-model-item>
        <a-form-model-item label=""> </a-form-model-item>
      </a-form-model>
    </MegaModal>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { Icon, Modal as MegaModal } from "@mega-design/ui-vue";
import { fetchFileUrl } from "@/utils/file";
import ApiConstant from "@/api/ApiConstant";
import MomImportButton from "@/components/MomImportButton";

export default {
  // eslint-disable-next-line vue/no-unused-components
  components: { MomImportButton, MegaModal, Icon },
  beforeRouteLeave(to, form, next) {
    this.templateVisible = false;
    next();
  },
  data() {
    return {
      loading: false,
      templateVisible: false,
      queryForm: {
        objectName: "",
        status: null,
        updateTime: null,
      },
      tableData: [],
      page: 1,
      total: 0,
      typeOptions: [],
      statusOptions: [],
      form: {
        objectName: "",
      },
      fileList: [],
      fileFormData: null,
      actionButtons: [
        (h, value) => {
          const { record } = value;
          if (record.resultFileUrl) {
            return (
              <span
                onClick={() => this.handleDownload(record)}
                style="cursor: pointer;"
                title={this.$t("DOWNLOAD")}>
                {<Icon type="icon-cur-cloud-download" size={16} />}
              </span>
            );
          }
          return null;
        },
      ],
    };
  },
  computed: {
    ...mapGetters("app", ["currentLang"]),
    rules() {
      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", // 所属应用
        //   sorter: false,
        //   title: () => this.$t("BELONG_APPLICATION"),
        //   width: 180,
        // },
        {
          key: "objectName", // 类型
          title: () => this.$t("TYPE"),
          scopedSlots: { customRender: "objectName" },
          width: 100,
          sorter: false,
          type: "object",
          options: [],
        },
        {
          dataIndex: "fileUrl", // 数据文件
          ellipsis: true,
          sorter: false,
          title: () => this.$t("DATA_FILE"),
          scopedSlots: { customRender: "fileUrl" },
          width: 260,
        },
        {
          key: "status", // 状态
          title: () => this.$t("STATUS"),
          scopedSlots: { customRender: "status" },
          width: 100,
          sorter: false,
          type: "object",
          options: [],
        },
        {
          dataIndex: "resultFileUrl", // 结果文件
          ellipsis: true,
          sorter: false,
          title: () => this.$t("RESULT_FILE"),
          scopedSlots: { customRender: "resultFileUrl" },
          width: 260,
        },
        {
          dataIndex: "executeTimes", // 执行次数
          title: () => this.$t("EXE_COUNT"),
          width: 120,
        },
        {
          dataIndex: "remark",
          ellipsis: true,
          sorter: false,
          title: () => this.$t("REMARK"),
          minWidth: 300,
        },
        {
          dataIndex: "updateBy", // 更新人员
          sorter: false,
          title: () => this.$t("UPDATE_BY"),
          width: 120,
        },
        {
          dataIndex: "updateTime", // 更新时间
          sorter: false,
          title: () => this.$t("UPDATE_TIME"),
          width: 168,
        },
      ];
    },
  },
  created() {
    this.queryDictData();
  },
  methods: {
    handleAdd() {
      this.templateVisible = true;
      this.form.objectName = "";
    },
    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;
      });
    },
    handleDownload(row) {
      const a = document.createElement("a");
      a.href = row.resultFileUrl;
      a.download = "";
      a.click();
      this.templateVisible = false;
    },
    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 no-param-reassign
      data.updateTime = data.updateTime
        ? this.formatDate(data.updateTime)
        : null;
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/data-import/search`, {
          params: data,
        })
        .then((res) => {
          this.loading = false;
          if (res.data.data.records && res.data.data.records.length > 0) {
            res.data.data.records.forEach((item) => {
              if (item.fileUrl) {
                // eslint-disable-next-line no-param-reassign
                item.fileUrl = fetchFileUrl(item.fileUrl, this);
              }
              if (item.resultFileUrl) {
                // eslint-disable-next-line no-param-reassign
                item.resultFileUrl = fetchFileUrl(item.resultFileUrl, this);
              }
            });
          }
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.i-form .form-row {
  padding: 0 !important;
}
/deep/.mega-design-drawer__footer {
  border: none;
}
</style>
