<template>
  <cms-query-table
    :tool-bars="toolBars"
    :query-params="queryParams"
    ref="attachTable"
    :columns="columns"
    :form-item-config="false"
    :request-call="this.$http.common.attach_page"
    :search-method="false"
  >
    <template slot="empty">
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </template>
    <template slot="buttons">
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="uploadUrl"
        :http-request="httpRequest"
        accept="*"
        :multiple="multiple"
        :auto-upload="autoUpload"
        :show-file-list="false"
      >
        <cms-button slot="trigger" size="small" type="primary"
          >选取需要上传的文件</cms-button
        >
        <cms-button
          v-if="!autoUpload"
          style="margin-left: 10px"
          size="small"
          type="success"
          @click="submitUpload"
          >上传到服务器
        </cms-button>
      </el-upload>
    </template>
  </cms-query-table>
</template>
<script>
import { dictionaryMix, mixTableConstants } from "@/comps/mixin/common-mixins";

export default {
  name: "user-list",
  mixins: [dictionaryMix, mixTableConstants],
  props: {
    queryParams: {
      type: Object,
      default: () => {
        return {};
      },
    },
    formModel: {
      type: Object,
      default: () => {
        return {};
      },
    },
    autoUpload: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    limit: {
      type: Number,
      default: () => {
        return 20;
      },
    },
    multiple: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    callback: Function,
  },
  data() {
    let { ...listeners } = this.$listeners;
    return {
      listeners: listeners,
      fileList: [],
      files: [],
      actionUrl: "",
      file: undefined,
      uploadUrl: "/api/base/system/attach/upload-file.json", // 上传地址，
      dictionaryConfig: [
        {
          type: "constants",
          keys: [
            "Enable.selectList",
            "Locked",
            "Enable",
            "UserType.selectList",
            "Locked.selectList",
            "UserSource",
            "UserSource.selectList",
          ],
        },
      ],
      constants: {},
      toolBars: [],
    };
  },
  async created() {
    const requestCall = this.$http.common.query_constants;
    await this.mixGetDictionaries(requestCall, this.dictionaryConfig).then((res) => {
      this.constants = res;
    });
  },
  methods: {
    /**
     * 查看详情
     */
    toView(row) {
      this.openPage({
        component: "",
        data: row,
        area: ["60%", "550px"],
        title: this.$t("user.title.view"),
        cancel: () => {
          //关闭事件
          this.searchClick();
        },
      });
    },
    deleteItem(file, fileList) {
      console.log(file, fileList);
      // this.$pageCommon.confirm(this.$t('common.message.deleteConfirm'), () => {
      //   this.$http.users.delete_user({id: row.id, version: row.version}).then(({msg}) => {
      //     this.searchClick();
      //     this.$messageTips.success(msg)
      //   })
      // })
    },
    batchDelete() {
      const tableData = this.$refs["userTable"].getCheckboxRecords();
      if (!tableData || tableData.length === 0) {
        this.$messageTips.warning(this.$t("common.message.unSelect"));
        return false;
      }
      this.$pageCommon.confirm(this.$t("common.message.deleteConfirm"), () => {
        this.$http.users.batch_delete_user(tableData).then((res) => {
          this.searchClick();
          this.$messageTips.success(res.msg);
        });
      });
    },
    onChange(file, fileList) {
      const length = file.name.indexOf(".") + 1;
      let filextension = file.name.substring(length, file.name.length);
      filextension = filextension.toLowerCase();
      this.fileList.push({
        fileName: file.name,
        fileSize: file.size,
        suffix: filextension,
      });
      this.files = fileList;
    },
    submitUpload() {
      let formData = new FormData(); // FormData 对象
      if (this.files.length === 0) {
        this.$messageTips.warning("請選擇需要上传的文件");
        return false;
      }
      this.files.forEach((file) => {
        formData.append("files", file.raw); // 文件对象
      });
      const queryParams = this.queryParams;
      for (const key in queryParams) {
        formData.append(key, queryParams[key]);
      }
      formData.append("name", "测试文件");
      const config = { headers: { "Content-Type": "multipart/form-data" } };
      let loading = this.$cmsLoading.open({ text: this.$t("common.message.loadingMsg") });
      this.$http.common.uploadFile(formData, config).then((res) => {
        loading.close();
        console.log(res);
        this.$refs["attachTable"].reload();
        this.$pageCommon.alert(res.msg, () => {
          if (this.callback) this.callback();
        });
      });
    },
    httpRequest({ file, data }) {
      let fd = new FormData();
      console.log(this.fileList, "==========================");
      fd.append("file", file);
      if (!this.multiple && this.fileList.length >= 1) {
        this.$message.error("只能上传一张图片, 请先删除再上传");
        return false;
      }
      if (data) {
        for (const key in data) {
          fd.append(key, data[key]);
        }
      }
      const queryParams = this.queryParams;
      for (const key in queryParams) {
        fd.append(key, queryParams[key]);
      }
      this.$http.common.uploadFile(fd).then(({ data }) => {
        this.$refs["attachTable"].reload();
        for (let i = 0; i < data.length; i++) {
          this.fileList.push(data[i]);
          if (this.callback) this.callback(this.fileList);
        }
      });
      return false;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    updateItem(file) {
      console.log(file);
    },
  },
  computed: {
    columns() {
      return [
        {
          ...mixTableConfig.seq,
          title: "序号",
        },
        {
          ...mixTableConfig.default,
          width: 160,
          fixed: "left",
          title: "业务单号",
          field: "businessNo",
        },
        {
          ...mixTableConfig.default,
          fixed: "left",
          minWidth: 260,
          title: "文件名称",
          field: "fileName",
          cellRender: {
            name: "cell-link",
            events: {
              click: this.toView,
            },
          },
        },
        {
          ...mixTableConfig.default,
          width: 160,
          title: "文件大小",
          field: "fileSize",
        },
        {
          ...mixTableConfig.default,
          width: 160,
          title: "文件后缀",
          field: "suffix",
        },
        {
          ...mixTableConfig.default,
          width: 160,
          title: "文件类型",
          field: "fileType",
        },
        {
          ...mixTableConfig.operate,
          title: this.$t("common.column.operate"),
          width: 170,
          cellRender: {
            name: "operateCell",
            buttons: [
              {
                click: this.updateItem,
                title: this.$t("common.button.edit"),
                props: {
                  icon: "el-icon-edit",
                  type: "primary",
                  vPermissionButton: ["user:update"],
                },
              },
              {
                click: this.deleteItem,
                title: this.$t("common.button.delete"),
                props: {
                  icon: "delete",
                  type: "danger",
                  vPermissionButton: ["user:delete"],
                },
              },
            ],
          },
        },
      ];
    },
  },
};
</script>

<style scoped></style>
