<template>
  <div class="app-container">
    <div class="search-con">
      <div class="title">查询条件</div>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="发行时间" prop="time">
          <el-date-picker v-model="queryParams.time" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
        <el-form-item label="发行年份" prop="issueYear">
          <el-date-picker v-model="queryParams.issueYear" type="year" placeholder="请选择发行年份" value-format="YYYY" clearable />
        </el-form-item>
        <el-form-item label="系列" prop="series">
          <el-select v-model="queryParams.series" placeholder="请选择系列" clearable>
            <el-option v-for="dict in commemorative_banknote_series" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="search-btn-con">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button type="info" icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </div>
    <div class="main-con">
      <div class="title-con">
        <div class="title">基本信息</div>
        <div class="operate-btn-con">
          <el-button @click="handleAdd" icon="Plus" v-hasPermi="['collect:CommemorativeBanknote:add']">新增</el-button>
          <el-button :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['collect:CommemorativeBanknote:remove']">删除</el-button>
          <el-button @click="handleExport" icon="Download" v-hasPermi="['collect:CommemorativeBanknote:export']">导出</el-button>
        </div>
      </div>
      <div class="content-con" v-loading="loading">
        <el-table v-loading="loading" :data="CommemorativeBanknoteList" @selection-change="handleSelectionChange" height="calc(100% - 0.62rem)">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="缩略图" align="center" prop="collectFileList" width="100">
            <template #default="scope">
              <el-image
                v-if="scope.row.collectFileList && scope.row.collectFileList.length > 0"
                :src="scope.row.collectFileList[0].url"
                style="width: 60px; height: 60px; cursor: pointer"
                fit="cover"
                @click="handlePreviewImages(scope.row.collectFileList)"
              />
              <span v-else style="color: #999">暂无图片</span>
            </template>
          </el-table-column>
          <el-table-column label="全称" align="center" prop="fullName" width="320" />
          <el-table-column label="简称" align="center" prop="shortName" />
          <el-table-column label="发行量" align="center" prop="mintage" />
          <el-table-column label="面额" align="center" prop="faceValue" />
          <el-table-column label="发行时间" align="center" prop="issueDate" />
          <el-table-column label="发行年份" align="center" prop="issueYear" />
          <el-table-column label="材质" align="center" prop="composition">
            <template #default="scope">
              <dict-tag :options="commemorative_banknote_composition" :value="scope.row.composition" />
            </template>
          </el-table-column>
          <el-table-column label="系列" align="center" prop="series">
            <template #default="scope">
              <dict-tag :options="commemorative_banknote_series" :value="scope.row.series" />
            </template>
          </el-table-column>
          <el-table-column label="铸币单位" align="center" prop="coinageUnit" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <div class="ctrl-btn d-flex">
                <el-tooltip v-for="item in operateList" :key="item.id" class="item" effect="dark" :content="item.title" placement="top">
                  <el-button :icon="item.icon" :v-hasPermi="item.hasPermi" circle @click="handleOperate(item.id, scope.row)"></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          background
          layout="total,sizes, prev, pager, next"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="queryParams.pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加或修改纪念钞对话框 -->
    <el-dialog :title="title" v-model="open" width="880px" append-to-body>
      <el-form ref="CommemorativeBanknoteRef" :model="form" :inline="true" :rules="rules" label-width="120px">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option v-for="dict in commemorative_banknote_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="全称" prop="fullName">
          <el-input v-model="form.fullName" placeholder="请输入全称" />
        </el-form-item>
        <el-form-item label="简称" prop="shortName">
          <el-input v-model="form.shortName" placeholder="请输入简称" />
        </el-form-item>
        <el-form-item label="发行量" prop="mintage">
          <el-input v-model="form.mintage" placeholder="请输入发行量" />
        </el-form-item>
        <el-form-item label="面额" prop="faceValue">
          <el-input v-model="form.faceValue" placeholder="请输入面额" />
        </el-form-item>
        <el-form-item label="发行时间" prop="issueDate">
          <el-date-picker v-model="form.issueDate" type="date" placeholder="请选择发行时间" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="发行年份" prop="issueYear">
          <el-date-picker v-model="form.issueYear" type="year" placeholder="请选择发行年份" value-format="YYYY" />
        </el-form-item>
        <el-form-item label="材质" prop="composition">
          <el-select v-model="form.composition" placeholder="请选择材质">
            <el-option v-for="dict in commemorative_banknote_composition" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系列" prop="series">
          <el-select v-model="form.series" placeholder="请选择系列">
            <el-option v-for="dict in commemorative_banknote_series" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="铸币单位" prop="coinageUnit">
          <el-input v-model="form.coinageUnit" placeholder="请输入铸币单位" />
        </el-form-item>
        <el-form-item label="版别" prop="blockType">
          <el-select v-model="form.blockType" placeholder="请选择版别">
            <el-option v-for="dict in commemorative_banknote_block_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发行说明" style="width: 792px" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入发行说明" />
        </el-form-item>

        <el-form-item label="图片上传" style="width: 792px" prop="imageUpload">
          <image-upload uploadUrl="/collect/collectFile/uploadFile" v-model:modelValue="form.collectFileList" v-model:isToString="isToString" />
        </el-form-item>
      </el-form>
      <template v-if="title !== '查看纪念钞'" #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="imagePreviewVisible" title="图片预览" width="800px" append-to-body>
      <div class="image-preview-container">
        <el-carousel :autoplay="false" arrow="always" height="500px" v-if="previewImageList.length > 0">
          <el-carousel-item v-for="(image, index) in previewImageList" :key="index">
            <div class="image-wrapper">
              <el-image :src="image.url" fit="contain" style="width: 100%; height: 100%" />
            </div>
          </el-carousel-item>
        </el-carousel>
        <div class="image-count" v-if="previewImageList.length > 0">共 {{ previewImageList.length }} 张图片</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="CommemorativeBanknote">
