package com.wzj.soopin.order.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wzj.soopin.order.convert.OrderConvert;
import com.wzj.soopin.order.domain.bo.OrderBo;
import com.wzj.soopin.order.domain.entity.Order;
import com.wzj.soopin.order.domain.vo.ManagerOrderDetailVO;
import com.wzj.soopin.order.domain.vo.OrderVO;
import com.wzj.soopin.order.service.OrderItemService;
import com.wzj.soopin.order.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.redis.redis.RedisService;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.web.core.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
/**
 * 订单管理
 *
 * @author zcc
 * &#064;date  2022-12-01
 */
@Tag(name = "订单管理")
@RestController
@RequestMapping("/oms/order")
@Slf4j
@RequiredArgsConstructor
@Validated
public class OrderController extends BaseController {

    private final OrderConvert convert;

    private final RedisService redisService;

    private final OrderService orderService;

    private final OrderItemService orderItemService;


    @Operation(summary = "分页查询当前商铺的订单列表")
    @PostMapping("/merchant/list")
    public R<IPage<OrderVO>> merchantOrderList(@RequestBody OrderBo query){
        return R.ok(orderService.merchantOrderList(query));
    }


    @Operation(summary = "分页查询团长绑定会员的订单列表")
    @PostMapping("/reference/list")
    public R<IPage<OrderVO>> referenceMemberOrderList(@RequestBody OrderBo query){
        return R.ok(orderService.referenceMemberOrderList(query));
    }


    @Operation(summary = "修改收件人信息")
    @PostMapping("/receiver/update")
    public R updateReceiver(@RequestBody Order order) {
        return R.ok(orderService.updateById(order));
    }


    @Operation(summary = "导出订单表列表")
    @Log(title = "订单售后", businessType = BusinessType.EXPORT)
    @PostMapping("export")
    public R<String> export(OrderBo query) {
        List<Order> list = orderService.list(query.toWrapper());
        ExcelUtil<OrderVO> util = new ExcelUtil<>(OrderVO.class);
        return R.ok(util.writeExcel(convert.toVO(list), "订单列表数据"));
    }


    @Operation(summary = "获取订单详细信息")
    @GetMapping(value = "/{id}")
    public R<ManagerOrderDetailVO> getInfo(@PathVariable("id") Long id) {
        return R.ok(orderService.selectById(id));
    }



    @Operation(summary = "修改订单表")
    @Log(title = "订单表", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public R edit(@RequestBody Order order) {
        return R.ok(orderService.updateById(order));
    }


    @Operation(summary = "删除订单表")
    @Log(title = "订单表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{id}")
    public R remove(@PathVariable Long id) {
        return R.ok(orderService.removeById(id));
    }


    @Operation(summary = "添加备注")
    @Log(title = "订单表", businessType = BusinessType.UPDATE)
    @PostMapping("/merchantNote/add")
    public R saveMerchantNote(@RequestBody Order order){
       return orderService.saveMerchantNote(order);
    }



    @Operation(summary = "订单日志")
    @GetMapping("/log/{orderId}")
    public R log(@PathVariable Long orderId){
        return R.ok (orderService.log(orderId));
    }


    @Operation(summary = "订单解密")
    @GetMapping("/decryptPhone/{orderId}")
    public R decryptPhone(@PathVariable Long orderId){
        return orderService.decryptPhone(orderId);
    }


    @Operation(summary = "手动触发缓存交易量最多商品")
    @PostMapping("/cacheTopTradingProducts")
    public R<Void> cacheTopTradingProducts(@RequestParam(defaultValue = "100") int limit) {
        try {
            orderItemService.cacheTopTradingProducts(limit);
            return R.ok();
        } catch (Exception e) {
            log.error("手动触发缓存交易量最多商品失败", e);
            return R.fail("缓存失败: " + e.getMessage());
        }
    }


    @Operation(summary = "获取缓存交易量最多商品")
    @GetMapping("/getTopTradingProducts")
    public R<Object> getTopTradingProducts(@RequestParam(required = false) String date) {
        try {
            String redisKey;
            if (date != null && !date.isEmpty()) {
                redisKey = "top_trading_products:" + date;
            } else {
                redisKey = "top_trading_products:" + java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            }

            String jsonData = RedisUtils.getCacheObject(redisKey);
            if (jsonData != null && !jsonData.isEmpty()) {
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.registerModule(new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule());
                return R.ok(objectMapper.readValue(jsonData, Object.class));
            } else {
                return R.ok("未找到缓存数据");
            }
        } catch (Exception e) {
            log.error("获取缓存交易量最多商品失败", e);
            return R.fail("获取失败: " + e.getMessage());
        }
    }



}
