<!--
 * @desc 档案管理-规章制度(菜单权限:企业管理员)
 * @author linyuanjie
 * @date 2023/9/21
-->

<template>
  <div class="rules-page">
    <basic-container>
      <div class="rules-tit">
        <h2>规章制度上传</h2>
        <span>注：请您确认：您拟分享的文件内容可以对外分享，且已经过法律合规专业人士的严格审查</span>
      </div>

      <p class="clr_666 mt10 mb36">上传的文件建议使用 PDF 文件，也支持DOC、DOCX、JPG、PNG 格式，大小20MB以内。</p>
      <el-button class="save-btn" type="primary" @click="submitFn">保存</el-button>
      <div v-for="(rule, ruleIdx) in rulesFileNameDict" :key="rule.label" class="rules-item">
        <div class="pb6 bb df_sb">
          <span class="rules-title">{{ rule.label }}</span>
          <el-switch v-model="switchObj[ruleIdx]" active-value="0" inactive-value="1">
          </el-switch>
        </div>
        <el-upload
          class="upload-demo mt16 mb44"
          :action="uploadUrl"
          :headers="headers"
          :before-upload="beforeFileUpload"
          :on-remove="(file, fileList) => { handleFileRemove(file, fileList, ruleIdx) }"
          :before-remove="beforeFileRemove"
          :on-success="(response, file, fileList) => { handleFileSuccess(response, file, fileList, ruleIdx) }"
          :on-error="(err, file, fileList) => { handleFileError(err, file, fileList, ruleIdx) }"
          :file-list="importFileObj[ruleIdx]"
          :show-file-list="false">
          <el-button icon="el-icon-upload">上传文件</el-button>
        </el-upload>
        <div class="file-list pl4">
          <div v-for="(item, index) in importFileObj[ruleIdx]" :key="item.url" class="file-item pr4 pointer">
            <div>
              <i class="el-icon-tickets mr7" /><span class="file-item-name">{{ item.name }}</span>
            </div>
            <div class="file-item-right">
              <span v-if="imgTypeList.includes(item.url.split('.')[1])" class="file-item-view f12 mr8" @click="viewImgFn(item)">查看</span>
              <span v-if="!imgTypeList.includes(item.url.split('.')[1])" class="file-item-view f12 mr8" @click="downloadFn(item)">下载</span>
              <i class="el-icon-close" @click="removeFileFn(item.url, index, ruleIdx)" />
            </div>
          </div>
        </div>
      </div>
    </basic-container>
    <el-image-viewer v-if="showViewer" :on-close="closeViewer" :url-list="viewerList" />
  </div>
</template>

<script>
import store from "@/store"
import {getDeptRulesList, getRulesFileNameDict, saveDeptRules} from "@/api/rules"
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import request from "@/router/axios";

