<template>
  <el-config-provider :locale="zhCn">
    <el-container class="content">
      <div class="work-area">
        <fieldset class="search-area">
          <el-form ref="searchQueryFormRef" :model="searchQueryFormEntity"
                   :label-position="labelPosition" label-width="158px" style="max-width: 100%" status-icon>
            <div style="display: flex;justify-content: space-between;">
              <el-row>
                <el-form-item label="成品类型">
                  <el-select-v2 style="width: 196px" v-model="searchQueryFormEntity.imageType" placeholder="成品类型"
                                :options="addAllOptionOfOptions(kittingBomTypeOptions)"
                                @change="search()" />
                </el-form-item>
                <el-form-item label="成品号">
                  <el-input v-model="searchQueryFormEntity.productId" @keyup.enter="search()" clearable/>
                </el-form-item>
                <el-form-item label="料盒号">
                  <el-input v-model="searchQueryFormEntity.boxNo" @keyup.enter="search()" clearable/>
                </el-form-item>
              </el-row>
              <div style="align-content: center;">
                <el-row>
                  <el-button type="primary" class="btn-search" @click="search()">查询</el-button>
                  <el-button type="warning" class="btn-search" @click="clearQuery()">清除输入</el-button>
                </el-row>
              </div>
            </div>
          </el-form>
        </fieldset>
        <div class="table-area">
          <el-table :data="displayImageList" stripe border v-loading="tableLoading" class="table-class"
                    :max-height="maxHeight" highlight-current-row @row-click="getCurrentRow"
                    :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
                    @sort-change="handleSortChange">
            <el-table-column width="65px" fixed="left">
              <template v-slot="scope">
                <el-radio :label="scope.row.imageId" v-model="imageId">&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column prop="imageId" label="图纸id" fixed="left" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="imageType" label="成品类型" :formatter="imageTypeFormat" min-width="120px"
                             sortable="custom" show-overflow-tooltip/>
            <el-table-column prop="productId" label="成品号" min-width="120px" sortable="custom" show-overflow-tooltip/>
            <el-table-column prop="boxNo" label="料盒号" min-width="120px" sortable="custom" show-overflow-tooltip/>
            <el-table-column prop="imagePath" label="存放路径" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="imageName" label="图纸名称" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column fixed="right" label="操作" width="120px">
              <template v-slot="scope">
                <el-button plain type="primary" @click="requestPreview(scope.row)">预览</el-button>
              </template>
            </el-table-column>
          </el-table>
          <br/>
          <el-pagination v-model:current-page="baseTableQuery.currentPage"
                         v-model:page-size="baseTableQuery.pageSize" :page-sizes="[10, 25, 50]" :small="false"
                         :disabled="false" :background="false" :default-page-size="10" @size-change="search"
                         @current-change="search" layout="total, sizes, prev, pager, next, jumper"
                         :total="baseTableQuery.total"/>
        </div>
        <!-- 图片预览 -->
        <el-image-viewer v-if="showImagePreview" :zoom-rate="1.2" @close="closePreview" :url-list="imgPreviewList">
          <template #toolbar="{ actions, prev, next, reset, activeIndex, setActiveItem }">
            <el-icon @click="actions('zoomOut')"><ZoomOut /></el-icon>
            <el-icon
                @click="actions('zoomIn', { enableTransition: false, zoomRate: 1.2 })"
            >
              <ZoomIn />
            </el-icon>
            <el-icon
                @click="
            actions('clockwise', { rotateDeg: 180, enableTransition: false })
          "
            >
              <RefreshRight />
            </el-icon>
            <el-icon @click="actions('anticlockwise')"><RefreshLeft /></el-icon>
            <el-icon @click="reset"><Refresh /></el-icon>
            <el-icon @click="download(activeIndex)"><Download /></el-icon>
          </template>
        </el-image-viewer>
      </div>
    </el-container>
  </el-config-provider>
</template>

<script setup>
import store from '@/store'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import {queryImagesByPage, requestImageDetail} from '@/api/kateWork.js'
import {ref, reactive, onMounted, nextTick, onBeforeUnmount} from 'vue'
import {ElMessage} from 'element-plus'
import {addAllOptionOfOptions, genTableRequest} from '@/utils/generator.js'
import {labelPosition} from '@/constant/form.js'
import {kittingBomTypeOptions} from '@/constant/options.js'
import {loading} from "@/utils/loading";
import {
  Download,
  Refresh,
  RefreshLeft,
  RefreshRight,
  ZoomIn,
  ZoomOut,
} from '@element-plus/icons-vue'
/**
 * 常量定义
 */
const STAND_ID = store.getters.getStandId
const USER_NAME = store.getters.getUserName
/**
 * 变量定义
 */
let maxHeight = ref(window.innerHeight * 0.55)
let tableLoading = ref(false)
let displayImageList = ref([])
let baseTableQuery = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  sortBy: new Map([['boxNo', true], ['productId', true]]),// 按照成品号顺序排序---多个条件排序时优先级高的放在后面
  standId: STAND_ID,
  userName: USER_NAME
})
let searchQueryFormEntity = reactive({
  imageType: -99,
  productId: '',
  boxNo: ''
})
let searchQueryFormRef = ref()
let imageId = ''
let showImagePreview = ref(false)
let imgPreviewList = ref([])
let selectedImageInfo = reactive({
  imageId: '',
  productId: '',
  boxNo: '',
  url: '',
  base64: '',
  name: ''
})
/**
 * 系统方法
 */
