<template>
  <div class="tab2">
    <div class="insideTop">
      文物管理
      <div class="add">
        <el-button type="primary" @click="addGood">新增</el-button>
      </div>
    </div>
    <div class="obstruct"></div>
    <div class="conten">
      <div class="con_left" v-show="0">
        <div class="cutJT">
          <i class="el-icon-menu"></i>
          典藏管理
        </div>
        <ul>
          <li
            v-for="item in conLeftArr"
            :key="item.id"
            :class="{ active: formData.type === item.type }"
            @click="cutLeft(item.type)"
          >
            {{ item.name }}
          </li>
        </ul>
      </div>
      <!-- 右侧主要内容 -->
      <div class="con_right" v-loading="loading">
        <div class="search" @keyup.enter="searchBtn">
          <span>&emsp;&emsp;名称：</span>
          <el-input
            maxlength="25"
            show-word-limit
            v-model="formData.searchKey"
            placeholder="请输入关键字"
            style="width: 240px"
          ></el-input>
          <span class="search_k">&emsp;&emsp;类别：</span>
          <el-select v-model="formData.dictTextureId" placeholder="请选择类别">
            <el-option
              v-for="i in dictTextureArr"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            >
            </el-option>
          </el-select>
          <span class="search_k">年代：</span>
          <el-select v-model="formData.dictAgeId" placeholder="请选择类别">
            <el-option
              v-for="i in dictAgeArr"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            >
            </el-option>
          </el-select>
          <span class="search_k">级别：</span>
          <el-select v-model="formData.dictLevelId" placeholder="请选择类别">
            <el-option
              v-for="i in dictLevelArr"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            >
            </el-option>
          </el-select>
        </div>
        <div class="search" @keyup.enter="searchBtn">
          <span>总登记号：</span>
          <el-input
            maxlength="25"
            show-word-limit
            v-model="formData.registerNum"
            placeholder="请输入关键字"
            style="width: 240px"
          ></el-input>

          <span class="search_k">创建时间：</span>
          <el-date-picker
            style="width: 257px;padding-right: 0px;"
            v-model="time"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>

          <!-- 右侧按钮 -->
          <div class="search_btn">
            <el-button type="primary" @click="searchBtn">查 询</el-button>
            <el-button @click="resetBtn">重 置</el-button>
            <download-excel
              :before-generate="derive"
              class="export-excel-wrapper"
              :data="json_data"
              :fields="json_fields"
              :name="`文物信息清单${nowTime}.xls`"
            >
              <!-- 上面可以自定义自己的样式，还可以引用其他组件button -->
              <el-button>批量导出</el-button>
            </download-excel>
          </div>
        </div>
        <!-- 表格 -->
        <div class="table">
          <el-table :data="tableData" style="width: 100%">
            <el-table-column label="编号" width="80">
              <template slot-scope="scope">
                {{
                  scope.$index + (formData.pageNum - 1) * formData.pageSize + 1
                }}
              </template>
            </el-table-column>
            <el-table-column label="名称" prop="name"> </el-table-column>
            <el-table-column label="总登记号">
              <template #default="{ row }">
                <span
                  style="cursor: pointer"
                  :title="row.registerNum"
                  v-if="row.registerNum"
                  >{{
                    row.registerNum.length > 10
                      ? row.registerNum.substring(0, 10) + "..."
                      : row.registerNum
                  }}</span
                >
                <span v-else>(空)</span>
              </template>
            </el-table-column>
            <el-table-column label="类别">
              <template #default="{ row }">
                <span v-if="row.dictTextureName">{{
                  row.dictTextureName
                }}</span>
                <span v-else>(空)</span>
              </template>
            </el-table-column>
            <el-table-column label="年代">
              <template #default="{ row }">
                <span v-if="row.dictAgeFront">{{ row.dictAgeFront }}</span>
                <span v-else>(空)</span>
              </template>
            </el-table-column>
            <el-table-column label="级别">
              <template #default="{ row }">
                <span v-if="row.dictLevelName">{{ row.dictLevelName }}</span>
                <span v-else>(空)</span>
              </template>
            </el-table-column>
            <el-table-column label="说明">
              <template #default="{ row }">
                <span
                  style="cursor: pointer"
                  :title="handTxt(row.description)"
                  v-if="handTxt(row.description)"
                  >{{handTxt(row.description).length > 10?handTxt(row.description).substring(0, 10) + "...":handTxt(row.description)}}</span
                >
                <span v-else>(空)</span>
              </template>
            </el-table-column>
            <el-table-column label="图片" width="120">
              <template #default="{ row }">
                <img
                  class="table_img"
                  :src="baseURL + row.thumb"
                  alt=""
                  :onerror="defaultImg"
                />
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间">
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button type="text" @click="editGood(row.id)"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  style="color: #d9001b"
                  :disabled="!!row.display"
                  @click="delGoods(row.id)"
                  :class="{ disNo: row.display }"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <!-- 分页 -->
    <div class="paging">
      <span>共 {{ total }} 条</span>
      <el-pagination
        layout="sizes,prev, pager, next,jumper"
        :total="total"
        :current-page="formData.pageNum"
        @current-change="currentChange"
        @size-change="sizeChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import axios from '@/utils/request'