export default {
  name: "Rules",
  components: { ElImageViewer },
  data () {
    return {
      headers: {
        Authorization: 'Bearer ' + store.getters.access_token
      },
      uploadUrl: '/admin/sys-file/upload',
      importFileObj: [],
      switchObj: {},
      rulesFileNameDict: [], // 所有规章制度文件名称
      deptRulesList: [], // 部门规章制度列表
      fileTypeLimit: [
        // 图片
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/bmp',
        'image/jpg',
        // word
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        // excel
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        // pdf
        'application/pdf',
        'application/x-pdf',
        // ppt
        'application/vnd.ms-powerpoint', // .ppt
        'application/vnd.openxmlformats-officedocument.presentationml.presentation' // .pptx
      ], // 支持上传的文件类型
      imgTypeList: ['jpeg', 'jpg', 'png', 'git', 'bmp'], // 能查看的文件类型
      showViewer: false,
      viewerList: []
    }
  },
  created () {
    this.getRulesFileNameDictFn()
  },
  methods: {
    async submitFn () {
      const params = []
      for (let i = 0; i < this.rulesFileNameDict.length; i++) {
        params.push({
          fileName: this.rulesFileNameDict[i].label,
          fileUrl: this.importFileObj[i].map(ele => ({
            fileName: ele.name,
            url: ele.url
          })),
          enableFlag: this.switchObj[i] // 0启用, 1禁用
        })
      }
      const res = await saveDeptRules(params)
      if (res.data.code === 0) {
        this.$message.success('保存成功')
        this.getDeptRulesListFn()
      }
    },
    initData () {
      for (let i = 0; i < this.rulesFileNameDict.length; i++) {
        const fileName = this.rulesFileNameDict[i].label
        const mapRuleItem = this.deptRulesList.find(ele => ele.fileName === fileName)
        this.$set(this.importFileObj, i, mapRuleItem ? [...mapRuleItem.fileUrl.map(ele => ({ name: ele.fileName, url: ele.url }))] : [])
        this.switchObj[i] = mapRuleItem ? mapRuleItem.enableFlag : '1'
      }
    },
    // 字典值-规章制度文件名称
    async getRulesFileNameDictFn () {
      const res = await getRulesFileNameDict()
      if (res.data.code === 0) {
        this.rulesFileNameDict = res.data.data || []
        this.getDeptRulesListFn()
      }
    },
    // 查询部门规章制度列表
    async getDeptRulesListFn () {
      const res = await getDeptRulesList()
      if (res.data.code === 0) {
        this.deptRulesList = res.data.data || []
        this.initData()
      }
    },
    beforeFileUpload (file) {
      if (!this.fileTypeLimit.includes(file.type)) {
        this.$message.warning('不支持的文件格式');
        return false
      }
    },
    beforeFileRemove (file, _fileList) {
      if (file.status === 'success') {
        return this.$confirm(`确定移除 ${ file.name }？`);
      }
    },
    removeFileFn (url, index, itemName) {
      this.importFileObj[itemName].splice()
      this.$confirm(`确定移除${url}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.importFileObj[itemName].splice(index, 1)
      }).catch(() => {})
    },
    handleFileRemove (file, _fileList, ruleIdx) {
      const delIdx = this.importFileObj[ruleIdx].findIndex(ele => ele.url === file.url)
      this.importFileObj[delIdx].splice(1, 1)
    },
    handleFileSuccess (res, file, fileList, ruleIdx) {
      if (res.code === 0) {
        this.$set(this.importFileObj, ruleIdx, [...this.importFileObj[ruleIdx], { name: file.name, url: res.data.url }])
        this.$message.success('上传成功！')
      }
    },
    handleFileError () {
      this.$message.error('上传失败！')
    },
    viewImgFn (fileItem) {
      this.viewerList = [fileItem.url]
      this.showViewer = true
    },
    closeViewer () {
      this.showViewer = false
    },
    // 下载文件
    downloadFn (item) {
      request({
        url: item.url,
        method: 'get',
        responseType: 'blob'
      }).then((response) => { // 处理返回的文件流
        const blob = response.data
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = item.name
        document.body.appendChild(link)
        link.click()
        window.setTimeout(function() {
          URL.revokeObjectURL(blob)
          document.body.removeChild(link)
        }, 0)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.rules-page {
 .rules-tit {
  display: flex;
  align-items: center;
  span {
    font-size: 12px;
    margin-left: 10px;
  }
 }
  .save-btn {
    position: fixed;
    top: 130px;
    right: 24px;
    z-index: 1000;
  }
  .rules-item {
    padding: 24px;
    border: 1px dashed #cccccc;
    margin-bottom: 16px;
    .rules-title {
      font-size: 16px;
      font-weight: bolder;
    }
    .file-list {
      margin-top: 12px;
      .file-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .file-item-name {
          color: #606266;
        }
        &:hover {
          background-color: #f5f7fa;
          .file-item-name {
            color: #2d8cf0;
          }
        }
        .file-item-right {
          .file-item-view {
            &:hover {
              color: #2d8cf0;
            }
          }
          .el-icon-close {
            &:hover {
              color: #606266;
            }
          }
        }
      }
    }
  }
}
</style>
