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

      <el-select
        v-model="searchParams.status"
        placeholder="请选择发布状态"
        class="search-select mx-12px"
        clearable
      >
        <el-option label="待发货" :value="0" />
        <el-option label="已发货" :value="1" />
        <el-option label="已取消" :value="2" />
      </el-select>
      <el-select
        v-model="searchParams.source"
        placeholder="请选择来源"
        class="search-select"
        clearable
      >
        <el-option label="商城" :value="1" />
        <el-option label="大转盘" :value="2" />
        <el-option label="每日抽奖" :value="3" />
      </el-select>
      <el-button type="primary" @click="refresh" class="ml-12px">
        <el-icon><IEpSearch /></el-icon>
        搜索
      </el-button>
      <el-button @click="reset">重置</el-button>
      <ExportExcelBtn
        :api="exportShopItemList"
        :searchParams="searchParams"
        :columns="columns"
        fileName="商品分发数据"
      />
    </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="itemName" 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="source" label="来源" min-width="200">
            <template #default="{ row }">
              {{ row.source === 1 ? '商城' : row.source === 2 ? '大转盘' : '每日抽奖' }}
            </template>
          </el-table-column>
          <el-table-column prop="num" label="兑换数量" min-width="200"> </el-table-column>

          <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="userName" label="兑换人" min-width="200" />
          <el-table-column prop="issuerName" label="发放人" min-width="200" />
          <el-table-column prop="memo" label="发放备注" min-width="200" />

          <el-table-column prop="issueTime" label="发放时间" min-width="200">
            <template #default="{ row }">
              {{
                row.issueTime ? dayjs(row.issueTime * 1000).format('YYYY-MM-DD HH:mm:ss') : '未发货'
              }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="发放状态" min-width="200">
            <template #default="{ row }">
              {{ row.status === 0 ? '待发货' : row.status === 1 ? '已发货' : '已取消' }}
            </template>
          </el-table-column>
          <el-table-column prop="memo" label="发放人备注" min-width="200" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button v-if="row.status === 0" type="primary" link @click="handleIssue(row)">
                发放
              </el-button>
              <el-button
                v-if="row.status === 1"
                type="warning"
                link
                @click="handleCancelIssue(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="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="form.color" />
          <span class="color-value">{{ form.color }}</span>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="100" />
        </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"><IEpUpload /></el-icon>
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { usePageSearch, useResetData } from '@/hooks'
import {
  addOrUpdateColumn,
  getBackendExchangeList,
  issueProduct,
  exportShopItemList,
} from '@/api/backend'
import type { FormInstance, FormRules } from 'element-plus'
import type {
  BackendColumnListItemDto,
  AddOrUpdateColumnDto,
  BackendShopItemDto,
} from '@/api/backend'
import dayjs from 'dayjs'
import ExportExcelBtn from '@/components/common/ExportExcelBtn/index.vue'
import type { ExportColumn } from '@/utils'
import { push } from 'notivue'
import { useMessageBox } from '@/hooks'

const { confirm, prompt } = useMessageBox()
const { loading, list, total, reset, goToPage, changePageSize, refresh, searchParams, search } =
  usePageSearch(getBackendExchangeList, {
    defaultParams: {},
  })

const columns: ExportColumn<BackendShopItemDto>[] = [
  {
    title: '商品名称',
    key: 'itemName',
  },

  {
    title: '图片',
    key: 'imageUrl',
  },
  {
    title: '来源',
    key: 'source',
    formatter: (value) => {
      return value === 1 ? '商城' : value === 2 ? '大转盘' : '每日抽奖'
    },
  },

  {
    title: '兑换数量',
    key: 'num',
  },
  {
    title: '兑换时间',
    key: 'createTime',
    formatter: (value) => {
      return dayjs((value as number) * 1000).format('YYYY-MM-DD HH:mm:ss')
    },
  },
  {
    title: '兑换人',
    key: 'userName',
  },
  {
    title: '发放人',
    key: 'issuerName',
  },

  {
    title: '发放备注',
    key: 'memo',
  },
  {
    title: '发放时间',
    key: 'issueTime',
    formatter: (value) => {
      return value ? dayjs((value as number) * 1000).format('YYYY-MM-DD HH:mm:ss') : '未发货'
    },
  },
  {
    title: '发放状态',
    key: 'status',
    formatter: (value) => {
      return value === 0 ? '待发货' : value === 1 ? '已发货' : '已取消'
    },
  },
  {
    title: '发放人备注',
    key: 'memo',
  },
]

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

// 表单数据

const [form] = useResetData<AddOrUpdateColumnDto>({
  title: '',
  color: '#000000',
  id: undefined,
  sort: 0,
  type: 'column',
})
// 表单验证规则
const formRules: FormRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  color: [{ required: true, message: '请选择颜色', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
}

// 取消发放
const handleCancelIssue = async (row: BackendColumnListItemDto) => {
  await confirm({
    title: '提示',
    message: '确定要取消发放吗?',
    confirmText: '确定',
    cancelText: '取消',
    type: 'warning',
  })
  await issueProduct({
    id: row.id,
    status: 0,
  })
  push.success('取消发放成功')
  refresh()
}

// 发放
const handleIssue = async (row: BackendColumnListItemDto) => {
  // 弹出message输入框 填写发放备注
  const memo = await prompt({
    title: '请输入发放备注',
    type: 'primary',
  })
  await issueProduct({
    id: row.id,
    memo,
    status: 1,
  })
  push.success('发放成功')
  refresh()
}

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

  try {
    await formRef.value.validate()

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

    push.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
}
</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>
