<template>
  <div class="g-p20" style="margin-bottom: 40px">
    <base-head @onTabChange="onTabChange" :titles="['资料库', '故障库']" bottom="20"></base-head>
    <div v-if="tabValue == '资料库'">
      <pro-select
        :options="selectData.items"
        v-model:selectValue="selectValue"
        :field-name="{
          label: 'name',
          value: 'id'
        }"
      >
      </pro-select>
      <div class="content" v-loading="resData.loading">
        <div class="item" v-for="item in resData.items">
          <div class="item__icon" :class="{ word: item.fileType == 2, pdf: item.fileType === 1 }"></div>
          <div class="item__name">{{ item.creationTime }}</div>
          <div class="item__pdf">{{ item.name }}{{ fileType[item.fileType] }}</div>
          <div class="item__type">{{ item.documentTypeFormat }}</div>
          <div class="line"></div>
          <div class="item__btn">
            <el-button type="default" @click="onDownload(item)">
              <el-icon class="mr-5"><Download /></el-icon>下载
            </el-button>
            <el-button type="default" @click="onView(item)"
              ><el-icon class="mr-5"><View /></el-icon> 预览
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <div v-else>
      <base-search width="400" bottom="20" @onSearch="onSearch"></base-search>
      <div v-if="!showDetails" class="list" v-loading="faultList.loading">
        <el-empty v-if="faultList.items.length == 0" description="暂无数据" />
        <div @click="onPitch(item)" class="list-item" v-for="(item, i) in faultList.items" :key="i">
          <div class="list-item__title">{{ item.description }}</div>
          <div class="list-item__time">
            创建时间：{{ item.creationTimeFormat }}
            <span class="ml-20">创建人：{{ item.creatorUser }}</span>
          </div>
        </div>
        <pro-pagination
          v-if="faultList.items.length != 0"
          small
          class="pagination"
          :pageObj="pageObj"
          @change="faultList.getData()"
          :total="faultList.data.totalCount"
        ></pro-pagination>
      </div>
      <div v-else class="list">
        <div class="close" @click="showDetails = !showDetails">
          <el-icon><CloseBold /></el-icon>
        </div>
        <div class="list-item" v-for="(item, i) in details.arr" :key="i">
          <div class="list-item__title">{{ item.description }}</div>
          <div class="list-item__time">
            创建时间：{{ item.creationTimeFormat }}
            <span class="ml-20">创建人：{{ item.creatorUser }}</span>
          </div>
        </div>
        <div class="cause">
          <div class="cause__title">故障原因</div>
          <div class="text">
            {{ details.arr[0].reason }}
          </div>
        </div>
        <div>
          <div class="process-mode">处理方式</div>
          <div class="text">{{ details.arr[0].approach }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { getDocumentsByProductId, getFaultList } from '@/api'
  import { getProducts } from '@/api/product'
  import { useRequest } from '@/utils/hooks'
  import axios from 'axios'

  const queryObj: any = ref({})
  // 故障库搜索对象
  const pageObj: any = ref({
    MaxResultCount: 10,
    SkipCount: 1
  })
  const showDetails = ref(false)
  const filter = ref('')
  const fileType: any = {
    1: '.pdf',
    2: '.word'
  }
  const selectValue = ref('')
  const tabValue = ref('资料库')
  onMounted(async () => {
    await resData.getData()
    await selectData.getData()
  })
  const details: any = reactive({ arr: [] })
  const onPitch = (item: any) => {
    details.arr = [item]
    showDetails.value = true
  }
  const onTabChange = (e: any) => {
    tabValue.value = e
    if (e == '故障库') {
      faultList.getData()
    } else {
      resData.getData()
    }
  }
  watchEffect(() => {
    if (selectValue.value !== '' || queryObj.value.ProductId) {
      queryObj.value.ProductId = selectValue.value
      resData.getData()
    }
  })

  const onSearch = (v: any) => {
    pageObj.value = {
      MaxResultCount: 10,
      SkipCount: 1
    }
    filter.value = v
    faultList.getData()
  }
  const onView = (e: any) => {
    if (e.fileType == 2) {
      window.open(`https://view.officeapps.live.com/op/view.aspx?src=${e.url}`)
    }
    if (e.fileType == 1) {
      window.open(e.url)
    }
  }

  const onDownload = async (item: any) => {
    // window.open(item.url)

    const res = await axios.get(item.url, {
      responseType: 'blob'
    })

    const blob = new Blob([res.data])
    let suffix = '.' + item.url.split('.').pop()
    let fileName = item.name + suffix
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      window.navigator.msSaveBlob(blob, decodeURIComponent(fileName))
    } else {
      // 创建新的URL并指向File对象或者Blob对象的地址
      const blobURL = window.URL.createObjectURL(blob)
      // 创建a标签，用于跳转至下载链接
      const tempLink = document.createElement('a')
      tempLink.style.display = 'none'
      tempLink.href = blobURL
      tempLink.setAttribute('download', decodeURIComponent(fileName))
      // 兼容：某些浏览器不支持HTML5的download属性
      if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank')
      }
      // 挂载a标签
      document.body.appendChild(tempLink)
      tempLink.click()
      document.body.removeChild(tempLink)
      // 释放blob URL地址
      window.URL.revokeObjectURL(blobURL)
    }
  }

  const resData = useRequest(() => getDocumentsByProductId({ ...queryObj.value }), false)
  const selectData = useRequest(() => getProducts({ ...queryObj.value }), false)
  const faultList = useRequest(
    () =>
      getFaultList({
        MaxResultCount: pageObj.value.MaxResultCount,
        SkipCount: (pageObj.value.SkipCount - 1) * pageObj.value.MaxResultCount,
        Filter: filter.value
      }),
    false
  )
