<!--文件上传组件-->
<template>
  <div style="display: inline-block;">
    <el-button style="margin-top: -4px;margin-left: 5px;" type="primary" size="default" @click="handleOpen"> 从资料库中选择
    </el-button>

    <el-dialog append-to-body title="个人资料库" @open="handleOpenDialog" :close-on-click-modal="false" draggable
      width="900px" @close="close" @keyup.enter.native="" v-model="visible">
      <el-form :inline="true" class="query-form m-b-10" ref="searchForm" :model="searchForm"
        @keyup.enter="refreshList()" @submit.prevent>
        <!-- 搜索框-->
        <el-form-item prop="fileName" label="附件名称">
          <el-input style="width: 200px;" v-model="searchForm.fileName" placeholder="请输入附件名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading" type="primary" @click="refreshList()" icon="search">查询</el-button>
          <el-button :loading="loading" type="default" @click="resetSearch()" icon="refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="jp-table">
        <div class="jp-table-body">
          <vxe-table border="inner" auto-resize resizable :loading="loading" size="small" ref="dataSetTable"
            show-header-overflow show-overflow highlight-hover-row :menu-config="{}" :print-config="{}"
            :import-config="{}" :export-config="{}" @sort-change="sortChangeHandle" :sort-config="{ remote: true }"
            :data="dataList" :checkbox-config="{}" @checkbox-all="selectAllChangeEvent"
            @checkbox-change="selectChangeEvent">
            <vxe-column type="checkbox" width="60"></vxe-column>
            <vxe-column type="seq" width="40"></vxe-column>

            <vxe-column field="fileName" sortable title="附件名称">
              <template #default="scope">
                <div>
                  <el-link type="primary" :underline="false" @click="showFile(scope.row)">{{ scope.row.fileName
                    }}</el-link>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="classification" sortable title="收藏分类">
            </vxe-column>
            <vxe-column field="fileDescription" sortable title="文件描述">
            </vxe-column>
            <vxe-column field="userName" sortable title="上传人">
            </vxe-column>
            <vxe-column field="collectUserName" sortable title="收藏人">
            </vxe-column>
            <vxe-column field="createTime" sortable title="上传/收藏时间">
            </vxe-column>
          </vxe-table>
          <vxe-pager background size="small" :current-page="tablePage.currentPage" :page-size="tablePage.pageSize"
            :total="tablePage.total" :page-sizes="[
              10,
              20,
              100,
              1000,
              { label: '全量数据', value: 1000000 },
            ]" :layouts="[
              'PrevPage',
              'JumpNumber',
              'NextPage',
              'FullJump',
              'Sizes',
              'Total',
            ]" @page-change="currentChangeHandle">
          </vxe-pager>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close()" icon="el-icon-circle-close">关闭</el-button>
          <el-button type="primary" :loading="loading" v-if="method != 'view'" @click="doSubmit()"
            icon="el-icon-circle-check" v-noMoreClick>确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-image-viewer hide-on-click-modal v-if="showViewer" @close="closeViewer" :url-list="[url]" zIndex="9999" />

  </div>
</template>

