<template>
  <div class="common-page-shadow">
    <div class="common-search-container" ref="contentPanel">
      <el-form
        ref="form"
        label-position="right "
        :inline="true"
        type="flex"
        justify="left"
      >
        <el-form-item label="资质类别编码">
          <el-input
            size="small"
            v-model="querys[0].value"
            clearable
            placeholder="请输入资质类别编码"
          ></el-input>
        </el-form-item>
        <el-form-item label="资质类别名称">
          <el-input
            size="small"
            v-model="querys[1].value"
            clearable
            placeholder="请输入资质类别名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="container-btn">
        <el-button
          size="small"
          icon="el-icon-search"
          type="danger"
          class="btn btn-plus"
          @click="handleSearch"
        >
          搜索
        </el-button>
        <el-button
          size="small"
          icon="el-icon-refresh-right"
          class="btn btn-plus"
          @click="clearSearchForm"
        >
          重置
        </el-button>
      </div>
    </div>
    <el-row
      class="common-table-container flex searchPanel"
      :style="SearchPanel"
    >
      <el-col :span="24" class="common-table-wrapper">
        <div class="common-btn-group">
          <el-button
            size="small"
            icon="el-icon-plus"
            type="primary"
            class="btn btn-plus"
            @click="handleAdd"
          >
            新增
          </el-button>
          <el-button
            :disabled="handleDeleteActive"
            size="small"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete"
          >
            删除
          </el-button>
        </div>
        <!-- LJ：表格高度自适应需配合样式  btn-pagenation 有按钮有分页  btngroup只有按钮  pagenation只有分页 -->
        <div class="common-table-content btn-pagenation" ref="tableContent">
          <el-table
            :border="true"
            stripe
            fit
            size="mini"
            :max-height="tableHeight"
            v-loading="tableLoading"
            ref="multipleSelection"
            :data="tableData"
            @selection-change="handleSelectionChange"
            @row-dblclick="handleDetail"
          >
            <el-table-column type="selection" min-width="20%" align="center">
            </el-table-column>
            
            <el-table-column
              prop="qualificationMember"
              show-overflow-tooltip
              min-width="130px"
              align="center"
              label="所属权"
              resizable
            >
            </el-table-column>
            <el-table-column
              prop="qualificationCode"
              show-overflow-tooltip
              min-width="110px"
              align="center"
              label="资质编码"
              resizable
            >
            </el-table-column>
            <el-table-column
              prop="qualificationName"
              show-overflow-tooltip
              min-width="100px"
              align="center"
              label="资质名称"
              resizable
            >
            </el-table-column>

            <el-table-column
              prop="qualificationTypeName"
              show-overflow-tooltip
              min-width="100px"
              align="center"
              label="资质类型"
              resizable
            >
            </el-table-column>
            <el-table-column
              prop="qualificationForm"
              min-width="100px"
              label="所属权分类"
              align="center"
              resizable
            >
              <template slot-scope="scope">
                <div>
                  <span v-if="scope.row.qualificationForm == 1">企业</span>
                  <span v-if="scope.row.qualificationForm == 2">专家</span>
                  <span v-if="scope.row.qualificationForm == 3">个人</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="qualificationAcquisitionDate"
              show-overflow-tooltip
              min-width="120px"
              align="center"
              label="有效开始期"
              resizable
            >
            </el-table-column>
            <el-table-column
              prop="expiryDate"
              show-overflow-tooltip
              min-width="120px"
              align="center"
              label="有效截止期"
              resizable
            >
            </el-table-column>
            <el-table-column min-width="130px" align="center" label="操作">
              <template v-slot="{row}">
                <template>
                  <el-button
                    icon="el-icon-edit"
                    type="primary"
                    plain
                    size="small"
                    @click="handleEdit(row)"
                    >编辑</el-button
                  >
                  <el-button
                    icon="el-icon-tickets"
                    type="primary"
                    plain
                    :loading="row.loading"
                    size="small"
                    @click="handleRecording(row)"
                    >资质预览</el-button
                  >
                </template>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="common-pagenation">
          <el-pagination
            ref="paginationPanel"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryParam.pageBean.page"
            :page-sizes="[20, 30, 40, 50]"
            :page-size="queryParam.pageBean.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryParam.pageBean.total"
          >
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog
      title="资质附件预览"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="dialogBeforeClose"
    >
      <div>
        <el-table
          class="down"
          :data="accessoryList"
          border
          stripe
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column prop="name" label="文件名称"></el-table-column>
          <el-table-column prop="size" label="文件大小">
            <template slot-scope="scope">
              <span>{{ scope.row.fileSize }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="上传时间">
            <template slot-scope="scope">
              <div>
                {{ scope.row.createTime }}
              </div>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="操作">
            <template slot-scope="scope">
              <el-button type="text">
                <a target="_blank" @click="clickPreView(scope.row)">预览</a>
              </el-button>

              <el-button size="small" type="text">
                <a
                  target="_blank"
                  @click="downloadFile(scope.row.name, scope.row.url)"
                  >下载</a
                >
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <ImgPreviewDialog ref="imgPre"></ImgPreviewDialog>
  </div>
</template>

<script>
import pagination from '@/components/pagination'
import {TableMixin} from '@/mixins/tableMixin'
import basicData from '@/api/basicData'
import ImgPreviewDialog from '@/components/dialog/ImgPreviewDialog.vue'
export default {
  name: 'DemandEntry',
  components: {
    pagination,
    ImgPreviewDialog
  },
  mixins: [TableMixin],
  data() {
    return {
      tableData: [],
      tableHeight: 1000,
      handleDeleteActive: true,
      handleDeleteId: [],
      visible: false,
      accessoryList: [],
      tableLoading: false,
      show: false,
      pdfUrl: '',
      imgUrl:'',
      currentUser:{},
      dialogVisible: false,
      queryParam: {
        pageBean: {
          page: 1,
          pageSize: 20,
          total: 0,
        },
        sorter: [
          {
            direction: 'DESC',
            property: 'create_time_',
          },
        ],
      },
      querys: [
        {
          group: 'main',
          operation: 'LIKE',
          parentGroup: '',
          property: 'qualificationTypeValue',
          relation: 'AND',
          value: '',
        },
        {
          group: 'main',
          operation: 'LIKE',
          parentGroup: '',
          property: 'qualificationTypeName',
          relation: 'AND',
          value: '',
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'qualificationForm',
          relation: 'AND',
          value: '3',
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'qualificationMemberId',
          relation: 'AND',
          value: '',
        }
      ],
    }
  },
  mounted() {
    //页面缩放从新计算表格的高度
    window.addEventListener('resize', this.calcTableHeight)
  },
  created() {
    this.currentUser = JSON.parse(sessionStorage.getItem('currentUserDetail'))
    this.querys[3].value = this.currentUser.user.userId
    this.loadData()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calcTableHeight)
  },
  methods: {
    // 动态计算表格的高度，自适应当前容器
    calcTableHeight() {
      this.tableHeight = this.$refs.tableContent.offsetHeight
    },
    //字典翻译
    getDictName(code, value) {
      return utils.getDictName(code, value)
    },
    //获取数据
    loadData() {
      this.tableLoading = true
      this.queryParam.querys = []
      if (this.querys[0].value) {
        this.queryParam.querys.push(this.querys[0])
      }
      if (this.querys[1].value) {
        this.queryParam.querys.push(this.querys[1])
      }
      if (this.querys[2].value) {
        this.queryParam.querys.push(this.querys[2])
      }
      if (this.querys[3].value) {
        this.queryParam.querys.push(this.querys[3])
      }
      basicData.bizQualificationLabelQuery(this.queryParam).then((res) => {
        this.queryParam.pageBean.total = res.value.total
        this.tableLoading = false
        this.tableData = res.value.rows
        this.tableData.forEach((item) => {
          this.$set(item, 'loading', false)
        })
      })
    },
    //添加
    handleAdd() {
      this.$router.push('libraryAddDialog')
    },
    // 编辑
    handleEdit(rows) {
      this.$refs.form.clearValidate()
      this.$router.push({
        name: 'libraryAddDialog',
        query: {editRows: rows, pageBean: this.queryParam},
      })
    },
    // 详情
    handleDetail(rows) {
      this.$router.push({
        name: 'libraryDetail',
        query: {detailRows: rows, pageBean: this.queryParam},
      })
    },
    // 资质库变更记录
    handleRecording(rows) {
      rows.loading = true
      this.$http
        .post('${portal}/bizQualificationLabel/v1/getById?id=' + rows.id)
        .then((res) => {
          console.log(res)
          if (res.data.state) {
            this.accessoryList = res.data.value.accessoryList
          }
          this.dialogVisible = true
          rows.loading = false
        })
    },
    //下载按钮回调
    downloadFile(name, url) {
      console.log(name, 'name')
      var a = document.createElement('a')
      var event = new MouseEvent('click')
      a.download = name
      a.target = '_blank'
      a.href = url
      a.dispatchEvent(event)
    },
    // 预览
    clickPreView(row) {
      //".rar, .zip, .doc, .docx, .xls, .txt, .pdf, .jpg, .png, .jpeg,"
      if (
        row.suffix === 'doc' ||
        row.suffix === 'docx' ||
        row.suffix === 'xls' ||
        row.suffix === 'xlsx'
      ) {
        window.open(row.url)
      }else if(row.suffix === 'pdf'){
        fetch(row.url)
        // val为传入的pdf下载地址链接
          .then((response) => response.blob())
          .then((res) => {
            let blob = new Blob([res], { type: "application/pdf" });
            // pdfurl即转化后的结果
            let pdfurl = window.URL.createObjectURL(blob);
            // 新标签页打开，即可预览并下载
            window.open(pdfurl);
          });
      
      } else if (row.suffix === 'txt') {
        window.open(row.url)
      } else if (['png', 'jpg', 'jpeg'].includes(row.suffix)) {
        this.imgUrl = row.url
        this.$refs.imgPre.open(this.imgUrl)
      } else if (row.suffix === 'rar' || row.suffix === 'zip') {
        this.$message({
          message: '该文件类型暂不支持预览',
          type: 'warning',
        })
        return false
      }
    },
    // 删除
    handleDelete() {
      this.$confirm('确定删除选中数据？', '提示', {
        confirmButtonText: '确 定',
        cancelButtonText: '取 消',
        type: 'warning',
      })
        .then(() => {
          basicData
            .bizQualificationLabelRemove(this.handleDeleteId)
            .then((res) => {
              if (res.state) {
                this.$notify({
                  type: 'success',
                  message: '删除成功',
                  duration: 2000,
                })
                this.loadData()
              }
            })
            .catch((res) => {
              this.$notify({
                type: 'error',
                message: res.message,
                duration: 2000,
                offset: 80,
              })
            })
        })
        .catch(() => {})
    },
    //重置
    clearSearchForm() {
      this.querys[0].value = ''
      this.querys[1].value = ''
      this.querys[2].value = '3'
      this.querys[3].value = this.currentUser.user.userId
      this.loadData()
    },
    // 顶部搜索
    handleSearch() {
      this.loadData()
    },
    dialogBeforeClose() {
      this.dialogVisible = false
    },
    handleSelectionChange(val) {
      if (val.length !== 0) {
        this.handleDeleteActive = false
        this.handleDeleteId = val.map((item) => {
          return item.id
        })
      } else {
        this.handleDeleteActive = true
      }
    },
    handleCurrentChange(page) {
      this.queryParam.pageBean = {...this.queryParam.pageBean, page}
      this.loadData()
    },
    handleSizeChange(pageSize) {
      this.queryParam.pageBean = {...this.queryParam.pageBean, pageSize}
      this.loadData()
    },
  },
  computed: {
    SearchPanel() {
      return {
        '--searchPanel': this.searchPanel + 'px',
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.cloumn-btn {
  border: 1px solid #2761ff;
  padding: 3px 10px;
  border-radius: 5px;
  &:nth-child(1) {
    margin-right: 5px;
  }
  &:nth-child(2) {
    margin-right: 5px;
  }
  &:nth-child(1):hover {
    background-color: #2761ff;
    color: #fff;
  }
  &:nth-child(2):hover {
    background-color: #2761ff;
    color: #fff;
  }
  // &:nth-child(2):hover {
  //   background-color: #f56c6c;
  //   color: #fff;
  //   border-color: #f56c6c;
  // }
  /deep/ i,
  span {
    font-size: 16px;
  }
}

/deep/ .el-tree-node__content {
  padding: 5px 0;
}

/deep/ .el-table thead tr th {
  background-color: #eee !important;
  border-right: 1px solid #dfe2e8 !important;
}
/deep/ .el-table {
  border-collapse: collapse !important;
}
</style>