</script>

<style lang="less" scoped>
  .content {
    margin-top: 20px;
    display: flex;
    flex-wrap: wrap;
    min-height: 500px;
    justify-content: flex-start;
    .word {
      background-image: url('../../../assets/img/word.png');
    }
    .pdf {
      background-image: url('../../../assets/img/pdf.png');
    }
    .item {
      width: 310px;
      height: 290px;
      background: #ffffff;
      border-radius: 10px;
      margin-bottom: 20px;
      padding: 30px;
      margin-right: 20px;
      &__btn > .el-button {
        width: 115px;
        height: 31px;
        background: #ffffff;
        border: 1px solid #cccccc;
        border-radius: 5px;
      }
      &__icon {
        width: 54px;
        height: 64px;
        margin-bottom: 24px;
      }
      &__name {
        color: #999999;
        font-size: 12px;
      }
      &__pdf {
        color: #000000;
        font-size: 14px;
        margin: 10px 0;
      }
      &__type {
        width: 56px;
        text-align: center;
        height: 20px;
        line-height: 20px;
        background: #e8f7f0;
        border-radius: 3px;
        color: #5ebb88;
        font-size: 12px;
      }
    }
    .line {
      width: 250px;
      height: 1px;
      background: #efefef;
      margin: 20px 0;
    }
  }
  .list {
    min-height: 27px;
    background: #ffffff;
    border-radius: 10px;
    padding: 40px 60px;
    padding-bottom: 100px;
    position: relative;
    &-item {
      height: 80px;
      cursor: pointer;
      border-bottom: 1px solid #efefef;
      padding: 20px 0;
      &__title {
        font-weight: bold;
      }
      &__time {
        color: #999999;
        font-size: 12px;
        margin-top: 6px;
      }
    }
    .close {
      position: absolute;
      right: 20px;
      top: 20px;
      cursor: pointer;
    }
  }
  .cause {
    min-height: 158px;
    background: #faf6f3;
    border-radius: 10px;
    margin: 30px 0 20px;
    &__title {
      width: 110px;
      height: 36px;
      background: #deb090;
      border-top-left-radius: 10px;
      border-bottom-right-radius: 10px;
      text-align: center;
      line-height: 36px;
      font-size: 20px;
      color: #fff;
      font-weight: bold;
    }
    .text {
      color: #999;
      font-size: 14px;
      padding: 20px 30px;
    }
  }
  .process-mode {
    width: 110px;
    height: 36px;
    font-weight: bold;
    color: #ffffff;
    background-color: #597fda;
    border-radius: 10px;
    line-height: 36px;
    text-align: center;
  }
  .pagination {
    position: absolute;
    bottom: 15px;
    right: 60px;
  }
  .text {
    font-size: 14px;
    padding: 20px 30px;
  }
  .mr-5 {
    margin-right: 5px;
  }
  .ml-20 {
    margin-left: 20px;
  }
</style>
