import { request, type ApiResponse, type PagedResult } from '@/utils/request'

// ==================== 盒子类型枚举 ====================

/** 
 * 盒子类型枚举
 * 注意：这里的值对应数据库 goods_types 表的 value 字段
 */
export enum GoodsType {
  YiFanShang = 1,       // 一番赏
  WuXianShang = 2,      // 无限赏
  ShangChengShang = 10, // 商城赏
  FuLiWu = 15,          // 福利屋
}

/** 盒子类型标签映射 */
export const GoodsTypeLabels: Record<number, string> = {
  [GoodsType.YiFanShang]: '一番赏',
  [GoodsType.WuXianShang]: '无限赏',
  [GoodsType.ShangChengShang]: '商城赏',
  [GoodsType.FuLiWu]: '福利屋',
}

// ==================== 盒子相关类型定义 ====================

/** 盒子列表查询参数 */
export interface GoodsListQuery {
  title?: string
  status?: number
  type?: number
  page: number
  pageSize: number
}

/** 盒子列表项 */
export interface GoodsListItem {
  id: number
  title: string
  imgUrl: string
  price: number
  type: number
  typeName: string
  status: number
  stock: number
  saleStock: number
  remainingStock: number
  sort: number
  flwStartTime: string | null
  flwEndTime: string | null
  openTime: string | null
  choujiangXianzhi: number
  unlockAmount: number
  createdAt: string
  updatedAt: string
}

/** 盒子详情 */
export interface GoodsDetail extends GoodsListItem {
  imgUrlDetail: string
  imgUrlBanner?: string
  categoryId: number
  dailyLimit: number
  lockIs: number
  lockTime: string | null
  integralIs: number
  showIs: number
  couponIs: number
  couponPro: number
  flwStartTime: string | null
  flwEndTime: string | null
  openTime: string | null
  choujiangXianzhi: number
  unlockAmount: number
  goodsDescribe: string | null
  newIs: number
  isShouZhe: number
  rageIs: number
  rage: number
  lingzhuIs: number
  lingzhuFan: number
  prizeNum: number
  isFlw: number
}

/** 创建盒子请求 */
export interface GoodsCreateRequest {
  title: string
  price: number
  type: number
  imgUrl: string
  imgUrlDetail: string
  imgUrlBanner?: string | null
  stock: number
  sort: number
  dailyLimit: number
  lockIs: number
  lockTime: number
  integralIs: number
  showIs: number
  couponIs: number
  couponPro: number
  flwStartTime?: string | null
  flwEndTime?: string | null
  openTime?: string | null
  choujiangXianzhi?: number
  categoryId: number
  goodsDescribe?: string | null
  newIs: number
  isShouZhe: number
  rageIs: number
  rage: number
  lingzhuIs: number
  lingzhuFan: number
  isAutoXiajia?: number
  xiajiaLirun?: number
  xiajiaAutoCoushu?: number
  xiajiaJine?: number
  unlockAmount?: number
}

/** 更新盒子请求 */
export interface GoodsUpdateRequest extends GoodsCreateRequest {}

/** 盒子状态请求 */
export interface GoodsStatusRequest {
  status: number
}

// ==================== 盒子管理 API ====================

const GOODS_BASE_URL = '/admin/business/goods'

/** 获取盒子列表 */
export function getGoodsList(params: GoodsListQuery): Promise<ApiResponse<PagedResult<GoodsListItem>>> {
  return request({
    url: GOODS_BASE_URL,
    method: 'get',
    params
  })
}

/** 获取盒子详情 */
export function getGoodsDetail(id: number): Promise<ApiResponse<GoodsDetail>> {
  return request({
    url: `${GOODS_BASE_URL}/${id}`,
    method: 'get'
  })
}

/** 创建盒子 */
export function createGoods(data: GoodsCreateRequest): Promise<ApiResponse<{ id: number }>> {
  return request({
    url: GOODS_BASE_URL,
    method: 'post',
    data
  })
}

/** 更新盒子 */
export function updateGoods(id: number, data: GoodsUpdateRequest): Promise<ApiResponse<string>> {
  return request({
    url: `${GOODS_BASE_URL}/${id}`,
    method: 'put',
    data
  })
}

/** 删除盒子 */
export function deleteGoods(id: number): Promise<ApiResponse<string>> {
  return request({
    url: `${GOODS_BASE_URL}/${id}`,
    method: 'delete'
  })
}

