<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
	    <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
        {{rcName}}
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-folder-add"
          size="mini"
          @click="handleAdd"
        >新建文件夹</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-upload2"
          size="mini"
          @click="handleAddFile"
        >上传文件</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="rcfileList"
      row-key="id"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column :label="$t('文件名')" width="500" align="left" prop="fileName" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <a v-if="scope.row.fileType == 1"  class="link-type"  @click="handleDownload(scope.row)">
            <span>{{ scope.row.fileName }}</span>
          </a>
          <span v-else-if="scope.row.fileType == 0" >{{ scope.row.fileName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="80" align="center" prop="fileType" >
        <template slot-scope="scope">
          <i v-if="scope.row.fileType == 1" class="el-icon-document"></i>
          <i v-else-if="scope.row.fileType == 0" class="el-icon-folder"></i>
        </template>
      </el-table-column>

      <el-table-column label="创建人" align="center" prop="creator" />
      <el-table-column label="创建时间" align="center" prop="createdate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="更新人" align="center" prop="updaterCode" />-->
<!--      <el-table-column label="更新时间" align="center" prop="updatedate" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.updatedate, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="备注" align="center" prop="remarks" />-->
<!--      <el-table-column label="业务类型" align="center" prop="pType" />-->
      <el-table-column label="文件大小(Kb)" width="100" align="center" prop="fileSize" />
<!--      <el-table-column label="父类ID" align="center" prop="parentId" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.fileName.endsWith('pdf') && scope.row.fileType == 1"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleSee(scope.row)"
          >{{ $t('预览') }}</el-button>
          <el-button
            v-if="scope.row.fileType == 1"
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
          >{{ $t('下载') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog  :close-on-click-modal="false" v-dialogDrag :title="pdf.title" :visible.sync="pdf.open" width="1300px" append-to-body>
      <div style="margin-top: -60px;float: right;margin-right: 40px;">
        <el-button size="mini" type="text" @click="openPdf">{{$t('新页面打开PDF')}}</el-button></div>
      <div style="margin-top: -30px">
        <iframe :src="pdf.pdfUrl" frameborder="0" width="100%" height="700px"></iframe>
      </div>
    </el-dialog>
    <!-- 添加或修改RC附件对话框 -->
    <el-dialog :title="doc.title" :visible.sync="doc.open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-upload
          ref="doc"
          :limit="50"
          :headers="doc.headers"
          :action="doc.url + '?parentId=' + form.parentId + '&pId=' + doc.pId "
          :disabled="doc.isUploading"
          :on-progress="handleFileDocProgress"
          :on-success="handleFileDocSuccess"
          :auto-upload="true"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            {{ $t('将文件拖到此处，或') }}
            <em>{{ $t('点击上传') }}</em>
          </div>
        </el-upload>

        <el-form-item label="上级" prop="parentId">
          <treeselect v-model="form.parentId" :options="rcfileOptions" :normalizer="normalizer" placeholder="请选择文件夹" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFile">确 定</el-button>
        <el-button @click="doc.open = false">返 回</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改RC附件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item v-if="form.fileType != 1" label="文件夹" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名" />
        </el-form-item>

        <el-form-item label="上级" prop="parentId">
          <treeselect v-model="form.parentId" :options="rcfileOptions" :normalizer="normalizer" placeholder="请选择文件夹" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRcfile, getRcfile, delRcfile, addRcfile, updateRcfile, exportRcfile } from "@/api/ehs/rcfile";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getToken} from "@/utils/auth";
import {addFile, getRcaudit} from "@/api/ehs/rcaudit";

export default {
  name: "Rcfile",
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: false,
      // RC附件表格数据
      rcfileList: [],
      // RC附件树选项
      rcfileOptions: [],
      // 弹出层标题
      title: "",
      rcName: "",
      // 是否显示弹出层
      open: false,
      pId: null,
      // 查询参数
      queryParams: {
        fileName: null,
        pId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "id不能为空", trigger: "blur" }
        ],
      },
      pdf : {
        title: '',
        pdfUrl: '',
        numPages: null,
        open: false,
        pageNum: 1,
        pageTotalNum: 1,
        loadedRatio: 0,
      },
      // 报告附件参数
      doc: {
        file: "",
        // 是否显示弹出层（报告附件）
        open: false,
        // 弹出层标题（报告附件）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 报告附件上传位置编号
        ids: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/ehs/rcfile/uploadFile",
        commonfileList: null,
        queryParams: {
          pId: null,
          pType: 'rcaudit'
        },
        pType: 'rcaudit',
        pId: null
      },
    };
  },
  created() {
    const pId = this.$route.params && this.$route.params.id;
    this.pId = pId
    this.doc.pId = pId;
    this.getList();
    getRcaudit(pId).then(response => {
      this.rcName =response.data.rcCode + "    " + response.data.nameCn;
      ;
    });
  },
  methods: {
    /** 查询RC附件列表 */
    getList() {
      this.loading = true;
      this.queryParams.pId = this.pId
      listRcfile(this.queryParams).then(response => {
        this.rcfileList = this.handleTree(response.data, "id", "parentId");
        this.loading = false;
      });
    },
    /** 转换RC附件数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.fileName,
        children: node.children
      };
    },
	/** 查询部门下拉树结构 */
    getTreeselect() {
      let param = {}
      param.pId= this.pId
      param.fileType = 0
      listRcfile(param).then(response => {
        this.rcfileOptions = [];
        const data = { id: 0, fileName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.rcfileOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        pId: null,
        fileName: null,
        fileUrl: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        remarks: null,
        pType: null,
        fileSize: null,
        pValue: null,
        pDate: null,
        fileType: null,
        parentId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
	  this.getTreeselect();
      this.open = true;
      this.title = "添加RC附件";
    },
    handleAddFile() {
      this.reset();
      this.getTreeselect();
      this.form.parentId = 0
      this.doc.open = true;
      this.$nextTick(() => {
        this.$refs.doc.clearFiles()
      })
      this.doc.title = "添加RC附件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
	  this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.id;
      }
      getRcfile(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改RC附件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRcfile(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.pId = this.pId
            addRcfile(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitFile(){
      this.doc.open = false;
      this.getList();
    },
    // 文件下载处理
    handleDownload(row) {
      var name = row.fileName;
      var url = row.fileUrl;
      var suffix = url.substring(url.lastIndexOf("."), url.length);
      const a = document.createElement('a')
      a.setAttribute('download', name)
      a.setAttribute('target', '_blank')
      a.setAttribute('href', process.env.VUE_APP_BASE_API + url)
      a.click()
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除RC附件编号为"' + row.id + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRcfile(row.id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    //附件上传中处理
    handleFileDocProgress(event, file, fileList) {
      this.doc.file = file;
      this.doc.isUploading = true;
    },
    //附件上传成功处理
    handleFileDocSuccess(response, file, fileList) {
      this.doc.isUploading = false;
      this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true });
      this.form.id = this.doc.pId;
      // addFile(this.form)
      this.$refs.upload.clearFiles();
      this.getList()
    },
    handleSee (row){
      this.pdf.open =true
      this.pdf.title = row.fileName
      this.pdf.pdfUrl = process.env.VUE_APP_BASE_API +'/pdf/web/viewer.html?file=' + process.env.VUE_APP_BASE_API + row.fileUrl
    },
    //pdf预览
    openPdf(){
      window.open(this.pdf.pdfUrl);//path是文件的全路径地址
    },
  }
};
</script>
