<template>
  <div class="box-main">
    <div class="box-body">
      <MomTable
        ref="MomTable"
        row-key="id"
        :row-selection="rowSelection"
        :columns="tableColumns"
        :data-source="tableData"
        :query-param="queryForm"
        :query-param-item="queryFormItem"
        :action-buttons="actionButtons"
        :page.sync="page"
        :total="total"
        @copy="handleCopy"
        @edit="handleEdit"
        @delete="handleDelete"
        @search="searchPageData"
      >
        <div slot="toolbar">
          <!-- 新增 -->
          <a-button
            v-if="hasAuth('PRINT_AUTHORIZATION:ADD')"
            @click="handleOpenDrawer('add')"
          >
            <a-icon type="plus" />
            {{ $t("ADD") }}
          </a-button>
          <a-button
            v-if="hasAuth('PRINT_AUTHORIZATION:BATCH_DELETE')"
            type="danger"
            icon="delete"
            @click="handDelete"
          >
            {{ $t("BATCH_DELETE") }}
          </a-button>
        </div>
      </MomTable>
    </div>
    <!-- 新增、编辑弹框 -->
    <MegaDrawer
      :visible.sync="drawer"
      :title="drawerType !== 'edit' ? `${$t('ADD')}` : `${$t('EDIT')}`"
      width="520"
      @close="handleCancel"
    >
      <div slot="main">
        <a-form-model
          ref="formRef"
          layout="vertical"
          :model="formData"
          :rules="rules"
        >
          <!-- 编码 -->
          <a-form-model-item :label="$t('CODE')" prop="code">
            <a-input v-model="formData.code" allow-clear />
          </a-form-model-item>
          <!-- 名称 -->
          <a-form-model-item :label="$t('NAME')" prop="name">
            <a-input v-model="formData.name" allow-clear />
          </a-form-model-item>
          <!-- 授权地址 -->
          <a-form-model-item :label="$t('SEVER_ADDRESS')" prop="serverAddress">
            <a-input v-model="formData.serverAddress" allow-clear />
          </a-form-model-item>
          <!-- 文件 -->
          <a-form-model-item :label="$t('AUTH_FILE')">
            <div style="position: absolute; top: -7px; left: -83px; color: red">
              *
            </div>
            <a-upload
              :action="url"
              :headers="headers"
              limit="1"
              :data="fileData"
              :file-list="fileList"
              :before-upload="beforeUpload"
              @change="uploadSuccess"
            >
              <a-button type="primary">
                {{ $t("UPLOAD") }}
              </a-button>
              {{ $t("UPLOAD_ONLY") }}mega-insight.html{{ $t("FILE") }}
            </a-upload>
          </a-form-model-item>
        </a-form-model>
      </div>
      <template slot="footer">
        <a-button type="primary" @click="save()">
          <Icon type="icon-cur-save_1" :size="18" />
          {{ $t("SAVE") }}
        </a-button>
        <a-button @click="handleCancel">
          <Icon type="icon-dir-f-rollback" :size="18" />
          {{ $t("CANCEL") }}
        </a-button>
      </template>
    </MegaDrawer>
  </div>
</template>

<script>
import Vue from "vue";
import VueClipBoard from "vue-clipboard2";
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import { v1 as uuidv1 } from "uuid";
import ApiConstant from "@/api/ApiConstant";
import { fetchFileUrl } from "@/utils/file";

