<template>
  <div class="appendix-manage">
    <div class="operation-panel-list">
      <el-row :gutter="10" class="mb20">
        <el-col :span="3">
          <el-input
            v-model="queryParams.createBy"
            size="small"
            placeholder="创建人"
          />
        </el-col>
        <el-col :span="3">
          <el-input
            v-model="queryParams.assistLabel"
            size="small"
            placeholder="辅助标签"
          />
        </el-col>
        <el-col :span="3">
          <el-select
            v-model="queryParams.privateFlag"
            size="small"
            placeholder="查看公共文件"
          >
            <el-option value="true" label="是" />
            <el-option value="false" label="否" />
          </el-select>
        </el-col>
        <el-col :span="1.5">
          <el-date-picker
            v-model="queryParams.Time"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            size="small"
            :clearable="false"
            end-placeholder="结束日期"
          />
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-search"
            plain
            size="mini"
            @click="search"
            >查 询</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button
            type="primary"
            icon="el-icon-refresh"
            plain
            size="mini"
            @click="reset"
            >重 置</el-button
          >
        </el-col>
      </el-row>
      <el-row :gutter="12" class="mb20">
        <el-col :span="3.5">
          <el-button
            type="primary"
            icon="el-icon-upload"
            plain
            size="mini"
            @click="handleShowAppendixModal"
            >上传附件</el-button
          >
        </el-col>
        <el-col :span="2.5">
          <el-button
            type="warning"
            icon="el-icon-edit"
            plain
            size="mini"
            :disabled="operationState.edit"
            @click="handleEditAppendix"
            >编 辑</el-button
          >
        </el-col>
        <el-col :span="3">
          <el-button
            type="danger"
            icon="el-icon-delete"
            plain
            size="mini"
            :disabled="operationState.delete"
            @click="handleDeleteAppendix"
            >删 除</el-button
          >
        </el-col>
      </el-row>
    </div>
    <div class="table-list">
      <div class="tree-filter">
        <el-input
          v-model="filterText"
          placeholder="输入关键字进行过滤"
          size="mini"
          clearable
        />
        <el-tree
          ref="tree"
          :data="treeList"
          :props="defaultProps"
          default-expand-all
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
        >
          <span slot-scope="{ node }" class="custom-tree-node">
            <div class="tree-item">
              <i
                class="el-icon-folder-opened"
                style="color: rgba(254, 210, 89, 1)"
              />
              <span
                style="margin-left: 5px; font-size: 12px; font-weight: bold"
                >{{ node.label }}</span
              >
            </div>
          </span>
        </el-tree>
      </div>
      <el-table
        stripe
        border
        :fit="true"
        height="460"
        :header-cell-style="{ background: '#EEE', color: '#414141' }"
        :data="tableList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" width="40" />
        <!-- <el-table-column label="序号" type="index" width="55" align="center" /> -->
        <el-table-column type="expand">
          <template v-slot="{ row }">
            <div class="expand-title">
              <span>辅助标签</span>
            </div>
            <div class="expand-content">
              <el-tag
                v-for="(item, index) in computedAssistLabel(row.assistLabel)"
                :key="index"
                style="margin: 6px 12px"
              >
                {{ item }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="文件名称"
          width="160"
          align="center"
          prop="originName"
          show-overflow-tooltip
        />
        <el-table-column
          label="主标签"
          width="140"
          align="center"
          prop="mainLabel"
          show-overflow-tooltip
        >
          <template v-slot="{ row }">
            <el-tag type="primary">{{
              computedMainLabel(row.mainLabel)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="有效时长/天"
          width="140"
          align="center"
          prop="validDay"
          show-overflow-tooltip
        />
        <el-table-column
          label="过期时间"
          width="160"
          align="center"
          prop="deadline"
          show-overflow-tooltip
        />
        <el-table-column
          label="文件状态"
          width="120"
          align="center"
          prop="state"
          show-overflow-tooltip
        >
          <template v-slot="{ row }">
            <el-tag :type="row.state === 'true' ? 'primary' : 'danger'">
              {{ row.state === "true" ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="是否允许下载"
          width="120"
          align="center"
          prop="downloadFlag"
          show-overflow-tooltip
        >
          <template v-slot="{ row }">
            <el-tag :type="row.downloadFlag === 'true' ? 'primary' : 'danger'">
              {{ row.downloadFlag === "true" ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="版本号"
          width="160"
          align="center"
          prop="version"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建人"
          width="120"
          align="center"
          prop="createBy"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          width="140"
          align="center"
          prop="createTime"
          show-overflow-tooltip
        >
          <template v-slot="{ row }">
            {{
              ![NaN, undefined, null, "", 0].includes(row.createTime)
                ? new Date(row.createTime).toLocaleString()
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="更新人"
          width="120"
          align="center"
          prop="updateBy"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新时间"
          width="140"
          align="center"
          prop="updateTime"
          show-overflow-tooltip
        >
          <template v-slot="{ row }">
            {{
              ![NaN, undefined, null, "", 0].includes(row.updateTime)
                ? new Date(row.updateTime).toLocaleString()
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="100">
          <template v-slot="{ row }">
            <el-button
              v-if="row.downloadFlag === 'true'"
              type="text"
              size="small"
              @click="downloadFile(row)"
              >下载文件</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination
      v-show="queryParams.total > 0"
      :total="queryParams.total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="search"
    />
    <Appendix
      ref="appendixDialog"
      @uploadFile="uploadFile"
      @cancelAppendixModal="cancelAppendixModal"
    />
  </div>
</template>
<script>
import Appendix from "./components/appendix.vue";
import {
  searchMkdirList,
  getAppendixTableData,
  insertOrUpdateAppendix,
  deleteAppendixData,
} from "@/api/system/appendix.js";
import { getDictionariesList } from "@/api/system/codeRule.js";
import { handleTree2 } from "@/utils/ruoyi.js";
import { blobType } from "@/utils/blobType";
import axios from "axios";

export default {
  components: { Appendix },
  data() {
    return {
      loading: false,
      treeList: [],
      filterText: "",
      defaultProps: {
        children: "children",
        label: "menuName",
      },
      // 查询参数
      queryParams: {
        // 总条数
        total: 0,
        pageNum: 1,
        pageSize: 50,
        createBy: "",
        fileName: "",
        assistLabel: "",
        privateFlag: "",
        printFlag: "0",
        Time: [],
      },
      tableList: [],
      tagDictList: [],
      selectTableRow: [],
      operationState: {
        edit: true,
        delete: true,
      },
    };
  },
  computed: {
    computedAssistLabel: () => {
      return (item) => {
        return item?.split(",") ?? [];
      };
    },
    computedMainLabel: function () {
      const _this = this;
      return (item) => {
        return _this.tagDictList.filter((opt) => item === opt.value)[0]?.label;
      };
    },
  },
  watch: {
    selectTableRow: {
      handler: function (event) {
        if (event?.length === 0) this.operationState.delete = true;
        if (event?.length > 0) this.operationState.delete = false;
        if (event?.length > 1 || event?.length === 0) {
          this.operationState.edit = true;
        } else {
          this.operationState.edit = false;
        }
      },
      deep: true,
    },
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  mounted() {
    this.search();
    getDictionariesList("sys_file_tag").then(({ data }) => {
      this.tagDictList = data?.list ?? [];
    });
    searchMkdirList().then(({ data }) => {
      this.treeList = handleTree2(data, "id", "parentId", "children");
    });
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.menuName.indexOf(value) !== -1;
    },
    handleNodeClick(node) {
      this.queryParams.filesMenuId = node?.id;
      this.search();
      this.$refs["appendixDialog"].mkdirList = JSON.parse(
        JSON.stringify(this.treeList)
      );
      this.$refs["appendixDialog"].form.filesMenuId = node?.id;
    },
    search() {
      getAppendixTableData(this.queryParams).then(({ data }) => {
        this.queryParams.total = data?.count;
        this.tableList = data?.list;
      });
    },
    reset() {
      this.queryParams = {
        // 总条数
        total: 0,
        pageNum: 1,
        pageSize: 50,
        createBy: "",
        fileName: "",
        assistLabel: "",
        privateFlag: "",
        Time: [],
      };
      this.search();
    },
    handleShowAppendixModal() {
      this.$refs["appendixDialog"].appendixTitle = "附件管理";
      this.$refs["appendixDialog"].mkdirList = JSON.parse(
        JSON.stringify(this.treeList)
      );
      this.$refs["appendixDialog"].resetForm();
      this.$refs["appendixDialog"].dialogAppendxModalState = true;
    },
    uploadFile(data) {
      let filesMenuId;
      if (
        Object.prototype.toString.call(data.filesMenuId) === "[object Array]"
      ) {
        filesMenuId = data.filesMenuId.at(-1);
      } else {
        filesMenuId = data.filesMenuId;
      }
      insertOrUpdateAppendix({ ...data, filesMenuId }).then((res) => {
        this.$notify({
          title: "成功",
          message: "附件已保存",
          type: "success",
          showClose: false,
        });
        if (this.$refs["appendixDialog"].appendixTitle !== "附件管理-编辑") {
          this.$refs["appendixDialog"].appendixTitle = "附件管理";
          this.$refs["appendixDialog"].resetForm();
        }
        this.$refs["appendixDialog"].dialogAppendxModalState = false;
      });
    },
    async downloadFile(row) {
      // 全局挂载loading事件
      const rLoading = this.openLoading();
      if (![NaN, null, undefined, ""].includes(blobType[row.fileSuffix])) {
        const result = await axios({
          method: "get",
          url: row.url,
          responseType: "blob",
        });
        const link = document.createElement("a");
        const url = window.URL.createObjectURL(
          new Blob([result.data], { type: blobType[row.fileSuffix] })
        );
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", row.originName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } else {
        location.href = row.url;
      }
      rLoading.close();
    },
    // 附件管理-编辑
    handleEditAppendix() {
      const fileObject = this.selectTableRow[0];
      const filterToFalse = [
        "deadlineFlag",
        "versionFlag",
        "state",
        "downloadFlag",
      ];
      if (
        Object.prototype.toString.call(fileObject.assistLabel) !==
        "[object Array]"
      ) {
        fileObject.assistLabel = fileObject.assistLabel?.split(",") ?? [];
      }
      Object.keys(fileObject).forEach((item) =>
        filterToFalse.includes(item) & (fileObject[item] === null)
          ? (fileObject[item] = "false")
          : fileObject[item]
      );
      this.$refs["appendixDialog"].resetForm();
      Object.assign(this.$refs["appendixDialog"].form, fileObject);
      // 校验有效期
      const deadlineField = [undefined, NaN, null, ""].includes(
        fileObject.deadline
      );
      // 有效期回显
      if (!deadlineField) {
        this.$refs["appendixDialog"].form.deadline = new Date(
          fileObject.deadline.split(" ")[0]
        ).getTime();
      }
      this.$refs["appendixDialog"].filesId = fileObject.filesId;
      this.$refs["appendixDialog"].fileList.length = 0;
      this.$refs["appendixDialog"].fileList.push({
        id: fileObject?.id ?? "",
        sysName: fileObject?.sysName ?? "",
        name: fileObject?.originName,
        url: fileObject?.url,
        size: fileObject?.size,
      });
      this.$refs["appendixDialog"].appendixTitle = "附件管理-编辑";
      this.$refs["appendixDialog"].mkdirList = JSON.parse(
        JSON.stringify(this.treeList)
      );
      this.$refs["appendixDialog"].dialogAppendxModalState = true;
    },
    handleDeleteAppendix() {
      const ids = Array.from(this.selectTableRow, (item) => item.id);
      deleteAppendixData(ids).then(({ code, msg }) => {
        if (code === 200) {
          this.$message.success("文件已删除！");
        } else {
          this.$message.error(msg);
        }
        this.search();
      });
    },
    handleSelectionChange(row) {
      this.selectTableRow = JSON.parse(JSON.stringify(row));
    },
    cancelAppendixModal() {
      this.search();
    },
  },
};
</script>

<style lang="scss" scoped>
.table-list {
  display: flex;
  .tree-filter {
    padding-right: 12px;
  }
}
.appendix-manage {
  height: calc(100vh - 95px);
  overflow-y: scroll;
  padding: 20px;
  .operation-panel-list {
    .mb20 {
      display: flex;
      align-items: center;
    }
  }
}
// 表格样式
::v-deep .el-table,
.el-link {
  font-size: 12px !important;
}
::v-deep .el-table--medium .el-table__cell {
  padding: 3px 0 !important;
}
::v-deep .el-table .el-table__header-wrapper th,
.el-table .el-table__fixed-header-wrapper th {
  height: 32px !important;
  font-size: 12px !important;
}

.expand-title {
  font-size: 14px;
  font-weight: bold;
  padding-left: 12px;
  display: flex;
  align-items: center;
}
.expand-title::before {
  content: "";
  display: block;
  width: 4px;
  height: 14px;
  margin-right: 4px;
  background-color: skyblue;
}
</style>
