<template>
  <div class="app-container">
    <!-- 上传文件窗口 -->
    <el-dialog
      title="上传文件"
      :visible.sync="picModal"
      :close-on-click-modal="false"
    >
    <el-form ref="formInfo" label-width="120px" :model="dialog1Data" :rules="folderRules">
      <el-form-item label="所属企业" prop="enterpriseId">
        <el-select
          v-model="dialog1Data.enterpriseId"
          placeholder="请选择企业"
          disabled
        >
          <el-option
            v-for="item in options4enterpriseIdList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="dialog1Data.type"
          placeholder="请选择类型"
        >
          <el-option
            v-for="item in options4type"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文件名称">
        <el-input
          v-model="dialog1Data.fileName"
          placeholder="请输入文件名称"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="上传文件" prop="floorPlanPath">
          <el-upload
            class="upload-demo"
            :action="`${previewUrl}/api/file/upload`"
            multiple
            :headers="httpHeaders"
            accept=".png,.jpg,jpeg"
            :limit="1"
            :on-success="upFloorPlanSuccess"
            :on-remove="upFloorPlanRemove"
            :on-error="upFloorPlanError"
            :on-exceed="upFloorPlanExceed"
            :before-upload="upFloorPlanBefore"
            :on-preview="openFile"
            :file-list="dialog1Data._fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过20M</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="">
          <div v-for="(item, index) in uploadedFiles" :key="item.name + index">
            {{ item.name }}
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="picModal = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmFolder"
          :loading="modalBtnLoad"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <el-row>
      <!--角色管理-->
      <el-col :span="24">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-button type="primary" size="mini" @click="showpicModal"
              >上传</el-button
            >
          </div>
          <el-table ref="table" style="width: 100%" :data="dataList">
            <el-table-column type="" width="55" />
            <el-table-column prop="enterpriseName" label="所属企业" width="400" />
            <el-table-column
              label="类型"
              prop="typeName"
              width="200"
            />
            <el-table-column width="400px" prop="fileName" label="文件名称" />
            <!-- <el-table-column width="200px" prop="createTime" label="上传时间" /> -->
            <el-table-column label="操作" width="230px" align="left">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click="updateFolder(scope.row)"
                  >修改</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  @click="delFolder(scope.row)"
                  >删除</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  @click="previewFile(scope.row)"
                  >预览</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <el-pagination
            :current-page="page"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalElement"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
  
  <script>
   import request from '@/utils/request'
import picApi from "@/api/picManage/pic.js";
import DateRangePicker from "@/components/DateRangePicker";
import { getToken } from "@/utils/auth";
import {getCompanyList} from '@/api/system/user'
import axios from "axios";