Vue.use(VueClipBoard);
export default {
  name: "Lablicense",
  components: {
    MegaDrawer,
    Icon,
  },
  data() {
    return {
      url: `${ApiConstant.PREFIX_CORE}/api/sys/file/upload`, // 上传文件路径
      headers: {
        Authorization: this.$auth.getToken("local"),
        tenantId:
          this.$store.state.app.systemConfig.TENANT_OPEN === "true"
            ? this.$store.state.account.tenantId
            : "",
      },
      fileData: {
        fileName: "mega-insight.html",
        rename: false,
        subDir: "/",
      },
      // 查询sort
      sortParams: null,
      // 查询表单数据
      queryForm: {
        name: null,
      },
      tableData: [],
      total: 0,
      page: 1,
      drawer: false,
      drawerType: "add",
      formData: {
        id: "",
        name: "",
        serverAddress: "",
        code: "",
        fileName: "",
      },
      form: null,
      fileList: [], // 文件列表
      isUpload: false, // 是否上传文件
      actionButtons: [
        this.hasAuth(`PRINT_AUTHORIZATION:COPY`) && "copy",
        this.hasAuth(`PRINT_AUTHORIZATION:EDIT`) && "edit",
        this.hasAuth(`PRINT_AUTHORIZATION:DELETE`) && "delete",
      ],
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    rules() {
      return {
        name: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        serverAddress: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      };
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        // 名称
        name: {
          label: () => this.$t("NAME"),
        },
      });
    },
    tableColumns() {
      return [
        // 名称
        {
          dataIndex: "name",
          title: () => this.$t("NAME"),
          width: 240,
          sorter: false,
        },
        // 授权地址
        {
          dataIndex: "serverAddress",
          title: () => this.$t("SEVER_ADDRESS"),
          width: 380,
          sorter: false,
        },
        // 配置地址
        {
          dataIndex: "settingUrl",
          title: () => this.$t("SETTING_URL"),
          sorter: false,
          minWidth: 380,
        },
        // 更新人员
        {
          dataIndex: "updateBy",
          title: () => this.$t("UPDATE_BY"),
          width: 120,
          sorter: false,
        },
        // 更新时间
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          width: 200,
          sorter: false,
        },
      ];
    },
  },
  methods: {
    // 查后台分页查询
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/print/license/search`, {
          params,
        })
        .then((res) => {
          if (res.data.data.records && res.data.data.records.length > 0) {
            res.data.data.records.forEach((item) => {
              if (item.settingUrl) {
                // eslint-disable-next-line
                item.settingUrl = fetchFileUrl(item.settingUrl, this);
              }
            });
          }
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 编辑
    handleEdit(row) {
      this.fileList = [];
      this.fileList.push({
        uid: uuidv1(),
        name: row.fileName,
        status: "done",
        url: "",
      });
      this.handleOpenDrawer("edit", row);
    },
    handleCopy(row) {
      this.$copyText(row.settingUrl).then(
        () => {
          this.$message.success(this.$t("COPY_SUCCESS"));
        },
        () => {
          this.$message.success(this.$t("COPY_FAILED"));
        }
      );
    },
    // 新增或者编辑
    handleOpenDrawer(type, row) {
      if (type === "add") {
        this.isUpload = false;
      } else {
        this.isUpload = true;
      }
      this.drawerType = type;
      this.drawer = true;
      if (type === "edit" || type === "copy") {
        this.formData.id = row.id;
        this.formData.name = row.name;
        this.formData.serverAddress = row.serverAddress;
        this.formData.fileName = row.fileName;
        this.formData.code = row.code;
      } else if (type === "add") {
        this.$set(this, "formData", {
          name: "",
          serverAddress: "",
          fileName: "",
          code: "",
        });
        this.fileList = [];
      }
    },
    handDelete() {
      if (this.selectedRowKeys.length > 0) {
        this.$confirm({
          title: this.$t("DELETE"),
          content: this.$t("DELETE_INFO"),
          okType: "warning",
          okText: this.$t("DELETE"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "close-circle",
          onOk: () => {
            this.$axios
              .delete(
                `${ApiConstant.PREFIX_CORE}/api/print/license/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then((res) => {
                this.$refs.MomTable?.query();
                this.$message.success(this.$t("DELETE_SUCCESS"));
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    // 删除
    handleDelete(row) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("DELETE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/print/license/${row.id}`)
            .then((res) => {
              this.$refs.MomTable?.query();
              this.$message.success(this.$t("DELETE_SUCCESS"));
            });
        },
      });
    },
    save() {
      // 编辑状态下，文件非必选
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 校验是否选择文件
          if (this.fileList.length < 1) {
            this.$message.warning(`${this.$t("PLEASE_SELECT_FILE_FIRST")}!`);
            return;
          }
          // 请求头支持文件
          const params = { ...this.formData };
          // 组请求
          if (this.drawerType === "edit") {
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/print/license`, params)
              .then((res) => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.$refs.MomTable?.query();
                this.drawer = false;
              });
          } else {
            this.$axios
              .post(`${ApiConstant.PREFIX_CORE}/api/print/license`, params)
              .then((res) => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.$refs.MomTable?.query();
                this.drawer = false;
              });
          }
        }
      });
    },
    // 对话框取消
    handleCancel() {
      this.$refs.formRef.clearValidate();
      this.$refs.formRef.resetFields();
      this.drawer = false;
    },
    // 获取查询条件
    getSearchParams() {
      const req = {
        page: this.page,
        size: this.$store.state.pagination.pageSize,
      };
      return { ...req, ...this.queryForm };
    },
    // 文件上传
    uploadSuccess(info) {
      this.fileList = [];
      this.fileList = [info.fileList[Number(info.fileList.length - 1)]];
      this.formData.fileName = info?.file?.name;
    },
    // 上传文件之前校验
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        // 判断文件类型
        if (file.name !== this.fileData.fileName) {
          this.fileList = [];
          this.$message.error(
            `${this.$t("UPLOAD_ONLY")}mega-insight.html${this.$t("FILE")}`
          );
          // eslint-disable-next-line prefer-promise-reject-errors
          reject(false);
        }
        const isLt2M = file.size / 1024 / 1024 < 100; // 判断文件大小是否小于100M
        if (!isLt2M) {
          this.$message.error(
            `${this.$t("UPLOAD_FILE_CANNOT_EXCEED") + 100}MB!`
          );
          // eslint-disable-next-line prefer-promise-reject-errors
          reject(false);
        }
        resolve(true);
      });
    },
  },
};
</script>
