package com.haha.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.admin.annotation.RequirePermission;
import com.haha.entity.dto.NewProductApplyQueryDTO;
import com.haha.entity.dto.NewProductApplySubmitDTO;
import com.haha.common.annotation.Log;
import com.haha.common.enums.ApplyStatus;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.NewProductApply;
import com.haha.service.NewProductApplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 新品申请控制器
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/new-product-apply")
public class NewProductApplyController {

    private final NewProductApplyService newProductApplyService;

    /**
     * 分页查询新品申请列表
     * @param params 查询参数
     * @return 申请列表
     */
    @RequirePermission("product-apply:read")
    @GetMapping("/list")
    public Result<PageResult<NewProductApply>> list(NewProductApplyQueryDTO queryDTO) {
        queryDTO.validate();
        
        IPage<NewProductApply> pageResult = newProductApplyService.getPage(
                queryDTO.getPage(), queryDTO.getPageSize(), queryDTO);
        
        return Result.success("查询成功", PageResult.of(pageResult));
    }

    /**
     * 获取申请详情
     * @param id 申请ID
     * @return 申请详情
     */
    @RequirePermission("product-apply:read")
    @GetMapping("/{id}")
    public Result<NewProductApply> getById(@PathVariable Long id) {
        NewProductApply apply = newProductApplyService.getById(id);
        return Result.success(apply);
    }

    /**
     * 获取申请统计信息
     * @return 统计信息
     */
    @RequirePermission("product-apply:read")
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics() {
        Map<String, Object> stats = newProductApplyService.getStatistics();
        return Result.success(stats);
    }

    /**
     * 提交新品申请
     * @param apply 申请信息
     * @return 申请ID
     */
    @RequirePermission("product-apply:create")
    @Log(module = "新品申请", operation = OperationType.INSERT, summary = "提交新品申请")
    @PostMapping("/submit")
    public Result<Long> submit(@RequestBody NewProductApplySubmitDTO dto) {
        try {
            Long userId = StpUtil.getLoginIdAsLong();
            String userName = StpUtil.getLoginIdAsString();
            Long id = newProductApplyService.submitApply(dto, userId, userName);
            return Result.success("新品申请已提交，请等待审核", id);
        } catch (Exception e) {
            log.error("提交新品申请失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 保存草稿（仅保存到本地数据库，不提交到哈哈平台）
     * @param apply 申请信息
     * @return 申请ID
     */
    @RequirePermission("product-apply:create")
    @Log(module = "新品申请", operation = OperationType.INSERT, summary = "保存新品申请草稿")
    @PostMapping("/save-draft")
    public Result<Long> saveDraft(@RequestBody NewProductApplySubmitDTO dto) {
        try {
            Long userId = StpUtil.getLoginIdAsLong();
            String userName = StpUtil.getLoginIdAsString();
            Long id = newProductApplyService.saveDraft(dto, userId, userName);
            return Result.success("草稿保存成功", id);
        } catch (Exception e) {
            log.error("保存草稿失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新申请信息
     * @param id 申请ID
     * @param apply 申请信息
     * @return 是否成功
     */
    @RequirePermission("product-apply:update")
    @Log(module = "新品申请", operation = OperationType.UPDATE, summary = "更新新品申请")
    @PutMapping("/{id}")
    public Result<Boolean> update(@PathVariable Long id, @RequestBody NewProductApplySubmitDTO dto) {
        try {
            NewProductApply existing = newProductApplyService.getById(id);
            if (existing == null) {
                return Result.error("申请记录不存在");
            }
            if (existing.getStatus() != ApplyStatus.DRAFT.getCode()) {
                return Result.error("只有待提交状态的申请才能修改");
            }
            newProductApplyService.updateApply(id, dto);
            return Result.success("更新成功", true);
        } catch (Exception e) {
            log.error("更新申请失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除申请（仅待提交状态可删除）
     * @param id 申请ID
     * @return 是否成功
     */
    @RequirePermission("product-apply:delete")
    @Log(module = "新品申请", operation = OperationType.DELETE, summary = "删除新品申请")
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        try {
            NewProductApply existing = newProductApplyService.getById(id);
            if (existing == null) {
                return Result.error("申请记录不存在");
            }
            
            // 只有待提交状态才能删除
            if (existing.getStatus() != ApplyStatus.DRAFT.getCode()) {
                return Result.error("只有待提交状态的申请才能删除");
            }
            
            newProductApplyService.removeById(id);
            return Result.success("删除成功", true);
        } catch (Exception e) {
            log.error("删除申请失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查询商品总库中是否存在该条码的商品
     * @param barcode 商品条码
     * @return 商品信息（如果存在）
     */
    @RequirePermission("product-apply:read")
    @GetMapping("/check-barcode")
    public Result<Map<String, Object>> checkBarcode(@RequestParam String barcode) {
        try {
            // 调用哈哈平台API查询商品总库
            Map<String, Object> result = newProductApplyService.checkBarcodeInTotalList(barcode);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询条码失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 主动刷新新品申请审核状态（回调补偿机制）
     * @param id 申请ID
     * @return 最新的申请状态
     */
    @RequirePermission("product-apply:read")
    @PostMapping("/{id}/refresh-status")
    public Result<Map<String, Object>> refreshStatus(@PathVariable Long id) {
        NewProductApply apply = newProductApplyService.getById(id);
        if (apply == null) {
            return Result.error(404, "申请记录不存在");
        }
        Map<String, Object> result = newProductApplyService.getNewGoodsInfo(
                apply.getHahaCode(), apply.getHahaApplyId());
        return Result.success("刷新成功", result);
    }
}