onMounted(() => {
  nextTick(() => {
    window.addEventListener('resize', resizeHeight)
    search()
  })
})
onBeforeUnmount(() => {
  nextTick(() => {
    window.removeEventListener('resize', resizeHeight)
  })
})
const resizeHeight = () => {
  maxHeight.value = window.innerHeight * 0.55
}
/**
 * 自定义方法
 */
// 查询
const search = () => {
  tableLoading.value = true
  let request = genTableRequest(baseTableQuery)
  // 设定查询参数
  request.imageType = searchQueryFormEntity.imageType === -99 ? null : searchQueryFormEntity.imageType
  request.productId = searchQueryFormEntity.productId.trim()
  request.boxNo = searchQueryFormEntity.boxNo.trim()
  queryImagesByPage(request).then((res) => {
    const response = res.data
    if (response.code === 0) {
      const data = response.data
      if (data != null) {
        displayImageList.value = data.lists
        baseTableQuery.total = data.total
      } else {
        displayImageList.value = []
        baseTableQuery.total = 0
      }
    } else {
      ElMessage.error(response.message)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('查询数据异常。')
  }).finally(() => {
    tableLoading.value = false
  })
}
const clearQuery = () => {
  searchQueryFormEntity.productId = ''
  searchQueryFormEntity.boxNo = ''
}
const imageTypeFormat = (row, column, cellValue, index) => {
  switch (cellValue) {
    case 1:
      return '非服务件'
    case 2:
      return '服务件'
    default:
      return '未知类型'
  }
}
const handleSortChange = (data) => {
  if (baseTableQuery.sortBy.has(data.prop)) {
    baseTableQuery.sortBy.delete(data.prop)
  }
  baseTableQuery.sortBy.set(data.prop, data.order === 'ascending')
  search()
}
const getCurrentRow = (row) => {
  imageId = row.imageId
}
// 请求预览
const requestPreview = (row) => {
  const request = {
    imageId: row.imageId,
    standId: STAND_ID,
    userName: USER_NAME
  }
  loading.open('打开预览中...')
  requestImageDetail(request).then(res => {
    const response = res.data
    if (response.code === 0) {
      const results = response.data
      if (results === undefined || results.length !== 1) {
        ElMessage.error('无图纸或图纸歧义。')
        return
      }
      const image = results[0]
      openPreview(image)
    } else {
      ElMessage.error(response.message)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('查询异常')
  }).finally(() => {
    loading.close()
  })
}
// 打开预览
const openPreview = (image) => {
  selectedImageInfo.imageId = image.imageId
  selectedImageInfo.productId = image.productId
  selectedImageInfo.boxNo = image.boxNo
  selectedImageInfo.url = image.imageIp + image.imagePath + image.imageName
  selectedImageInfo.base64 = 'data:image/png;base64,' + image.imageDetail
  selectedImageInfo.name = image.imageName
  // 打开预览
  showImagePreview.value = true
  // 显示图片信息
  imgPreviewList.value = [selectedImageInfo.base64]
}
// 关闭预览
const closePreview = () => {
  selectedImageInfo.imageId = ''
  selectedImageInfo.productId = ''
  selectedImageInfo.boxNo = ''
  selectedImageInfo.url = ''
  selectedImageInfo.base64 = ''
  selectedImageInfo.name = ''
  // 打开预览
  showImagePreview.value = false
  // 显示图片信息
  imgPreviewList.value = []
}
// 下载图片
const download = (activeIndex) => {
  if (imgPreviewList.value.length === 0 || imgPreviewList.value.length < activeIndex - 1) {
    ElMessage.error('没有下载数据。')
    return
  }
  // 这里是获取到的图片base64编码,这里只是个例子哈，要自行编码图片替换这里才能测试看到效果
  const imgUrl = imgPreviewList.value[activeIndex]
  // 只支持新的浏览器
  const a = document.createElement('a')
  a.href = imgUrl
  a.setAttribute('download', selectedImageInfo.name)
  a.click()
}
</script>
<style scoped>
.content {
  display: flex;
  width: 100%;
}

.work-area {
  width: 100%;
  /* padding: 5px; */
}

.search-area {
  margin: auto;
  min-height: fit-content;
  max-height: 40%;
  margin-bottom: 10px;
  min-width: inherit;
  border: solid 1px;
  border-radius: 10px;
  box-shadow: 0px 15px 10px -15px #000;
  overflow: auto;
  padding: 10px;
}

.table-area {
  margin: auto;
  min-height: fit-content;
  max-height: 60%;
  margin-bottom: 10px;
  min-width: inherit;
  border: solid 1px;
  border-radius: 10px;
  box-shadow: 0px 15px 10px -15px #000;
  overflow: auto;
  padding: 10px;
}

.el-form-item {
  margin: 5px 5px 5px 5px;
}

.el-form-item .el-input {
  width: 196px;
}

.el-form-item .el-select-v2 {
  width: 196px;
}

.table-class {
  margin: 5px 5px 5px 5px;
  width: inherit;
}

.el-pagination {
  padding-left: 5px;
}

.btn-search {
  height: 30px;
  width: 80px;
  margin: auto 5px 5px auto;
  color: black;
}
</style>