package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.Result;
import com.zhentao.entity.PointsOrder;
import com.zhentao.entity.PointsProduct;
import com.zhentao.mapper.PointsOrderMapper;
import com.zhentao.service.PointsOrderService;
import com.zhentao.service.PointsProductService;
import com.zhentao.service.SystemMessagesService;
import com.zhentao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 积分订单管理控制器
 */
@RestController
@RequestMapping("/admin/points-order")
@CrossOrigin(origins = "*")
public class PointsOrderController {
    
    @Autowired
    private PointsOrderService pointsOrderService;
    
    @Autowired
    private PointsOrderMapper pointsOrderMapper;
    
    @Autowired
    private SystemMessagesService systemMessagesService;
    @Autowired
    private PointsProductService productService;
    @Autowired
    private UserService userService;
    
    /**
     * 积分订单列表（分页查询）
     * @param page 页码
     * @param pageSize 每页数量
     * @param orderNo 订单号（模糊查询）
     * @param productName 产品名称（模糊查询）
     * @param review 审核状态（0-待审核，1-审核通过，2-审核未通过）
     * @param status 发货状态（0-待发货，1-已发货，2-已完成，3-已取消）
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> list(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "orderNo", required = false) String orderNo,
            @RequestParam(value = "productName", required = false) String productName,
            @RequestParam(value = "review", required = false) Integer review,
            @RequestParam(value = "status", required = false) Integer status) {
        
        try {
            Page<PointsOrder> pageInfo = new Page<>(page, pageSize);
            LambdaQueryWrapper<PointsOrder> queryWrapper = new LambdaQueryWrapper<>();
            
            // 只查询未删除的记录（is_del = 0）
            queryWrapper.eq(PointsOrder::getIsDel, 0);
            
            // 订单号模糊查询
            if (orderNo != null && !orderNo.trim().isEmpty()) {
                queryWrapper.like(PointsOrder::getOrderNo, orderNo.trim());
            }
            
            // 产品名称模糊查询
            if (productName != null && !productName.trim().isEmpty()) {
                queryWrapper.like(PointsOrder::getProductName, productName.trim());
            }
            
            // 审核状态查询
            if (review != null) {
                queryWrapper.eq(PointsOrder::getReview, review);
            }
            
            // 发货状态查询
            if (status != null) {
                queryWrapper.eq(PointsOrder::getStatus, status);
            }
            
            // 按创建时间倒序
            queryWrapper.orderByDesc(PointsOrder::getCreateTime);
            
            Page<PointsOrder> result = pointsOrderService.page(pageInfo, queryWrapper);
            
            Map<String, Object> data = new HashMap<>();
            data.put("list", result.getRecords());
            data.put("total", result.getTotal());
            data.put("page", page);
            data.put("pageSize", pageSize);
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 审核订单
     * @param id 订单ID
     * @param review 审核结果（1-审核通过，2-审核未通过）
     * @param reviewFail 审核失败说明（审核未通过时必填）
     */
    @PostMapping("/review/{id}")
    public Result<String> review(
            @PathVariable Long id,
            @RequestParam("review") Integer review,
            @RequestParam(value = "reviewFail", required = false) String reviewFail) {
        
        try {
            PointsOrder order = pointsOrderService.getById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            if (order.getIsDel() != null && order.getIsDel() == 1) {
                return Result.error("订单已删除");
            }
            
            // 验证审核结果
            if (review == null || (review != 1 && review != 2)) {
                return Result.error("审核结果无效，必须为1（通过）或2（不通过）");
            }
            
            // 如果审核不通过，必须提供失败说明
            if (review == 2) {
                if (reviewFail == null || reviewFail.trim().isEmpty()) {
                    return Result.error("审核不通过时必须填写审核失败说明");
                }
                PointsProduct byId = productService.getById(order.getProductId());
                Boolean boo = userService.updatePoints(byId.getPointsPrice(), order.getMakerId());

                order.setReviewFail(reviewFail.trim());
            } else {
                // 审核通过时清空失败说明
                order.setReviewFail(null);
            }
            
            order.setReview(review);
            order.setUpdateTime(new Date());
            
            boolean success = pointsOrderService.updateById(order);
            if (success) {
                System.out.println("订单审核更新成功，订单ID=" + id + ", 审核状态=" + review);
                System.out.println("订单信息 - 订单号: " + order.getOrderNo() + ", 收件人电话: " + order.getReceiverPhone());
                
                // 创建系统消息
                try {
                    System.out.println("开始调用系统消息创建方法...");
                    systemMessagesService.createPointsOrderReviewMessage(order);
                    System.out.println("系统消息创建方法调用完成");
                } catch (Exception e) {
                    // 系统消息创建失败不影响审核结果，只记录日志
                    System.err.println("创建系统消息失败：" + e.getMessage());
                    e.printStackTrace();
                }
                
                return Result.success(review == 1 ? "审核通过成功" : "审核不通过已记录");
            } else {
                return Result.error("审核失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除订单（逻辑删除）
     * @param id 订单ID
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        try {
            PointsOrder order = pointsOrderService.getById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            // 逻辑删除：设置is_del = 1
            order.setIsDel(1);
            order.setUpdateTime(new Date());
            
            boolean success = pointsOrderService.updateById(order);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取订单详情
     * @param id 订单ID
     */
    @GetMapping("/{id}")
    public Result<PointsOrder> detail(@PathVariable Long id) {
        try {
            PointsOrder order = pointsOrderService.getById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            if (order.getIsDel() != null && order.getIsDel() == 1) {
                return Result.error("订单已删除");
            }
            
            return Result.success(order);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
}