import {
  listCommemorativeBanknote,
  getCommemorativeBanknote,
  delCommemorativeBanknote,
  addCommemorativeBanknote,
  updateCommemorativeBanknote
} from '@/api/collect/CommemorativeBanknote'
import dayjs from 'dayjs'
// eslint-disable-next-line no-unused-vars
import { require } from '@/utils/require'
const { proxy } = getCurrentInstance()
const { commemorative_banknote_type, commemorative_banknote_series, commemorative_banknote_composition, commemorative_banknote_block_type } = proxy.useDict(
  'commemorative_banknote_type',
  'commemorative_banknote_series',
  'commemorative_banknote_composition',
  'commemorative_banknote_block_type'
)

const CommemorativeBanknoteList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const isToString = ref(false)
const imagePreviewVisible = ref(false)
const previewImageList = ref([])
const operateList = ref([
  { id: 'view', icon: 'View', title: '查看', hasPermi: ['collect:CommemorativeBanknote:query'] },
  { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['collect:CommemorativeBanknote:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['collect:CommemorativeBanknote:remove'] }
])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    issueYear: null,
    series: null,
    time: '',
    startTime: '',
    endTime: ''
  },
  rules: {
    type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
    fullName: [{ required: true, message: '全称不能为空', trigger: 'blur' }],
    shortName: [{ required: true, message: '简称不能为空', trigger: 'blur' }],
    mintage: [{ required: true, message: '发行量不能为空', trigger: 'blur' }],
    faceValue: [{ required: true, message: '面额不能为空', trigger: 'blur' }],
    issueDate: [{ required: true, message: '发行时间不能为空', trigger: 'blur' }],
    issueYear: [{ required: true, message: '发行年份不能为空', trigger: 'blur' }],
    composition: [{ required: true, message: '材质不能为空', trigger: 'change' }],
    series: [{ required: true, message: '系列不能为空', trigger: 'change' }],
    coinageUnit: [{ required: true, message: '铸币单位不能为空', trigger: 'blur' }]
  }
})

const handleOperate = (operate, row) => {
  switch (operate) {
    case 'view':
      handleView(row)
      break
    case 'edit':
      handleUpdate(row)
      break
    case 'delete':
      handleDelete(row)
      break
    default:
      break
  }
}

const { queryParams, form, rules } = toRefs(data)

// 预览图片
const handlePreviewImages = (imageList) => {
  previewImageList.value = imageList || []
  imagePreviewVisible.value = true
}

// 监听发行时间变化，自动设置发行年份
watch(
  () => form.value.issueDate,
  (newDate) => {
    if (newDate) {
      const year = newDate.split('-')[0]
      form.value.issueYear = year
    }
  }
)

/** 查询纪念钞列表 */
function getList() {
  loading.value = true
  const timeRange = queryParams.value.time
  let st = ''
  let et = ''
  if (timeRange && timeRange.length === 2) {
    st = dayjs(timeRange[0]).format('YYYY-MM-DD')
    et = dayjs(timeRange[1]).format('YYYY-MM-DD')
  }
  queryParams.value.startTime = st
  queryParams.value.endTime = et
  listCommemorativeBanknote(queryParams.value).then((response) => {
    CommemorativeBanknoteList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    type: null,
    fullName: null,
    shortName: null,
    mintage: null,
    faceValue: null,
    issueDate: null,
    issueYear: null,
    composition: null,
    series: null,
    blockType: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    coinageUnit: null
  }
  proxy.resetForm('CommemorativeBanknoteRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 分页
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

// 每页显示条数改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 查看
const handleView = (row) => {
  title.value = '查看纪念钞'
  form.value = row
  open.value = true
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加纪念钞'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getCommemorativeBanknote(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改纪念钞'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.CommemorativeBanknoteRef.validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateCommemorativeBanknote(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addCommemorativeBanknote(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delCommemorativeBanknote(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'collect/CommemorativeBanknote/export',
    {
      ...queryParams.value
    },
    `CommemorativeBanknote_${new Date().getTime()}.xlsx`
  )
}

getList()
</script>

<style scoped lang="scss">
.image-preview-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-count {
  margin-top: 10px;
  text-align: center;
  color: #606266;
  font-size: 14px;
}

:deep(.el-image-viewer__wrapper) {
  z-index: 9999 !important;
}

:deep(.el-upload-list) {
  display: flex !important;
  flex-wrap: wrap !important;
  gap: 8px !important;
}

:deep(.el-upload-list__item) {
  margin: 0 !important;
}

/* 确保表格内容区域可以滚动 */
:deep(.el-table__body-wrapper) {
  overflow-y: auto !important;
}
</style>