<script>
import OSSSerivce, {
  openWindowOnUrl,
} from '@/api/sys/OSSService'
import workCollectAccessoryService from "@/api/workCollectAccessory/index"
export default {
  props: {
    directory: {
      required: true, // 表示该属性是必传的
      type: String    // 数据类型为字符串
    },
    formatList: {
      type: Array,     // 数据类型为数组
      default: () => []
    }
  },
  data() {
    return {
      url: "",
      showViewer: false,
      ossService: null,
      visible: false,
      inputForm: {

      },
      searchForm: {
        createById: '',
      },
      dataList: [],
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        orders: [],
      },
      loading: false,
      userInfo: {},
      selectRow: null,
      selectList: []
    }
  },
  watch: {
  },
  created() {
    this.ossService = new OSSSerivce()

  },
  components: {
  },
  mounted() {
  },
  methods: {
    ifName(row) {
      if (this.commonJS.isEmpty(row.fileName)) {
        row.fileName = '---'
        return false
      }
      let suffix = row.fileName.substring(row.fileName.lastIndexOf('.') + 1)
      if (suffix === 'jpg' || suffix === 'png' || suffix === 'gif' || suffix === 'bmp' || suffix === 'jpeg') {
        return true
      } else {
        return false
      }
    },
    // 关闭查看器
    closeViewer() {
      this.url = ''
      this.showViewer = false
    },
    onPreview(url) {
      this.url = url
      this.showViewer = true
    },
    // 预览文件
    showFile(row) {
      if (this.ifName(row)) {
        this.ossService.getTemporaryUrl(row.url).then((data) => {
          this.onPreview(data)
        })
      } else {
        console.log(2);
        let obj = {
          name: row.fileName,
          url: row.url
        }
        openWindowOnUrl(obj)
      }

    },
    hasDuplicateName(arr) {
      const names = new Set();
      for (const obj of arr) {
        if (names.has(obj.fileName)) {
          return true; // 有重复的 name
        }
        names.add(obj.fileName);
      }
      return false; // 没有重复的 name
    },
    doSubmit() {
      let flag = this.hasDuplicateName(this.selectList)
      if (flag) {
        this.$message.error(`请勿选择相同名称文件进行上传`);
        return
      }
      if (this.selectList.length == 0) {
        this.$message.error(`请选择文件后上传`);
        return
      }
      this.selectList.forEach(selectRow => {
        let fileName = selectRow.fileName;
        let fileType = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); // 获取后缀并转小写
        if (this.formatList.length && !this.formatList.includes(fileType)) {
          this.$message.error(`只能上传 ${this.formatList.join(", ")} 格式的文件`);
          return;
        }
        this.ossService.getTemporaryUrl(selectRow.url).then((data) => {
          workCollectAccessoryService
            .downloadAndUploadToOSS({
              url: data,
              fileName: selectRow.fileName,
              dir: this.directory
            }).then(res => {
              this.$emit("onDownToOss", selectRow, res)
              this.visible = false
            })
        })
      })

    },
    resetSearch() {
      this.$refs.searchForm.resetFields();
      this.refreshList();
    },
    selectAllChangeEvent({ checked }) {
      if (this.$refs.dataSetTable) {
        const records = this.$refs.dataSetTable.getCheckboxRecords()
        console.log(records);
        this.selectList = [...records]

      }
    },
    selectChangeEvent({ checked }) {
      if (this.$refs.dataSetTable) {
        const records = this.$refs.dataSetTable.getCheckboxRecords()
        console.log(records);
        this.selectList = [...records]
      }
    },
    radioChangeEvent({ row }) {
      this.selectRow = row
    },
    clearRadioRowEevnt() {
      if (this.$refs.dataSetTable) {
        this.selectRow = null
        this.$refs.dataSetTable.clearRadioRow()
      }
    },
    handleOpen() {
      this.visible = true
    },
    handleOpenDialog() {
      this.userInfo = this.$TOOL.data.get("USER_INFO");
      this.searchForm.createById = this.userInfo.id
      this.refreshList();
    },
    close() {
      this.clearRadioRowEevnt()
      this.visible = false
    },
    // 当前页
    currentChangeHandle({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage;
      this.tablePage.pageSize = pageSize;
      this.refreshList();
    },
    // 获取数据列表
    refreshList() {
      this.loading = true;
      workCollectAccessoryService
        .list({
          current: this.tablePage.currentPage,
          size: this.tablePage.pageSize,
          orders: this.tablePage.orders,
          ...this.searchForm,
        })
        .then((data) => {
          this.dataList = data.records;
          this.tablePage.total = data.total;
          this.loading = false;
        });
    },
    // 排序
    sortChangeHandle(column) {
      this.tablePage.orders = [];
      if (column.order != null) {
        this.tablePage.orders.push({
          column: this.$utils.toLine(column.property),
          asc: column.order === "asc",
        });
      }
      this.refreshList();
    },
  }
}
</script>
<style></style>
