<template>
  <el-dialog
    width="600px"
    :show-close="false"
    :visible.sync="dialogAppendxModalState"
    append-to-body
  >
    <template slot="title">
      <div class="left-content">
        <el-image class="logo" :src="home_source_image" fit="scale-down" />
        <span>{{ appendixTitle }}</span>
      </div>
      <div class="right-content">
        <el-tooltip effect="light" content="保存" placement="top">
          <i class="el-icon-success" @click="handleSaveFile" />
        </el-tooltip>
        <el-tooltip effect="light" content="关闭" placement="top">
          <i class="el-icon-error" @click="handleCancelFile" />
        </el-tooltip>
      </div>
    </template>
    <el-form
      ref="form"
      :rules="rules"
      label-position="right"
      :model="form"
      label-width="90px"
    >
      <el-upload
        v-if="dialogAppendxModalState"
        ref="upload"
        class="upload-demo"
        drag
        :limit="1"
        :file-list="fileList"
        :on-change="handleFilePreview"
        :on-remove="handleRemoveFile"
        :on-exceed="handleExceed"
        :auto-upload="false"
        action=""
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <!-- <div class="el-upload__text"><em>文件大小不超过10MB</em></div> -->
      </el-upload>
      <el-row>
        <el-col :span="12">
          <el-form-item label="文件名">
            <el-input
              v-model="form.originName"
              class="default-width"
              disabled
              size="mini"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文件标签" prop="mainLabel">
            <el-select
              v-model="form.mainLabel"
              size="mini"
              placeholder="请选择标签"
              @change="handleChangeTag"
            >
              <el-option
                v-for="item in tagDictList"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="大小">
            <el-input
              v-model="form.size"
              class="default-width"
              :disabled="true"
              size="mini"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效期至">
            <el-date-picker
              v-model="form.deadline"
              class="default-width"
              :disabled="form.deadlineFlag != 'true'"
              size="mini"
              type="date"
              format="yyyy-MM-dd"
              value-format="timestamp"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="版本">
            <el-input
              v-model="form.version"
              class="default-width"
              :disabled="form.versionFlag != 'true'"
              size="mini"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否共享">
            <el-select
              v-model="form.privateFlag"
              class="default-width"
              size="mini"
            >
              <el-option label="是" value="false" />
              <el-option label="否" value="true" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="存放路径">
            <el-cascader
              v-model="form.filesMenuId"
              style="width: 470px"
              size="small"
              :options="mkdirList"
              :props="{
                checkStrictly: true,
                expandTrigger: 'hover',
                value: 'id',
                label: 'menuName',
                children: 'children',
              }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="辅助标签">
            <el-select
              v-model="form.assistLabel"
              style="width: 470px"
              size="small"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择/输入（辅助标签）"
            >
              <el-option
                v-for="item in defaultTagList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="版本控制">
            <el-radio v-model="form.versionFlag" disabled label="true"
              >是</el-radio
            >
            <el-radio v-model="form.versionFlag" disabled label="false"
              >否</el-radio
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效期控制">
            <el-radio v-model="form.deadlineFlag" disabled label="true"
              >是</el-radio
            >
            <el-radio v-model="form.deadlineFlag" disabled label="false"
              >否</el-radio
            >
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="允许下载">
            <el-radio v-model="form.downloadFlag" disabled label="true"
              >是</el-radio
            >
            <el-radio v-model="form.downloadFlag" disabled label="false"
              >否</el-radio
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-radio v-model="form.state" disabled label="true">可用</el-radio>
            <el-radio v-model="form.state" disabled label="false"
              >禁用</el-radio
            >
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注">
        <el-input
          v-model="form.note"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 8 }"
          size="mini"
          resize="none"
        />
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import { uploadFile, deleteAppendixFile } from "@/api/system/appendix.js";
import { getDictionariesList } from "@/api/system/codeRule.js";
import { formatDate } from "@/utils/index.js";