/** 设置盒子状态（上架/下架） */
export function setGoodsStatus(id: number, status: number): Promise<ApiResponse<string>> {
  return request({
    url: `${GOODS_BASE_URL}/${id}/status`,
    method: 'put',
    data: { status }
  })
}

/** 复制盒子（含奖品） */
export function copyGoods(id: number): Promise<ApiResponse<{ id: number }>> {
  return request({
    url: `${GOODS_BASE_URL}/${id}/copy`,
    method: 'post'
  })
}

/** 清空盒子抽奖记录 */
export function clearGoodsLottery(id: number): Promise<ApiResponse<string>> {
  return request({
    url: `${GOODS_BASE_URL}/${id}/clear-lottery`,
    method: 'post'
  })
}


// ==================== 奖品相关类型定义 ====================

/** 奖品分类枚举 */
export enum PrizeCategory {
  XianHuo = 1,    // 现货
  YuShou = 2,     // 预售
  HuoBi = 3,      // 货币
  BaoXiang = 4,   // 宝箱
}

/** 奖品分类标签映射 */
export const PrizeCategoryLabels: Record<number, string> = {
  [PrizeCategory.XianHuo]: '现货',
  [PrizeCategory.YuShou]: '预售',
  [PrizeCategory.HuoBi]: '货币',
  [PrizeCategory.BaoXiang]: '宝箱',
}

/** 奖品列表项 */
export interface PrizeItem {
  id: number
  goodsId: number
  num: number
  title: string
  imgUrl: string
  imgUrlDetail: string | null
  stock: number
  surplusStock: number
  price: number
  money: number
  scMoney: number
  realPro: number
  goodsType: number
  sort: number
  shangId: number | null
  shangTitle: string | null
  shangColor: string | null
  rewardNum: number
  rank: number
  giveMoney: number
  cardNo: string | null
  prizeCode: string | null
  type: number
  lianJiType: number
  rewardId: string | null
  doubling: number
  isLingzhu: number
  goodsListId: number  // 父奖品ID，0表示父奖品，>0表示子奖品
  rewards?: PrizeRewardItem[]  // 奖励配置
  createdAt: string | null
  updatedAt: string
  children?: PrizeItem[]  // 子奖品列表（前端构建树形结构用）
}

/** 奖品奖励配置项 */
export interface PrizeRewardItem {
  type: number    // 奖励类型：1=钻石 2=UU币 3=哈尼券
  amount: number  // 数量
}

/** 创建奖品请求 */
export interface PrizeCreateRequest {
  title: string
  imgUrl: string
  imgUrlDetail?: string
  stock: number
  price: number
  money: number
  scMoney: number
  realPro: number
  goodsType: number
  sort: number
  shangId?: number
  rewardNum: number
  rank: number
  giveMoney: number
  cardNo?: string
  type: number
  lianJiType: number
  rewardId?: string
  doubling: number
  isLingzhu: number
  goodsListId?: number  // 父奖品ID，添加宝箱子奖品时使用
  rewards?: PrizeRewardItem[]  // 奖励配置
}

/** 更新奖品请求 */
export interface PrizeUpdateRequest extends PrizeCreateRequest {}

// ==================== 奖品管理 API ====================

const PRIZES_BASE_URL = '/admin/business/prizes'

/** 获取盒子奖品列表 */
export function getGoodsPrizes(goodsId: number): Promise<ApiResponse<PrizeItem[]>> {
  return request({
    url: `${GOODS_BASE_URL}/${goodsId}/prizes`,
    method: 'get'
  })
}

/** 添加奖品 */
export function addPrize(goodsId: number, data: PrizeCreateRequest): Promise<ApiResponse<{ id: number }>> {
  return request({
    url: `${GOODS_BASE_URL}/${goodsId}/prizes`,
    method: 'post',
    data
  })
}

/** 更新奖品 */
export function updatePrize(id: number, data: PrizeUpdateRequest): Promise<ApiResponse<string>> {
  return request({
    url: `${PRIZES_BASE_URL}/${id}`,
    method: 'put',
    data
  })
}

/** 删除奖品 */
export function deletePrize(id: number): Promise<ApiResponse<string>> {
  return request({
    url: `${PRIZES_BASE_URL}/${id}`,
    method: 'delete'
  })
}

