<template>
  <div class="official-tag-page">
    <!-- 搜索栏 -->
    <div class="search-section">
      <div class="flex-1 flex gap-2">
        <el-input
          v-model="searchParams.name"
          placeholder="请输入商品名称"
          class="w-200px"
        ></el-input>

        <el-select
          v-model="searchParams.itemType"
          placeholder="请选择商品类型"
          class="search-select"
          clearable
        >
          <el-option label="实物" :value="ShopGoodsTypeEnum.REAL_GOODS" />
          <el-option label="虚拟" :value="ShopGoodsTypeEnum.VIRTUAL_GOODS" />
        </el-select>
        <el-select
          v-model="searchParams.region"
          placeholder="请选择上架地区"
          class="search-select"
          clearable
        >
          <el-option
            v-for="item in regionListOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="searchParams.enable"
          placeholder="是否展示在前台"
          class="search-select"
          clearable
        >
          <el-option label="是" :value="BooleanFlag.YES" />
          <el-option label="否" :value="BooleanFlag.NO" />
        </el-select>
        <el-button type="primary" :icon="Search" @click="refresh">搜索</el-button>
        <el-button @click="reset">重置</el-button>
      </div>

      <div class="flex justify-end">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
      </div>
    </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="sortOrder" label="商品排序" min-width="200" />
          <el-table-column prop="name" label="商品名称" min-width="200" />
          <el-table-column prop="itemTypeName" label="商品类型" min-width="200" />
          <el-table-column prop="description" label="商品描述" min-width="200" />
          <el-table-column prop="imageUrl" label="图片" width="300">
            <template #default="{ row }">
              <el-image
                :preview-teleported="true"
                :src="row.imageUrl"
                class="w-20 h-20 object-cover"
                :preview-src-list="[row.imageUrl]"
              />
            </template>
          </el-table-column>
          <el-table-column prop="region" label="上架地区" min-width="200"> </el-table-column>
          <el-table-column prop="stock" label="库存数量" min-width="200"> </el-table-column>

          <el-table-column prop="price" label="兑换所需YA币" min-width="200"> </el-table-column>

          <el-table-column prop="showName" label="创建人" min-width="200" />

          <el-table-column prop="createTime" label="创建时间" min-width="200">
            <template #default="{ row }">
              {{ dayjs(row.createTime * 1000).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column prop="enable" label="是否展示在前台" min-width="200">
            <template #default="{ row }">
              <el-switch
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
                :model-value="row.enable"
                @change="handleEnableChange(row)"
              />
            </template>
          </el-table-column>

          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(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="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="auto">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品类型" prop="itemType">
          <el-select v-model="form.itemType" placeholder="请选择商品类型">
            <el-option label="实物" :value="ShopGoodsTypeEnum.REAL_GOODS" />
            <el-option label="虚拟" :value="ShopGoodsTypeEnum.VIRTUAL_GOODS" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" v-model="form.description" placeholder="请输入商品描述" />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <UploadFile v-model="form.imageUrl" :limit="1" />
        </el-form-item>
        <el-form-item label="上架地区" prop="region">
          <el-select v-model="form.region" placeholder="请选择上架地区">
            <el-option
              v-for="item in regionListOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="兑换所需YA币" prop="price">
          <el-input-number v-model="form.price" placeholder="请输入" :min="0" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input-number v-model="form.stock" placeholder="请输入" :min="0" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" placeholder="请输入" :min="0" />
        </el-form-item>
        <el-form-item label="是否展示在前台" prop="enable">
          <el-switch
            v-model="form.enable"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          <el-icon class="btn-icon"><Upload /></el-icon>
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Search, Plus, Upload } from '@element-plus/icons-vue'
import { usePageSearch, useResetData } from '@/hooks'
import { getShopItemList, addOrUpdateShopItem, deleteShopItem } from '@/api/backend'
import type { FormInstance, FormRules } from 'element-plus'
import type { BackendColumnListItemDto } from '@/api/backend'
import dayjs from 'dayjs'
import { BooleanFlag, ShopGoodsTypeEnum, regionListOptions } from '@/constants'
import UploadFile from '@/components/common/UploadFile/index.vue'
import type { BackendShopItemDto } from '@/api/backend'

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

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

// 表单数据

const [form, resetForm] = useResetData<BackendShopItemDto>({
  id: undefined,
  sort: 0,
  enable: 1,
  imageUrl: '',
  itemType: ShopGoodsTypeEnum.REAL_GOODS,
  name: '',
  price: 0,
  region: '',
  stock: 0,
  sortOrder: 0,
  description: '',
})
// 表单验证规则
const formRules: FormRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  color: [{ required: true, message: '请选择颜色', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
}

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

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

// 删除
const handleDelete = async (row: BackendColumnListItemDto) => {
  try {
    await ElMessageBox.confirm(`确定要删除商品"${row.name}"吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await deleteShopItem(row.id)
    refresh()
    ElMessage.success('删除成功')
    refresh()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

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

  try {
    await formRef.value.validate()

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

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

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

const handleEnableChange = async (row: BackendColumnListItemDto) => {
  console.log(row)
  await addOrUpdateShopItem({
    id: row.id,
    enable: row.enable === BooleanFlag.YES ? BooleanFlag.NO : BooleanFlag.YES,
  })
  ElMessage.success('修改成功')
  refresh()
}
</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;
  gap: 12px;
  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>