export default {
  data() {
    return {
      defaultTagList: [
        {
          label: "常用",
          value: "常用",
        },
        {
          label: "重要",
          value: "重要",
        },
      ],
      appendixTitle: "附件管理",
      fileList: [], // 文件列表
      tagDictList: [],
      mkdirList: [],
      filesId: "",
      form: {
        filesMenuId: [""],
        originName: "",
        mainLabel: "",
        downloadFlag: "true",
        size: "",
        version: "",
        versionFlag: "true",
        state: "true",
        deadline: "",
        deadlineFlag: "false", // 有效期控制
        assistLabel: [], // 辅助标签
        note: "", // 备注
      },
      home_source_image: require("@/assets/logo/logo.png"),
      dialogAppendxModalState: false,
      rules: {
        mainLabel: [
          { required: true, message: "文件标签不能为空", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    getDictionariesList("sys_file_tag").then(({ data }) => {
      this.tagDictList = data?.list ?? [];
    });
  },
  methods: {
    resetForm() {
      this.form = {
        filesMenuId: [""],
        originName: "",
        mainLabel: "",
        downloadFlag: "true",
        size: "",
        version: "",
        versionFlag: "true",
        state: "true",
        deadline: "",
        deadlineFlag: "false", // 有效期控制
        assistLabel: [], // 辅助标签
        note: "", // 备注
      };
      this.fileList.length = 0;
    },
    handleChangeTag(e) {
      switch (e) {
        case "1":
          this.form.downloadFlag = "true";
          this.form.versionFlag = "true";
          this.form.deadlineFlag = "false";
          this.form.state = "true";
          break;
        case "2":
        case "3":
          this.form.downloadFlag = "false";
          this.form.versionFlag = "false";
          this.form.deadlineFlag = "true";
          this.form.state = "true";
          break;
        case "4":
          this.form.downloadFlag = "false";
          this.form.versionFlag = "false";
          this.form.deadlineFlag = "true";
          this.form.state = "false";
          break;
      }
    },
    handleSaveFile() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.deadline = formatDate(this.form.deadline);
          this.$emit("uploadFile", JSON.parse(JSON.stringify(this.form)));
        }
      });
    },
    handleCancelFile() {
      // 文件列表长度>0 且 文件列表id不为false
      if (
        this.fileList?.length > 0 &&
        [NaN, null, undefined, ""].includes(this.filesId)
      ) {
        deleteAppendixFile(this.fileList[0].sysName);
      }
      this.dialogAppendxModalState = false;
      this.$emit("cancelAppendixModal");
      // 清空表单数据
      this.filesId = "";
      this.resetForm();
    },
    handleFilePreview(file) {
      this.form.originName = file?.name?.split(".")[0];
      this.form.size = file?.size;
      const formData = new FormData();
      formData.append("file", file.raw);
      uploadFile(formData)
        .then(({ code, data, message }) => {
          if (code === 200) {
            console.log(file, data);
            this.fileList.push({
              name: file?.name,
              sysName: data?.sysName,
              url: data?.url,
              fileSuffix: data?.suffix,
              size: file?.size,
            });
            this.form.sysName = data?.sysName;
            this.form.url = data?.url;
            this.form.fileSuffix = data?.suffix;
            this.$message.success("文件上传成功");
          } else {
            this.$message.warning(message);
          }
        })
        .catch((e) => {
          this.$refs.upload.clearFiles();
        });
    },
    handleRemoveFile(file, fileList) {
      if (file.sysName) {
        deleteAppendixFile(file.sysName).then(() => {
          const note = JSON.parse(JSON.stringify(this.form.note));
          const assistLabel = JSON.parse(JSON.stringify(this.form.assistLabel));
          this.fileList.length = 0;
          this.$refs.upload.clearFiles();
          this.resetForm();
          this.form.note = note;
          this.form.assistLabel = assistLabel;
        });
      } else {
        this.resetForm();
      }
    },
    handleExceed(files, fileList) {
      this.$notify({
        title: "提示",
        message: "只允许单文件上传！！！",
        type: "warning",
        showClose: false,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.default-width {
  width: 190px;
}
.logo {
  width: 20px;
  display: flex;
  align-items: center;
  margin: 0 5px;
}
.upload-demo {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 10px 0 18px 0;
}
.left-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  > span {
    padding-left: 4px;
    font-size: 14px;
    font-weight: bold;
  }
}
.right-content {
  font-size: 24px;
  i {
    cursor: pointer;
    padding-left: 5px;
    padding-right: 3px;
  }
  i:nth-of-type(1) {
    color: rgba(0, 160, 233, 1);
  }
  i:nth-of-type(2) {
    color: rgba(235, 57, 65, 1);
  }
}
::v-deep .el-upload-dragger {
  width: 280px !important;
  height: 130px !important;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
::v-deep .el-upload-dragger .el-icon-upload {
  margin: 5px 0;
}
::v-deep .el-dialog {
  border-radius: 6px;
}
::v-deep .el-dialog__header {
  padding: 10px !important;
  border-radius: 6px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: rgba(245, 247, 250, 1);
}
::v-deep .el-dialog__body {
  padding: 10px 20px !important;
}

::v-deep .el-tag.el-tag--info {
  padding: 12px;
  background-color: #4ea5ff;
  border-color: #d9ecff;
  color: #ecf5ff;
}
::v-deep .el-tag.el-tag--info .el-tag__close {
  color: #4ea5ff;
  background: #ecf5ff;
}
</style>
