<template>
  <div class="official-tag-page">
    <!-- 搜索栏 -->
    <div class="search-section">
      <el-input
        v-model="searchParams.name"
        placeholder="请输入竞拍名称"
        clearable
        class="w-200px mr-12px"
      ></el-input>
      <el-button type="primary" :icon="Search" @click="refresh">搜索</el-button>
      <el-button @click="reset">重置</el-button>

      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增
      </el-button>
      <el-button type="primary" @click="handleBatchShow" :disabled="selectedRows.length === 0">
        批量修改展示竞拍
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
        批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <!-- 表格 -->
      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="list"
          height="100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="createUserName" label="发布人" width="100" />
          <el-table-column prop="createdAt" label="发布时间" width="200" sortable>
            <template #default="{ row }">
              {{ dayjs(row.createdAt * 1000).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" width="200" />
          <el-table-column prop="imageUrl" label="图片" width="150">
            <template #default="{ row }">
              <el-image
                v-if="row.imageUrl"
                :preview-teleported="true"
                :src="row.imageUrl"
                class="w-20 h-20 object-cover"
                :preview-src-list="[row.imageUrl]"
              />
              <span v-else>暂无图片</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="description"
            label="介绍内容"
            width="200"
            :ellipsis="true"
            :show-overflow-tooltip="{
              placement: 'top',
              popperClass: 'max-w-300',
            }"
          >
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100"> </el-table-column>

          <el-table-column prop="specification" label="规格" width="100"> </el-table-column>

          <el-table-column prop="startingPrice" label="起拍价" width="100" />
          <el-table-column prop="minIncrement" label="最低加价幅度" width="150" />
          <el-table-column prop="currentPrice" label="当前出价" width="150" />
          <el-table-column prop="bidLimit" label="竞拍次数上限" width="150" />
          <el-table-column prop="startTime" label="竞拍时间" width="320">
            <template #default="{ row }">
              {{ dayjs(row.startTime * 1000).format('YYYY-MM-DD HH:mm:ss') }} ~
              {{ dayjs(row.endTime * 1000).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column prop="statusDesc" label="展示竞拍" width="100">
            <template #default="{ row }">
              {{ row.isDisplay === 1 ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column prop="showName" label="竞拍状态" width="100">
            <template #default="{ row }">
              {{
                // 未展示的时候不展示竞拍状态
                row.isDisplay === 0
                  ? '未展示在前台时不展示竞拍状态'
                  : auctionStatusListOptions.find((item) => item.value === row.status)?.label
              }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="primary" link @click="handleAuctionRecord(row)">竞拍记录</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="searchParams.current"
          v-model:page-size="searchParams.size"
          :total="total"
          :page-sizes="[10, 20, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="changePageSize"
          @current-change="goToPage"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="510px"
      top="5vh"
      :close-on-click-modal="false"
    >
      <el-scrollbar height="650px" class="pr-4">
        <el-form ref="formRef" :model="form" :rules="formRules" label-width="auto">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入名称（最多25个字符）" maxlength="25" />
          </el-form-item>
          <el-form-item label="图片" prop="imageUrl">
            <UploadFile v-model="form.imageUrl" :limit="1" />
          </el-form-item>
          <el-form-item label="介绍内容" prop="description">
            <el-input v-model="form.description" type="textarea" placeholder="请输入介绍内容" />
          </el-form-item>
          <el-form-item label="数量" prop="quantity">
            <el-input-number
              class="w-60%!"
              v-model="form.quantity"
              :min="1"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="规格" prop="specification">
            <el-input
              v-model="form.specification"
              placeholder="请输入规格（最多4个字符）"
              maxlength="4"
            />
          </el-form-item>
          <el-form-item label="起拍价" prop="startingPrice">
            <el-input-number
              class="w-60%!"
              v-model="form.startingPrice"
              :min="1"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="最低加价幅度" prop="minIncrement">
            <el-input-number
              class="w-60%!"
              v-model="form.minIncrement"
              :min="1"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="竞拍次数上限" prop="bidLimit">
            <el-input-number
              class="w-60%!"
              v-model="form.bidLimit"
              :min="1"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="竞拍时间" prop="startTime">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="X"
            />
          </el-form-item>
          <el-form-item label="展示竞拍" prop="isDisplay">
            <el-switch
              v-model="form.isDisplay"
              :active-value="1"
              :inactive-value="0"
              active-text="是"
              inactive-text="否"
            />
          </el-form-item>
          <el-form-item v-if="form.id" label="竞拍状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择竞拍状态" class="w-60%!">
              <el-option
                v-for="item in editAuctionStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          <el-icon class="btn-icon"><Upload /></el-icon>
          保存
        </el-button>
      </template>
    </el-dialog>

    <AuctionRecordDialog ref="auctionRecordDialogRef" />
  </div>
</template>

<script setup lang="tsx">
import { Search, Plus, Upload } from '@element-plus/icons-vue'
import { usePageSearch, useResetData } from '@/hooks'
import {
  getBackendAuctionList,
  addOrUpdateAuctionItem,
  deleteAuction,
  batchUpdateShowAuction,
} from '@/api/backend'
import type { FormInstance, FormRules } from 'element-plus'
import type { BackendAuctionListItemDto, BackendAddOrUpdateAuctionItemDto } from '@/api/backend'
import { AuctionStatusEnum, auctionStatusListOptions } from '@/constants'
import UploadFile from '@/components/common/UploadFile/index.vue'
import AuctionRecordDialog from './components/auctionRecordDialog.vue'
import dayjs from 'dayjs'
import { push } from 'notivue'
import { useMessageBox } from '@/hooks'

const { confirm } = useMessageBox()
const { loading, list, total, reset, goToPage, changePageSize, refresh, searchParams, search } =
  usePageSearch(getBackendAuctionList)

const auctionRecordDialogRef = ref<InstanceType<typeof AuctionRecordDialog>>()

// 对话框
const dialogVisible = ref(false)
const dialogTitle = computed(() => (form.value.id ? '编辑' : '新增'))
const formRef = ref<FormInstance>()

// 表单数据
const [form, resetForm] = useResetData<BackendAddOrUpdateAuctionItemDto>({
  id: undefined,
  imageUrl: '',
  name: '',
  description: '',
  quantity: 1,
  specification: '',
  startingPrice: 0,
  minIncrement: 0,
  bidLimit: 0,
  isDisplay: 0,
  startTime: '',
  endTime: '',
  status: undefined,
})

// 可编辑的 竞拍状态   只可以选择 「竞拍成功 / 已流拍」
const editAuctionStatusOptions = computed(() => {
  const options = auctionStatusListOptions
    .filter((item) =>
      [AuctionStatusEnum.AUCTION_SUCCESS, AuctionStatusEnum.AUCTION_FAILED].includes(item.value),
    )
    .map((item) => ({
      ...item,
      disabled: false,
    }))

  const hasCurrentStatus = options.some((item) => item.value === form.value.status)
  if (form.value.status !== undefined && !hasCurrentStatus) {
    const currentStatus = auctionStatusListOptions.find((item) => item.value === form.value.status)
    options.unshift({
      label: currentStatus?.label || `未知状态(${form.value.status})`,
      value: form.value.status,
      disabled: true,
    })
  }

  return options
})
// 表单验证规则
const formRules: FormRules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入介绍内容', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
  // specification: [{ required: true, message: '请输入规格', trigger: 'blur' }],
  startingPrice: [{ required: true, message: '请输入起拍价', trigger: 'blur' }],
  minIncrement: [{ required: true, message: '请输入最低加价幅度', trigger: 'blur' }],
  bidLimit: [{ required: true, message: '请输入竞拍次数上限', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择竞拍时间', trigger: 'change' }],
  isDisplay: [{ required: true, message: '请选择是否展示在前台', trigger: 'blur' }],
  imageUrl: [{ required: true, message: '请上传图片', trigger: 'change' }],
  status: [{ required: true, message: '请选择竞拍状态', trigger: 'change' }],
}
const dateRange = computed({
  get() {
    if (form.value.startTime && form.value.endTime) {
      return [form.value.startTime, form.value.endTime]
    }
    return []
  },
  set(value) {
    if (value) {
      form.value.startTime = value[0] || ''
      form.value.endTime = value[1] || ''
    } else {
      form.value.startTime = ''
      form.value.endTime = ''
    }
  },
})

const submitLoading = ref(false)

// 新增
const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: BackendAddOrUpdateAuctionItemDto) => {
  resetForm()
  form.value = {
    ...row,
  }
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: BackendAuctionListItemDto) => {
  const confirmDelete = row.currentPrice > 0
  await confirm({
    title: '提示',
    message: confirmDelete
      ? '该竞拍已有人出价，是否确定删除？删除后无法恢复，并会同步删除竞拍者的记录'
      : `确定要删除竞拍物品"${row.name}"吗?`,
    type: 'danger',
  })

  await deleteAuction({ idList: [row.id], confirmDelete })
  refresh()
  push.success('删除成功')
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    submitLoading.value = true
    await formRef.value.validate()

    if (form.value.id) {
      await addOrUpdateAuctionItem(form.value)
    } else {
      await addOrUpdateAuctionItem(form.value)
    }

    push.success(form.value.id ? '编辑成功' : '新增成功')
    dialogVisible.value = false
    if (form.value.id) {
      search()
    } else {
      refresh()
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleBatchShow = async () => {
  const show = ref(1)
  await ElMessageBox({
    title: '是否展示竞拍',
    message: () => (
      <el-radio-group v-model={show.value}>
        <el-radio value={1}>是</el-radio>
        <el-radio value={0}>否</el-radio>
      </el-radio-group>
    ),
    showCancelButton: true,
    async beforeClose(action, instance, done) {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        try {
          await batchUpdateShowAuction({
            idList: selectedRows.value.map((item) => item.id),
            isDisplay: show.value,
          })
          push.success('批量修改展示竞拍成功')
          refresh()
          done()
        } catch (error) {
          console.error(error)
        } finally {
          instance.confirmButtonLoading = false
        }
      } else {
        done()
      }
    },
  })
}

const handleBatchDelete = async () => {
  const bidRows = selectedRows.value.filter((item) => item.currentPrice > 0)
  const unbidRows = selectedRows.value.filter((item) => item.currentPrice === 0)
  const formatNames = (rows: BackendAuctionListItemDto[]) =>
    rows.map((item) => `【${item.name}】`).join('')

  let message = `确定要删除竞拍物品${formatNames(unbidRows)}吗？`
  if (bidRows.length && unbidRows.length) {
    message = `其中${formatNames(bidRows)}这些竞拍已有人出价，是否确定删除？删除后无法恢复，并会同步删除竞拍者的记录，其余${formatNames(unbidRows)}未出价会正常删除，确定删除吗？`
  } else if (bidRows.length) {
    message = `${formatNames(bidRows)}这些竞拍已有人出价，是否确定删除？删除后无法恢复，并会同步删除竞拍者的记录，确定删除吗？`
  }

  await confirm({
    title: '提示',
    message,
    type: 'danger',
  })

  if (unbidRows.length && bidRows.length) {
    await Promise.all([
      deleteAuction({
        idList: unbidRows.map((item) => item.id),
        confirmDelete: false,
      }),
      deleteAuction({
        idList: bidRows.map((item) => item.id),
        confirmDelete: true,
      }),
    ])
  } else {
    const rows = bidRows.length ? bidRows : unbidRows
    await deleteAuction({
      idList: rows.map((item) => item.id),
      confirmDelete: bidRows.length > 0,
    })
  }
  refresh()
  push.success('删除成功')
}

const selectedRows = ref<BackendAuctionListItemDto[]>([])
// 选择
const handleSelectionChange = (selection: BackendAuctionListItemDto[]) => {
  selectedRows.value = selection
}

const handleAuctionRecord = async (row: BackendAuctionListItemDto) => {
  auctionRecordDialogRef.value?.open(row.id)
}
</script>

<style scoped lang="scss">
.official-tag-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

// 搜索区域
.search-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px 0;
  flex-shrink: 0;

  .search-select {
    width: 200px;
  }
}

// 表格区域
.table-section {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-wrapper {
  flex: 1;
  min-height: 0;

  .color-cell {
    display: flex;
    align-items: center;
    gap: 12px;

    .color-block {
      width: 100%;
      height: 36px;
      border-radius: 4px;
      border: 1px solid #e5e7eb;
      flex: 1;
    }

    .color-text {
      color: #fff;
      font-size: 14px;
      font-weight: 500;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      text-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
    }
  }
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  flex-shrink: 0;
}

// 对话框内的颜色显示
.color-value {
  margin-left: 12px;
  color: #606266;
  font-family: monospace;
}

.btn-icon {
  margin-right: 4px;
}
</style>