export default {
  name: "Folder",
  components: {
    DateRangePicker,
  },
  data() {
    return {
      previewUrl: process.env.VUE_APP_LOCAL_API,
      dialog1Data:{},
      httpHeaders: {
        'Authorization': getToken()
      },
      enterpriseId: '',
      type: '',
      options4enterpriseIdList: [],
      options4type:[{
        name: '矿山全景',
        id: 1
      },{
        name: '资源储量',
        id: 2
      },{
        name: '开发利用',
        id: 3
      },{
        name: '地质环境',
        id: 4
      },{
        name: '绿色矿山',
        id: 5
      },{
        name: '水监测',
        id: 6
      },{
        name: '土监测',
        id: 7
      }],
      dialogVisible4: false,
      pdfSrc: "",
      modalBtnLoad: false,
      query: {
        originallyName: "",
        classification: "",
        time: "",
      },
      picModal: false,
      fileType: "",
      picModal: false,
      uploadedFiles: [],
      selectedFolderId: "",
      selectedFolderId: "",
      selectedFolderInfo: {},
      dataList: [],
      totalElement: 0,
      page: 0,
      size: 10,
      defaultProps: { children: "children", label: "name", isLeaf: "leaf" },
      level: 3,
      currentId: 0,
      currentName: "",
      menuLoading: false,
      showButton: false,
      menus: [],
      menuIds: [],
      folderRules: {
        enterpriseId: [{ required: true, message: "请选择企业", trigger: "blur" }],
        type: [{ required: true, message: "请选择类型", trigger: "blur" }],
      },
    };
  },
  computed: {},
  mounted() {
    this.getCompanyList(); // 获取所有文件夹
    this.getData();
  },
  created() {},
  methods: {
    upFloorPlanSuccess(response, file, fileList) {
      if (!this.dialog1Data._fileList) {
        this.dialog1Data._fileList = []
      }
      this.dialog1Data._fileList.push({
        name: file.name,
        url: response.result
      })
      this.dialog1Data.filePath = response.result || ''
    },
    upFloorPlanError() {
      this.$message.error('上传失败，请稍后再试')
    },
    upFloorPlanRemove() {
      this.$set(this.dialog1Data, '_fileList', [])
      this.dialog1Data.filePath = ''
    },
    upFloorPlanBefore(file) {
      const isIMG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLtSize = file.size / 1024 / 1024 < 20
      if (!isIMG) {
        this.$message.error('上传图片只能是 JPG/JPEG/PNG 格式')
        return false
      }
      if (!isLtSize) {
        this.$message.error('上传图片大小不能超过 20MB')
        return false
      }
      return true
    },
    upFloorPlanExceed() {
      this.$message.error('您已经上传了一张图，请删除后重新上传')
    },
    openFile(file) {
      if (file.url) {
        window.open(this.previewUrl + '/file' + file.url)
      } else if (file.response && file.response.result) {
        window.open(this.previewUrl + '/file' + file.response.result)
      }
    },
    previewFile(item) {
      if (item.filePath) {
        window.open(this.previewUrl + '/file' + item.filePath)
      }
    },
    getCompanyList(){
      request({
        url: 'api/enterprise/auth/enterpriseList',
        method: 'get',
        params:{
        }
      }).then((res)=>{
        this.options4enterpriseIdList = res.body || []
      })
    },
    showpicModal() {
      this.picModal = true;
      this.dialog1Data = {}
      // this.dialog1Data.filePath = '';
      // this.dialog1Data.id = ''
      // this.dialog1Data.enterpriseId = ''
      // this.dialog1Data.type = ''
      this.dialog1Data._fileList = []
      // 右上角全局公司值设置
      this.dialog1Data.enterpriseId = localStorage.getItem('currGlobalCompId')?localStorage.getItem('currGlobalCompId') * 1:''
   
    },
   
    // 当前页的条数变化
    handleSizeChange(val) {
      this.size = val;
      this.getData();
    },
    // 当前第几页
    handleCurrentChange(val) {
      this.page = val;
      this.getData();
    },
    confirmFolder() {
      if(!this.dialog1Data.filePath){
        this.$message.warning("请上传图片");
        return
      }
      this.$refs["formInfo"].validate((valid) => {
        if (valid) {
          if (this.modalBtnLoad) {
            return;
          }
          this.modalBtnLoad = true;
          if (this.dialog1Data.id) {
            // 修改
            picApi
              .mod({
                ...this.dialog1Data,
              })
              .then((res) => {
                this.picModal = false;
                this.$message.success("操作成功");
                this.getData();
              });
          } else {
            // 新增
            picApi
              .add({
                ...this.dialog1Data,
              })
              .then((res) => {
                this.picModal = false;
                this.$message.success("操作成功");
                this.getData();
              });
          }
          this.modalBtnLoad = false;
        }
      });
    },

    addFolder() {
      // if (!this.selectedFolderId) {
      //   this.$message.warning("请选择文件夹");
      //   return;
      // }
      this.picModal = true;
      this.dialog1Data = { id: "", enterpriseId: "", type: '' };
    },
    delFolder(item) {
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(
        () => {
          picApi.del([item.id]).then((res) => {
            this.$message.success("操作成功");
            this.getData();
          });
        },
        () => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        }
      );
    },
    updateFolder(item) {
      this.picModal = true;
      this.dialog1Data.id = item.id;
      this.dialog1Data.enterpriseId = item.enterpriseId;
      this.dialog1Data.type = item.type;
      this.dialog1Data.filePath = item.filePath
      this.dialog1Data.fileName = item.fileName
      this.dialog1Data._fileList = [{
        name: item.filePath,
        url: item.filePath
      }]
    },
    search() {
      this.getData();
    },
    getData() {
      picApi
        .getkdFile({
          page: this.page,
          size: this.size,
        })
        .then((res) => {
          this.dataList = res.body.list;
          this.totalElement = res.body.total;
        });
    },
    confirmUploadFile() {
      if (!this.selectedFolderId) {
        this.$message.warning("请选择文件夹");
        return;
      }
      if (!this.uploadedFiles.length) {
        this.$message.warning("请上传文件");
        return;
      }
      if (this.modalBtnLoad) {
        return;
      }
      this.modalBtnLoad = true;
      const formData = new FormData();
      // console.log(this.formInfo.hdstatus1, "haStatus");
      formData.append("fileList", this.uploadedFiles[0]);
      formData.append("catalogueId", this.selectedFolderId);
      formData.append("classification", this.fileType);

      picApi.addFileByFolderId(formData).then((res) => {
        this.$message.success("操作成功");
        this.getData();
        this.$refs.addhdpic.value = "";
        this.fileType = "";
        this.picModal = false;
      });
      this.modalBtnLoad = false;
    },

  },
};
</script>
  
  <style rel="stylesheet/scss" lang="scss">
.role-span {
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}
</style>
  
  <style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
::v-deep .vue-treeselect__multi-value {
  margin-bottom: 0;
}
::v-deep .vue-treeselect__multi-value-item {
  border: 0;
  padding: 0;
}
</style>
  