<template>
  <div class="AboutView">
    <div class="w-full h-[180px] relative flex items-center md:h-[380px]">
      <div
        class="w-full h-full bg-[url('/src/assets/images/detail_top_bg.png')] bg-no-repeat bg-center bg-cover absolute left-0 top-0 z-0"
      ></div>
      <div class="relative z-1 p-4 w-full md:w-[1280px] mx-auto">
        <div
          class="font-['PingFang-Heavy'] px-3 mibold text-xl md:text-[32px] md:leading-tight"
        >
          工具数字化展示
        </div>
        <div class="flex mt-4 flex-wrap">
          <div
            class="ml-3 text-[14px] font-semibold cursor-pointer"
            v-for="typeItem in typeOptions1Ref"
            :key="typeItem.id"
            @click="handleReturn(typeItem)"
          >
            {{ typeItem.toolName }}
          </div>
        </div>
      </div>
    </div>
    <section
      class="w-full bg-[url('/src/assets/images/detail_bg.png')] bg-no-repeat bg-center bg-cover left-0 top-0 z-0 flex justify-center"
    >
      <div
        class="w-[1440px] max-w-md mx-auto bg-white rounded-xl shadow-md overflow-hidden md:max-w-7xl"
      >
        <div class="md:flex">
          <div class="w-full md:w-[450px] md:shrink-0 p-3">
            <div class="w-full h-[450px] tool-img border-2 flex items-center justify-center">
              <van-image class="max-w-[450px] max-h-[450px] tool-img" :src="devPath + sytPath" />
            </div>
            <van-grid
              square
              :column-num="4"
              class="w-full object-cover mt-4"
              :gutter="10"
            >
              <van-grid-item
                v-for="syt in sytList"
                :key="syt.id"
                @click="changeImg(syt)"
                :class="[syt.id === detailImg ? 'active' : '', 'cursor-pointer']"
              >
                <van-image class="max-w-[105px] max-h-[105px]" :src="devPath + syt.filePath" />
              </van-grid-item>
            </van-grid>
          </div>
          <div class="p-8 w-full">
            <div
              class="font-['PingFang-Heavy'] font-semibold text-xl md:text-[20px] md:leading-tight"
            >
              {{ toolInfoRef.toolName }}
            </div>
            <div
              class="bg-[#E6F7FF] border border-[#004EA2] rounded px-3 text-[#004EA2] text-center mt-9 font-normal text-xs w-[200px] h-[22px] leading-[22px] truncate"
            >
              {{ breadTitle }}
            </div>

            <div class="my-8">
              <!-- 搜索表单 -->
              <el-form :model="queryParams" ref="searchFormRef" :inline="true" v-show="showSearch">
                <el-form-item label="物料编码" prop="materialNo">
                  <el-input
                    v-model="queryParams.materialNo"
                    placeholder="请输入物料编码"
                    clearable
                    style="width: 200px"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="物料名称" prop="materialName">
                  <el-input
                    v-model="queryParams.materialName"
                    placeholder="请输入物料名称"
                    clearable
                    style="width: 200px"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleQuery">搜索</el-button>
                  <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>

              <!-- 是否展示搜索图标 -->
              <van-icon class="float-right" name="search" @click="toggleSearch()" />

              <!-- 表格 -->
              <el-table :data="wlList">
                <el-table-column label="物料编码" align="center" prop="materialNo">
                  <template #default="scope">
                    <div class="flex items-center justify-center">
                      <div>{{ scope.row.materialNo }}</div>
                      <van-icon
                        name="description-o"
                        class="text-[#004EA2] description-o ml-1 cursor-pointer"
                        @click="codeCopy(scope.row.materialNo)"
                      />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="物料名称" align="center" prop="materialName" />
                <el-table-column label="规格" align="center" prop="specifications" />
              </el-table>
              <div class="w-full mt-2">
                <el-pagination
                  background
                  hide-on-single-page
                  :current-page="pageNum"
                  :page-size="5"
                  :pager-count="5"
                  layout="->,prev, pager, next"
                  :total="total"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
            <div class="font-['PingFang-SC'] text-sm font-normal mt-4">
              <div class="font-semibold">标准规格说明：</div>
              <div>{{ toolInfoRef.specifications }}</div>
            </div>
            <div class="font-['PingFang-SC'] text-sm font-normal mt-4">
              <div class="font-semibold">举例：</div>
              <div>{{ toolInfoRef.example }}</div>
            </div>
            <div class="font-['PingFang-SC'] text-sm font-normal mt-4">
              <div class="font-semibold">附件：</div>
              <van-cell-group v-if="fileList.length > 0">
                <van-cell v-for="file in fileList" :key="file.id">
                  <template #title>
                    <span class="cursor-pointer" @click="fileDownload(file)">{{
                      file.fileName
                    }}</span>
                  </template>
                  <template #right-icon>
                    <img
                      class="w-[18px] h-[18px] cursor-pointer"
                      src="../assets/images/download.png"
                      alt=""
                      @click="fileDownload(file)"
                    />
                  </template>
                </van-cell>
              </van-cell-group>
              <van-empty v-else image-size="100" description="暂无数据" />
            </div>
          </div>
        </div>
      </div>
    </section>
    <!-- <h1 class="text-3xl font-bold underline" @click="goBack">详情页</h1> -->
  </div>