// ==================== 盒子类型相关类型定义 ====================

/** 盒子类型项 */
export interface GoodsTypeItem {
  id: number
  name: string
  value: number
  sortOrder: number
  isShow: number
  isFenlei: number
  flName: string
  cornerText: string | null
  payWechat: number
  payBalance: number
  payCurrency: number
  payCurrency2: number
  payCoupon: number
  isDeduction: number
  remark: string | null
}

/** 创建盒子类型请求 */
export interface GoodsTypeCreateRequest {
  name: string
  value: number
  sortOrder: number
  isShow: number
  isFenlei: number
  flName: string
  cornerText?: string
  payWechat: number
  payBalance: number
  payCurrency: number
  payCurrency2: number
  payCoupon: number
  isDeduction: number
  remark?: string
}

/** 更新盒子类型请求 */
export interface GoodsTypeUpdateRequest extends GoodsTypeCreateRequest {}

/** 盒子类型状态请求 */
export interface GoodsTypeStatusRequest {
  type: string   // is_show-首页显示 is_fenlei-分类显示
  value: number  // 0-否 1-是
}

// ==================== 盒子类型管理 API ====================

const GOODS_TYPES_BASE_URL = '/admin/business/goods-types'

/** 货币名称配置 */
export interface CurrencyNames {
  balanceName: string
  currency1Name: string
  currency2Name: string
}

/** 盒子类型列表响应 */
export interface GoodsTypesResponse {
  list: GoodsTypeItem[]
  currencyNames: CurrencyNames
}

/** 获取盒子类型列表 */
export function getGoodsTypes(): Promise<ApiResponse<GoodsTypesResponse>> {
  return request({
    url: GOODS_TYPES_BASE_URL,
    method: 'get'
  })
}

/** 创建盒子类型 */
export function createGoodsType(data: GoodsTypeCreateRequest): Promise<ApiResponse<{ id: number; message: string }>> {
  return request({
    url: GOODS_TYPES_BASE_URL,
    method: 'post',
    data
  })
}

/** 更新盒子类型 */
export function updateGoodsType(id: number, data: GoodsTypeUpdateRequest): Promise<ApiResponse<{ success: boolean; message: string }>> {
  return request({
    url: `${GOODS_TYPES_BASE_URL}/${id}`,
    method: 'put',
    data
  })
}

/** 删除盒子类型 */
export function deleteGoodsType(id: number): Promise<ApiResponse<{ success: boolean; message: string }>> {
  return request({
    url: `${GOODS_TYPES_BASE_URL}/${id}`,
    method: 'delete'
  })
}

/** 修改盒子类型状态 */
export function setGoodsTypeStatus(id: number, data: GoodsTypeStatusRequest): Promise<ApiResponse<{ success: boolean; message: string }>> {
  return request({
    url: `${GOODS_TYPES_BASE_URL}/${id}/status`,
    method: 'put',
    data
  })
}

// ==================== 盒子扩展设置相关类型定义 ====================

/** 盒子扩展设置 */
export interface GoodsExtendItem {
  id: number
  goodsId: number
  payWechat: number
  payBalance: number
  payCurrency: number
  payCurrency2: number
  payCoupon: number
  isDeduction: number
  isInherited: boolean
}

/** 更新盒子扩展设置请求 */
export interface GoodsExtendUpdateRequest {
  payWechat: number
  payBalance: number
  payCurrency: number
  payCurrency2: number
  payCoupon: number
  isDeduction: number
}

// ==================== 盒子扩展设置 API ====================

/** 获取盒子扩展设置 */
export function getGoodsExtend(goodsId: number): Promise<ApiResponse<GoodsExtendItem>> {
  return request({
    url: `${GOODS_BASE_URL}/${goodsId}/extend`,
    method: 'get'
  })
}

/** 更新盒子扩展设置 */
export function updateGoodsExtend(goodsId: number, data: GoodsExtendUpdateRequest): Promise<ApiResponse<string>> {
  return request({
    url: `${GOODS_BASE_URL}/${goodsId}/extend`,
    method: 'put',
    data
  })
}

/** 删除盒子扩展设置（恢复使用类型默认配置） */
export function deleteGoodsExtend(goodsId: number): Promise<ApiResponse<string>> {
  return request({
    url: `${GOODS_BASE_URL}/${goodsId}/extend`,
    method: 'delete'
  })
}