import { goodsList, goodsRemove, goodsDisplay, dictGetTree } from '@/apis/tab2'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
dayjs.extend(relativeTime)

export default {
  name: 'tab2',
  components: {},
  data () {
    // 这里存放数据
    return {
      loading: false,
      nowTime: '',
      // 导出表格的数据
      json_fields: {
        名称: 'name', // 常规字段
        总登记号: 'registerNum', // 支持嵌套属性
        类别: 'dictTextureName',
        年代: 'dictAgeName',
        级别: 'dictLevelName',
        长: 'sizeLength',
        宽: 'sizeWidth',
        高: 'sizeHeight',
        说明: 'description'
      },
      json_data: [],
      json_meta: [
        [
          {
            ' key ': ' charset ',
            ' value ': ' utf- 8 '
          }
        ]
      ],

      baseURL: '',
      total: 0,
      time: '',
      conLeftArr: [
        { name: '精品图片', type: 'img' },
        { name: '三维模型', type: 'model' }
      ],
      formData: {
        startTime: '',
        endTime: '',
        pageNum: 1,
        pageSize: 10,
        searchKey: '',
        registerNum: '',
        dictTextureId: '',
        dictLevelId: '',
        dictAgeId: '',
        type: 'model'
      },
      tableData: [],
      dictLevelArr: [],
      dictTextureArr: [],
      dictAgeArr: []
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    time (val) {
      this.handleSelect(val)
    }
  },
  // 方法集合
  methods: {
    // 处理说明的文本
    handTxt (val) {
      let temp = val.replaceAll('&emsp;', ' ')
      temp = temp.replaceAll('<br/>', '/')
      return temp
    },
    // 点击导出
    async derive () {
      this.searchBtn()
      this.json_data = []
      this.loading = true
      this.nowTime = dayjs().format('YYYYMMDD')
      // 封装获取列表的函数
      const res = await goodsList({
        ...this.formData,
        pageNum: 1,
        pageSize: 9999
      })
      if (res.code === 0) {
        if (res.data.records.length === 0) {
          this.$message.warning('没有符合条件的数据')
          this.loading = false
          return
        }
        this.json_data = res.data.records.map((v) => {
          return {
            name: v.name,
            registerNum: v.registerNum,
            dictTextureName: v.dictTextureName,
            dictAgeName: v.dictAgeName,
            sizeLength: v.sizeLength.replace(',', ''),
            sizeWidth: v.sizeWidth.replace(',', ''),
            sizeHeight: v.sizeHeight.replace(',', ''),
            description: v.description
          }
        })
        this.loading = false
      } else this.$message.warning(res.msg)
    },
    // 点击重置
    resetBtn () {
      this.formData.searchKey = ''
      this.time = ''
      this.formData.pageNum = 1
      this.formData.startTime = this.formData.endTime = ''
      this.formData.registerNum =
        this.formData.dictTextureId =
        this.formData.dictLevelId =
        this.formData.dictAgeId =
          ''
      this.goodsList(this.formData)
    },
    // 点击查询
    searchBtn () {
      this.formData.pageNum = 1
      this.goodsList(this.formData)
    },
    // 点击开关
    async changeSwit (val, id) {
      const res = await goodsDisplay(id, val)
      if (res.code === 0) {
        this.$message.success('操作成功')
        this.goodsList(this.formData)
      } else this.$message.warning(res.msg)
      console.log(998, val, id)
    },
    // 分页器方法
    currentChange (val) {
      // console.log('当前页改变了', val)
      this.formData.pageNum = val
      this.goodsList(this.formData)
    },
    sizeChange (val) {
      // console.log('条数改变了', val)
      this.formData.pageNum = 1
      this.formData.pageSize = val
      this.goodsList(this.formData)
    },
    // 点击删除
    delGoods (id) {
      this.$confirm('删除后，信息无法恢复，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await goodsRemove(id)
          if (res.code === 0) {
            this.$message.success('删除成功')
            if (this.tableData.length === 1 && this.formData.pageNum > 1) {
              this.formData.pageNum -= 1
            }
            this.goodsList(this.formData)
          } else this.$message.warning(res.msg)
        })
        .catch(() => {
          this.$message.info('已取消')
        })
    },
    // 点击编辑文物
    editGood (id) {
      this.$router.push({
        path: '/layout/tab2Add',
        query: { typeU: this.formData.type, id, k: this.formData.pageNum }
      })
    },
    // 点击新增文物
    addGood () {
      this.$router.push({
        path: '/layout/tab2Add',
        query: { typeU: this.formData.type, k: this.formData.pageNum }
      })
    },
    // 点击左侧的tab栏
    cutLeft (type) {
      if (type === this.formData.type) return
      this.formData.pageNum = 1
      this.formData.type = type
      this.goodsList(this.formData)
    },
    // 时间处理----------------
    handleSelect (e) {
      const date = []
      for (const i in e) {
        date.push(this.gettime(e[i]))
      }
      this.formData.startTime = date[0]
      if (date[1]) {
        this.formData.endTime = date[1].replace('00:00:00', '23:59:59')
      }
      if (e === null) this.formData.endTime = ''
    },
    gettime (data) {
      const value =
        data.getFullYear() +
        '-' +
        this.checkTime(data.getMonth() + 1) +
        '-' +
        this.checkTime(data.getDate()) +
        ' ' +
        this.checkTime(data.getHours()) +
        ':' +
        this.checkTime(data.getMinutes()) +
        ':' +
        this.checkTime(data.getSeconds())
      return value
    },
    checkTime (i) {
      if (i < 10) {
        i = '0' + i
      }
      return i
    },
    // 封装获取列表的函数
    async goodsList (data) {
      const res = await goodsList(data)
      this.total = res.data.total
      this.tableData = res.data.records
      // console.log(998, res)
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  async created () {
    // 获取服务器前缀地址
    this.baseURL = axios.defaults.baseURL
    // 判断是第一次进来还是修改或者新增或者查看后返回
    // 拿到路由跳转传过来的数据
    if (this.$route.query.typeU) {
      this.formData.type = this.$route.query.typeU
    }
    const k = this.$route.query.k
    if (k) this.formData.pageNum = Number(k)
    this.goodsList(this.formData)
    // 几个下拉框的数据
    // --------年代
    const res = await dictGetTree({ type: 'age' })
    const temp = []
    res.data.forEach((v) => {
      v.children.forEach((p) => {
        temp.push({ value: p.id, label: p.name })
      })
    })
    temp.unshift({ value: '', label: '全部' })
    this.dictAgeArr = [...temp]
    // -------类别
    const res2 = await dictGetTree({ type: 'texture' })
    this.dictTextureArr = res2.data.map((v) => {
      return { value: v.id, label: v.name }
    })
    this.dictTextureArr.unshift({ value: '', label: '全部' })
    // -------级别
    const res3 = await dictGetTree({ type: 'level' })
    this.dictLevelArr = res3.data.map((v) => {
      return { value: v.id, label: v.name }
    })
    this.dictLevelArr.unshift({ value: '', label: '全部' })
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {},
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='less' scoped>
.tab2 {
  height: 100%;
  .conten {
    display: flex;
    height: calc(100% - 52px);
    .con_left {
      padding: 20px 0 0 15px;
      width: 150px;
      height: 100%;
      border-right: 1px solid black;
      .cutJT {
        margin-bottom: 10px;
      }
      ul {
        li {
          cursor: pointer;
          width: 100px;
          text-align: center;
          line-height: 40px;
          height: 40px;
          &:hover {
            color: #3a80d2;
          }
        }
        .active {
          color: #3a80d2;
        }
      }
    }
    .con_right {
      padding: 15px 30px 0;
      width: 100%;
      .classify {
        text-align: center;
        width: 40px;
        padding-bottom: 10px;
        color: #b9412e;
        border-bottom: 2px solid #b9412e;
      }
      .search {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        position: relative;
        margin-top: 12px;
        height: 40px;
        /deep/.el-input__inner {
          padding-right: 50px;
        }
        /deep/.el-select {
          width: 150px;
        }
        .search_k {
          margin-left: 30px;
        }
        .search_btn {
          margin-left: 50px;
          display: flex;
          justify-content: space-between;
          width: 300px;
        }
      }
    }
  }
  // .table {
  //   max-width: 1370px;
  // }
  /deep/.el-table__body-wrapper {
    max-height: 440px;
    overflow-y: auto;
  }
  .paging {
    display: flex;
    align-items: center;
    position: absolute;
    bottom: 15px;
    right: 50px;
    & > span {
      margin-right: 15px;
      font-size: 13px;
    }
  }
  .disNo {
    color: #ccc !important;
  }
}
</style>