</template>

<script setup name="AboutView">
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { detailList } from '@/api/index.js'
import Clipboard from 'clipboard'
import { listTools, getwlList } from '@/api/index.js'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const queryId = ref(route.query.id)

const wlList = ref([])
// const wlSelectId = ref(0)
// const selectWlCode = ref('')
// const selectMaterialName = ref('')
const sytList = ref([])
const fileList = ref([])
const detailImg = ref(0)
const sytPath = ref('')
const devPath = import.meta.env.VITE_APP_BASE_API
const breadTitle = ref('')
const typeOptions1Ref = ref([])
const toolInfoRef = ref({})

// 物料搜索相关参数
const queryParams = ref({
  materialNo: '',
  materialName: ''
})
const showSearch = ref(false)
const pageNum = ref(1)
const total = ref(0)

const getWlList = (params) => {
  getwlList({ basisId: queryId.value, ...params }).then((res) => {
     console.log(res)
    wlList.value = res.rows
    total.value = res.total
  })
}

const init = () => {
  // 查详情
  detailList({ id: queryId.value }).then((res) => {
    const toolDetails = res.data.toolDetails || []
    toolInfoRef.value = res.data.toolData || {}
    sytList.value = toolDetails.filter((item) => item.informationType === 'syt')
    if (sytList.value.length > 0) {
      detailImg.value = sytList.value[0].id
      sytPath.value = sytList.value[0].filePath
    }
    fileList.value = toolDetails.filter(
      (item) => item.informationType !== 'syt' && item.informationType !== 'wl'
    )

    const ttoolBasis = res.data.ttoolBasis
    breadTitle.value = ttoolBasis.map((item) => item.toolName).join(' > ')
  })

  listTools({
    level: '1',
    pageSize: 999
  }).then((res) => {
    typeOptions1Ref.value = res.rows
  })

  // 查物料详情的
  getWlList({ pageNum: 1, pageSize: 5 })
}
init()

const changeImg = ({ id, filePath }) => {
  detailImg.value = id
  sytPath.value = filePath
}

const codeCopy = async (val) => {
  // console.log(val)
  const clipboard = new Clipboard('.description-o', {
    text: () => val
  })
  // 添加成功事件处理函数
  clipboard.on('success', (e) => {
    e.clearSelection()
    ElMessage.success('复制成功')
    clipboard.destroy()
  })
  // 添加失败事件处理函数
  clipboard.on('error', () => {
    ElMessage.error('无法复制到剪贴板！')
    console.warn('无法复制到剪贴板！')
  })
}

// const changeWlCode = ({ id, materialNo, materialName }) => {
//   wlSelectId.value = id
//   selectWlCode.value = materialNo
//   selectMaterialName.value = materialName
// }
//  informationType 物料  wl  点击切换 物料编码 materialNo
//  informationType 示意图 syt 左侧图
const fileDownload = ({ fileName, filePath }) => {
  // console.log('filePath', filePath)
  const el = document.createElement('a')
  el.style.display = 'none'
  el.setAttribute('target', '_blank')

  fileName && el.setAttribute('download', fileName)
  el.href = devPath + filePath
  document.body.appendChild(el)
  el.click()
  document.body.removeChild(el)
}

const handleReturn = (typeItem) => {
  router.push({ path: '/home', query: { id: typeItem.id } })
}

// 搜索物料
const handleQuery = () => {
  const params = {
    materialNo: queryParams.value.materialNo || '',
    materialName: queryParams.value.materialName || '',
    // 看看有没有分页
    pageNum: pageNum.value,
    pageSize: 5
  }
  // console.log('搜索物料', params)
  getWlList(params)
}
const searchFormRef = ref(null)
// 重置
const resetQuery = () => {
  searchFormRef.value.resetFields()
  handleQuery()
}

// 切换分页
const handleCurrentChange = (val) => {
  // console.log(val)
  pageNum.value = val
  handleQuery()
}

// 显示搜索框
const toggleSearch = () => {
  showSearch.value = !showSearch.value
}
</script>

<style lang="scss" scoped>
:deep(.van-grid-item__content--surround:after) {
  border: 4px solid #e5e7eb;
}
.active {
  :deep(.van-grid-item__content--surround:after) {
    border: 4px solid #004ea2;
  }
}
</style>
