package com.fs.app.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.fs.app.annotation.Login;
import com.fs.app.utils.JwtUtils;
import com.fs.common.annotation.Log;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.common.utils.sign.Md5Utils;
import com.fs.live.domain.Live;
import com.fs.live.domain.LiveOrder;
import com.fs.live.domain.LiveOrderPayment;
import com.fs.live.enums.LiveOrderCancleReason;
import com.fs.live.param.FsUserLiveOrderPayUParam;
import com.fs.live.param.LiveOrderCancelParam;
import com.fs.live.param.LiveOrderConfirmParam;
import com.fs.live.service.ILiveOrderPaymentService;
import com.fs.live.service.ILiveOrderService;
import com.fs.live.vo.LiveOrderListVo;
import com.fs.live.vo.LiveOrderQueryVO;
import com.fs.store.domain.FsStoreOrder;
import com.fs.store.dto.ExpressInfoDTO;
import com.fs.store.dto.FsStoreOrderComputeDTO;
import com.fs.store.dto.LiveOrderComputeDTO;
import com.fs.store.enums.ShipperCodeEnum;
import com.fs.store.param.*;
import com.fs.store.service.IFsExpressService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.fs.live.service.impl.LiveServiceImpl.to16Hex;

/**
 * 订单Controller
 *
 * @author fs
 * @date 2025-07-08
 */
@Slf4j
@RestController
@RequestMapping("/app/live/liveOrder")
public class LiveOrderController extends AppBaseController
{
    @Autowired
    private ILiveOrderService liveOrderService;


    @Autowired
    private IFsExpressService expressService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private ILiveOrderPaymentService liveOrderPaymentService;


    @Login
    @ApiOperation("物流查询多运单号")
    @PostMapping("/getExpressMulti")
    public R getExpressMulti( @Validated @RequestBody FsStoreOrderExpressParam param){
        log.info("物流查询多运单号 请求参数: {}", JSON.toJSONString(param));

        LiveOrder order=liveOrderService.selectLiveOrderByOrderId(String.valueOf(param.getOrderId()));
        if (ObjectUtil.isNull(order)) {
            throw new CustomException("订单不存在");
        }
//        if (order.getStatus() < 2) {
//            throw new CustomException("未发货订单不能查询");
//        }
        return liveOrderService.getExpressMulti(order);
    }

    @Login
    @ApiOperation("物流查询")
    @PostMapping("/getExpress")
    public R getExpress( @Validated @RequestBody FsStoreOrderExpressParam param){
        log.info("物流查询 参数: {}", JSON.toJSONString(param));

        LiveOrder order=liveOrderService.selectLiveOrderByOrderId(String.valueOf(param.getOrderId()));
        if (ObjectUtil.isNull(order)) {
            throw new CustomException("订单不存在");
        }
        if (order.getStatus() <2) {
            throw new CustomException("未发货订单不能查询");
        }

        return liveOrderService.getExpress(order);
    }

    @Login
    @ApiOperation("修改支付类型")
    @PostMapping("/clearPayType")
    @Transactional
    public R clearPayType(HttpServletRequest request, @Validated @RequestBody FsStoreOrderPayParam param) {
        redisCache.deleteObject("isPaying:"+param.getOrderId());
        return R.ok();
    }


    /**
     * 查询订单列表
     */
    @Login
    @GetMapping("/list")
    public R list(LiveOrder liveOrder)
    {
        log.info("查询订单列表 参数: {}", JSON.toJSONString(liveOrder));

        PageHelper.startPage(Integer.parseInt(ServletUtils.getParameter("pageNum")) ,Integer.parseInt(ServletUtils.getParameter("pageSize")) );
        try {
            liveOrder.setUserId(getUserId());
            List<LiveOrderListVo> list = liveOrderService.selectLiveOrderListVo(liveOrder);
            PageInfo<LiveOrderListVo> result = new PageInfo<>(list);
            return R.ok().put("data", result);
        } catch (Exception e) {
            log.error("查询失败！",e);
            return R.error("操作异常");
        }

    }

    /**
     * 导出订单列表
     */
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LiveOrderQueryVO liveOrder)
    {
        log.info("订单导出 参数: {}", JSON.toJSONString(liveOrder));

        List<LiveOrder> list = liveOrderService.selectLiveOrderListExport(liveOrder);
        ExcelUtil<LiveOrder> util = new ExcelUtil<LiveOrder>(LiveOrder.class);
        return util.exportExcel(list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
    @Login
    @GetMapping(value = "/info/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") String orderId)
    {
        log.info("获取订单详细信息 参数: {}",orderId);

        return AjaxResult.success(liveOrderService.selectLiveOrderByOrderId(orderId));
    }

    @ApiOperation("确认订单")
    @PostMapping("/confirm")
    public R confirm(@Validated @RequestBody LiveOrderConfirmParam param, HttpServletRequest request){
        log.info("确认订单 参数: {}", JSON.toJSONString(param));

        param.setUserId(Long.parseLong(getUserId()));
        return liveOrderService.confirmOrder(param);
    }

    @PostMapping("/buy")
    @ApiOperation("购物车购买")
    @Login
    @RepeatSubmit
    public R buy(@RequestBody LiveOrder liveOrder)
    {
        log.info("购物车购买 参数: {}", JSON.toJSONString(liveOrder));

        liveOrder.setUserId(getUserId());
        return liveOrderService.buy(liveOrder);
    }

    /**
     * 新增订单
     */
    @Login
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    @RepeatSubmit
    public R add(@RequestBody LiveOrder liveOrder)
    {
        log.info("新增订单: {}", JSON.toJSONString(liveOrder));

        liveOrder.setUserId(getUserId());
        return liveOrderService.createLiveOrder(liveOrder);
    }

    @Login
    @ApiOperation("计算订单金额")
    @PostMapping("/computed")
    public R computed(@Validated @RequestBody LiveOrderComputedParam param){
        log.info("计算订单金额 {}",JSON.toJSONString(param));

        LiveOrderComputeDTO dto=liveOrderService.computedOrder(Long.parseLong(getUserId()),param);
        return R.ok().put("data",dto);
    }

    @Login
    @ApiOperation("计算中奖订单")
    @PostMapping("/computedReward")
    public R computedReward(@Validated @RequestBody LiveOrderComputedParam param){
        log.info("计算中奖订单 {}",JSON.toJSONString(param));

        LiveOrderComputeDTO dto=liveOrderService.computedReward(Long.parseLong(getUserId()),param);
        return R.ok().put("data",dto);
    }

    /**
     * 新增中奖订单
     */
    @Login
    @Log(title = "新增中奖订单", businessType = BusinessType.INSERT)
    @PostMapping("/createReward")
    @RepeatSubmit
    public R createReward(@RequestBody LiveOrder liveOrder)
    {
        log.info("新增中奖订单: {}", JSON.toJSONString(liveOrder));

        liveOrder.setUserId(getUserId());
        return liveOrderService.createRewardLiveOrder(liveOrder);
    }

    /**
     * 新增订单
     */
    @Login
    @Log(title = "提交中奖订单", businessType = BusinessType.INSERT)
    @PostMapping("/payConfirmReward")
    @RepeatSubmit
    public R payConfirmReward(@RequestBody LiveOrder liveOrder)
    {
        log.info("新增订单: {}", JSON.toJSONString(liveOrder));

        liveOrder.setUserId(getUserId());
        return liveOrderService.payConfirmReward(liveOrder);
    }

    /**
     * 修改订单
     */
    @Login
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    @RepeatSubmit
    public R edit(@RequestBody LiveOrder liveOrder)
    {
        return R.ok().put("orderId",liveOrder.getOrderId());
    }


    /**
     * 查看物流状态
     * */
    @GetMapping(value = "/getExpress/{id}")
    @Deprecated
    public R getExpress(@PathVariable("id") Long id)
    {
        log.info("查看物流状态 {}",id);

        LiveOrder order=liveOrderService.selectLiveOrderByOrderId(String.valueOf(id));
        ExpressInfoDTO expressInfoDTO=null;
        if(StringUtils.isNotEmpty(order.getDeliverySn())){

            String lastFourNumber = "";
            if (order.getDeliverySn().equals(ShipperCodeEnum.SF.getValue())) {
                lastFourNumber = order.getUserPhone();
                if (lastFourNumber.length() == 11) {
                    lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
                }
            }
            expressInfoDTO=expressService.getExpressInfo(order.getOrderCode(),order.getDeliverySn(),order.getDeliverySn(),lastFourNumber);
        }
        return R.ok().put("data",expressInfoDTO);
    }

    /**
     * 支付订单
     * */
    @PostMapping(value = "/pay")
    public void pay(LiveOrder liveOrder)
    {
        log.info("支付订单 参数: {}",liveOrder);

       liveOrderService.handlePay(liveOrder);
    }

    @Login
    @ApiOperation("支付宝支付")
    @PostMapping("/aliPayment")
    @RepeatSubmit
    public R aliPayment(@Validated @RequestBody FsUserLiveOrderPayUParam param)
    {
        param.setUserId(Long.parseLong(getUserId()));
        return R.ok();
    }

    @Login
    @ApiOperation("微信支付")
    @PostMapping("/weChatPayment")
    @RepeatSubmit
    public R payment(@Validated @RequestBody FsUserLiveOrderPayUParam param)
    {
        param.setUserId(Long.parseLong(getUserId()));
        return liveOrderService.wxPayment(param);
    }

    @Log(title = "退款", businessType = BusinessType.UPDATE)
    @PostMapping("/refundOrderMoney")
    public synchronized R refundOrderMoney(@Validated @RequestBody LiveOrderRefundParam param, HttpServletRequest request) {
        log.info("退款 {}",JSON.toJSONString(param));

        return liveOrderService.refundOrderMoney(param.getOrderId());
    }

    /**
     * 订单确认
     * */
    @Login
    @GetMapping(value = "/updateConfirm/{orderId}/{type}")
    @RepeatSubmit
    public R cancelConfirm(@PathVariable String orderId,@PathVariable String type)
    {
        log.info("订单确认 参数 orderId: {} type: {}", orderId, type);

        LiveOrder byId = liveOrderService.getById(orderId);
        List<Map<String, String>> allCodeDescMap = null;
        if (type.equals("0"))
            allCodeDescMap = LiveOrderCancleReason.getAllCodeDescMap();
        return R.ok().put("reason",allCodeDescMap).put("data",byId);
    }

    /**
     *正在购买的用户
     * */
    @GetMapping(value = "/liveOrderUser/{liveId}")
    public R liveOrderUser(@PathVariable  String liveId)
    {
        log.info("正在购买的用户 参数: {}",liveId);
        return liveOrderService.liveOrderUser(liveId);
    }


    @Login
    @ApiOperation("取消订单")
    @PostMapping("/cancelOrder")
    public R cancelOrder(@Validated @RequestBody LiveOrderCancelParam param, HttpServletRequest request){
        log.info("取消订单 参数: {}",JSON.toJSONString(param));

        LiveOrder order=liveOrderService.selectLiveOrderByOrderId(String.valueOf(param.getOrderId()));
        if (ObjectUtil.isNull(order)) {
            throw new CustomException("订单不存在");
        }
        List<LiveOrderPayment> liveOrderPayments = liveOrderPaymentService.selectLiveOrderPaymentByOrderId(order.getOrderId());
        if(CollectionUtils.isNotEmpty(liveOrderPayments)){
            LiveOrderPayment liveOrderPayment = liveOrderPayments.get(0);
            if(liveOrderPaymentService.queryHf(liveOrderPayment)){
                return R.error("当前订单状态不为待支付，请刷新页面!");
            }
        }
        return liveOrderService.cancelOrder(order);

    }

    @Login
    @ApiOperation("完成订单")
    @PostMapping("/finishOrder")
    public R finishOrder(@Validated @RequestBody LiveOrderCancelParam param, HttpServletRequest request){
        log.info("完成订单 参数: {}",JSON.toJSONString(param));

        return liveOrderService.finishOrder(param.getOrderId());
    }
    @ApiOperation("完成订单")
    @GetMapping("/test")
    public R tes(){
        List<Long> ids = liveOrderService.selectOrderIdByNoErp();
        for (Long id : ids) {
            try{
                liveOrderService.createOmsOrder(id);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }



}
