package com.slodon.b2b2c.controller.business.admin;

import com.slodon.b2b2c.aop.OperationLogger;
import com.slodon.b2b2c.business.example.*;
import com.slodon.b2b2c.business.pojo.*;
import com.slodon.b2b2c.core.constant.*;
import com.slodon.b2b2c.core.controller.BaseController;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.PageVO;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.*;
import com.slodon.b2b2c.member.pojo.Member;
import com.slodon.b2b2c.model.business.*;
import com.slodon.b2b2c.model.member.MemberModel;
import com.slodon.b2b2c.model.promotion.LadderGroupOrderExtendModel;
import com.slodon.b2b2c.model.promotion.PresellOrderExtendModel;
import com.slodon.b2b2c.model.promotion.SpellTeamMemberModel;
import com.slodon.b2b2c.model.promotion.SpellTeamModel;
import com.slodon.b2b2c.promotion.example.LadderGroupOrderExtendExample;
import com.slodon.b2b2c.promotion.example.PresellOrderExtendExample;
import com.slodon.b2b2c.promotion.example.SpellTeamMemberExample;
import com.slodon.b2b2c.promotion.pojo.LadderGroupOrderExtend;
import com.slodon.b2b2c.promotion.pojo.PresellOrderExtend;
import com.slodon.b2b2c.promotion.pojo.SpellTeam;
import com.slodon.b2b2c.promotion.pojo.SpellTeamMember;
import com.slodon.b2b2c.util.OrderExportUtil;
import com.slodon.b2b2c.vo.business.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author Slodon
 */
@Api(tags = "admin-订单管理")
@RestController
@RequestMapping("v3/business/admin/orderInfo")
@Slf4j
public class AdminOrderInfoController extends BaseController {

    @Resource
    private OrderModel orderModel;
    @Resource
    private OrderExtendModel orderExtendModel;
    @Resource
    private OrderPayModel orderPayModel;
    @Resource
    private OrderProductModel orderProductModel;
    @Resource
    private OrderLogModel orderLogModel;
    @Resource
    private OrderReserveModel orderReserveModel;
    @Resource
    private OrderAfterServiceModel orderAfterServiceModel;
    @Resource
    private PresellOrderExtendModel presellOrderExtendModel;
    @Resource
    private LadderGroupOrderExtendModel ladderGroupOrderExtendModel;
    @Resource
    private SpellTeamModel spellTeamModel;
    @Resource
    private SpellTeamMemberModel spellTeamMemberModel;
    @Resource
    private MemberModel memberModel;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("订单列表相关接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderSn", value = "订单号", paramType = "query"),
            @ApiImplicitParam(name = "memberName", value = "会员名称", paramType = "query"),
            @ApiImplicitParam(name = "goodsName", value = "商品名称", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "下单开始时间", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "下单结束时间", paramType = "query"),
            @ApiImplicitParam(name = "isVirtualGoods", value = "是否是虚拟商品：1-实物商品；2-虚拟商品", paramType = "query"),
            @ApiImplicitParam(name = "orderState", value = "订单状态：0-已取消；10-未付款订单；20-已付款；30-已发货；40-已完成;50-已关闭", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("list")
    public JsonResult<PageVO<OrderListVO>> getList(HttpServletRequest request, String orderSn, String memberName,
                                                   String goodsName, Date startTime, Date endTime, Integer orderState, Integer isVirtualGoods) {
        PagerInfo pager = WebUtil.handlerPagerInfo(request);

        OrderExample orderExample = new OrderExample();
        orderExample.setOrderSnLikes(orderSn);
        orderExample.setMemberNameLike(memberName);
        orderExample.setGoodsNameLike(goodsName);
        orderExample.setCreateTimeAfter(startTime);
        orderExample.setCreateTimeBefore(endTime);
        orderExample.setOrderState(orderState);
        orderExample.setIsVirtualGoods(isVirtualGoods);

        List<Order> orderList = orderModel.getOrderList(orderExample, pager);
        List<OrderListVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(orderList)) {
            orderList.forEach(order -> {
                //是否有定金
                boolean isHasDeposit = false;
                OrderListVO vo = new OrderListVO(order);
                //获取订单货品列表信息
                OrderProductExample orderProductExample = new OrderProductExample();
                orderProductExample.setOrderSn(order.getOrderSn());
                orderProductExample.setOrderBy("order_product_id ASC");
                List<OrderProduct> orderProductList = orderProductModel.getOrderProductList(orderProductExample, null);
                List<OrderProductListVO> productListVos = new ArrayList<>();
                if (!CollectionUtils.isEmpty(orderProductList)) {
                    for (OrderProduct orderProduct : orderProductList) {
                        OrderProductListVO orderProductListVO = new OrderProductListVO(orderProduct);
                        productListVos.add(orderProductListVO);
                    }
                }
                vo.setOrderProductListVOList(productListVos);

                //拼团订单
                if (order.getOrderType() == PromotionConst.PROMOTION_TYPE_102) {
                    SpellTeamMemberExample teamMemberExample = new SpellTeamMemberExample();
                    teamMemberExample.setOrderSn(order.getOrderSn());
                    List<SpellTeamMember> teamMemberList = spellTeamMemberModel.getSpellTeamMemberList(teamMemberExample, null);
                    AssertUtil.notEmpty(teamMemberList, "获取拼团成员信息为空");
                    //查询拼团团队状态
                    SpellTeam spellTeam = spellTeamModel.getSpellTeamBySpellTeamId(teamMemberList.get(0).getSpellTeamId());
                    AssertUtil.notNull(spellTeam, "获取拼团团队信息为空，请重试");
                    //拼团没有成功就不显示待发货
                    if (spellTeam.getState() == SpellConst.SPELL_GROUP_STATE_1 && order.getOrderState() == OrderConst.ORDER_STATE_20) {
                        vo.setOrderStateValue("已付款,待成团");
                    }
                }
                //预售订单
                if (order.getOrderType() == PromotionConst.PROMOTION_TYPE_103) {
                    PresellOrderExtendExample presellOrderExtendExample = new PresellOrderExtendExample();
                    presellOrderExtendExample.setOrderSn(order.getOrderSn());
                    List<PresellOrderExtend> presellOrderExtendList = presellOrderExtendModel.getPresellOrderExtendList(presellOrderExtendExample, null);
                    AssertUtil.notEmpty(presellOrderExtendList, "获取预售订单扩展信息为空");
                    PresellOrderExtend presellOrderExtend = presellOrderExtendList.get(0);
                    if (presellOrderExtend.getIsAllPay() == OrderConst.IS_ALL_PAY_1) {
                        vo.setOrderStateValue(MemberOrderListVO.getRealOrderStateValue(order.getOrderState(),
                                0, 0L, order.getOrderType()));
                    } else {
                        long time1 = presellOrderExtend.getRemainStartTime().getTime();
                        long time2 = System.currentTimeMillis();
                        long depositRemainTime = (time1 - time2) / 1000;
                        depositRemainTime = depositRemainTime < 0 ? 0 : depositRemainTime;

                        vo.setOrderStateValue(MemberOrderListVO.getRealOrderStateValue(order.getOrderState(),
                                presellOrderExtend.getOrderSubState(), depositRemainTime, order.getOrderType()));

                        isHasDeposit = true;
                    }
                }
                //阶梯团订单
                if (order.getOrderType() == PromotionConst.PROMOTION_TYPE_105) {
                    LadderGroupOrderExtendExample groupOrderExtendExample = new LadderGroupOrderExtendExample();
                    groupOrderExtendExample.setOrderSn(order.getOrderSn());
                    List<LadderGroupOrderExtend> groupOrderExtendList = ladderGroupOrderExtendModel.getLadderGroupOrderExtendList(groupOrderExtendExample, null);
                    AssertUtil.notEmpty(groupOrderExtendList, "获取阶梯团订单扩展信息为空");
                    LadderGroupOrderExtend groupOrderExtend = groupOrderExtendList.get(0);
                    if (order.getOrderState() == OrderConst.ORDER_STATE_10) {
                        long time1 = groupOrderExtend.getRemainStartTime().getTime();
                        long time2 = System.currentTimeMillis();
                        long depositRemainTime = (time1 - time2) / 1000;
                        depositRemainTime = depositRemainTime < 0 ? 0 : depositRemainTime;

                        vo.setOrderStateValue(MemberOrderListVO.getRealOrderStateValue(order.getOrderState(),
                                groupOrderExtend.getOrderSubState(), depositRemainTime, order.getOrderType()));
                    }
                }
                vo.setOrderTypeValue(MemberOrderListVO.dealOrderTypeValue(order.getOrderType(), isHasDeposit));

                vos.add(vo);
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("获取订单详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderSn", value = "订单号", required = true)
    })
    @GetMapping("detail")
    public JsonResult<OrderVO> getOrderDetail(HttpServletRequest request, @RequestParam("orderSn") String orderSn) {
        //获取订单信息
        Order order = orderModel.getOrdersWithOpByOrderSn(orderSn);
        AssertUtil.notNull(order, "无此订单");

        //获取订单扩展表信息
        OrderExtendExample orderExtendExample = new OrderExtendExample();
        orderExtendExample.setOrderSn(orderSn);
        OrderExtend orderExtend = orderExtendModel.getOrderExtendList(orderExtendExample, null).get(0);

        //支付信息
        OrderPay orderPay = orderPayModel.getOrderPayByPaySn(order.getPaySn());

        OrderVO orderVO = new OrderVO(order, orderExtend, orderPay);

        //获取会员信息
        Member member = memberModel.getMemberByMemberId(order.getMemberId());
        orderVO.setMemberEmail(member.getMemberEmail());

        //获取货品信息

        //图片处理
        List<OrderProduct> orderProductList = order.getOrderProductList();
        for (OrderProduct orderProduct : orderProductList) {
            orderProduct.setProductImage(FileUrlUtil.getFileUrl(orderProduct.getProductImage(), null));
        }

        //该货品是否有售后信息
        for (OrderProduct orderProduct : order.getOrderProductList()) {
            OrderAfterServiceExample orderAfterServiceExample = new OrderAfterServiceExample();
            orderAfterServiceExample.setOrderProductId(orderProduct.getOrderProductId());
            orderAfterServiceExample.setOrderBy("afs_id desc");
            List<OrderAfterService> orderAfterServiceList = orderAfterServiceModel.getOrderAfterServiceList(orderAfterServiceExample, null);
            if (CollectionUtils.isEmpty(orderAfterServiceList)) {
                orderProduct.setIsHasAfs(OrdersAfsConst.NOT_HAS_AFS);
            } else {
                orderProduct.setIsHasAfs(OrdersAfsConst.IS_HAS_AFS);
                orderProduct.setAfsSn(orderAfterServiceList.get(0).getAfsSn());
            }

        }

        orderVO.setOrderProductList(order.getOrderProductList());
        //获取订单日志信息
        OrderLogExample orderLogExample = new OrderLogExample();
        orderLogExample.setOrderSn(orderSn);
        orderLogExample.setOrderBy("log_time asc");
        List<OrderLog> orderLogList = orderLogModel.getOrderLogList(orderLogExample, null);
        //订单日志拆分为状态流转日志和操作日志
        orderLogList.forEach(orderLog -> {
            if (orderLog.getOrderStateLog().equals(OrderConst.ORDER_STATE_LOG)) {
                orderVO.getOrderOperateList().add(orderLog);
            } else {
                orderVO.getOrderLogs().add(orderLog);
            }
        });

        //虚拟商品查询预留信息
        if (order.getIsVirtualGoods() == GoodsConst.IS_VIRTUAL_GOODS_2) {
            OrderReserveExample example = new OrderReserveExample();
            example.setOrderSn(orderSn);
            example.setOrderBy("reserve_id asc");
            List<OrderReserve> orderReserveList = orderReserveModel.getOrderReserveList(example, null);
            orderVO.setOrderReserveList(orderReserveList);
        }

        //拼团订单
        if (order.getOrderType() == PromotionConst.PROMOTION_TYPE_102) {
            SpellTeamMemberExample teamMemberExample = new SpellTeamMemberExample();
            teamMemberExample.setOrderSn(order.getOrderSn());
            List<SpellTeamMember> teamMemberList = spellTeamMemberModel.getSpellTeamMemberList(teamMemberExample, null);
            AssertUtil.notEmpty(teamMemberList, "获取拼团成员信息为空");
            //查询拼团团队状态
            SpellTeam spellTeam = spellTeamModel.getSpellTeamBySpellTeamId(teamMemberList.get(0).getSpellTeamId());
            AssertUtil.notNull(spellTeam, "获取拼团团队信息为空，请重试");
            //拼团没有成功就不显示待发货
            if (spellTeam.getState() == SpellConst.SPELL_GROUP_STATE_1 && order.getOrderState() == OrderConst.ORDER_STATE_20) {
                orderVO.setOrderStateValue("已付款,待成团");
            }
        }
        //预售订单
        if (order.getOrderType() == PromotionConst.PROMOTION_TYPE_103) {
            PresellOrderExtendExample presellOrderExtendExample = new PresellOrderExtendExample();
            presellOrderExtendExample.setOrderSn(order.getOrderSn());
            List<PresellOrderExtend> presellOrderExtendList = presellOrderExtendModel.getPresellOrderExtendList(presellOrderExtendExample, null);
            AssertUtil.notEmpty(presellOrderExtendList, "获取预售订单扩展信息为空");
            PresellOrderExtend presellOrderExtend = presellOrderExtendList.get(0);
            if (presellOrderExtend.getIsAllPay() == OrderConst.IS_ALL_PAY_1) {
                orderVO.setOrderStateValue(MemberOrderListVO.getRealOrderStateValue(order.getOrderState(),
                        0, 0L, order.getOrderType()));
            } else {
                long time1 = presellOrderExtend.getRemainStartTime().getTime();
                long time2 = System.currentTimeMillis();
                long depositRemainTime = (time1 - time2) / 1000;
                depositRemainTime = depositRemainTime < 0 ? 0 : depositRemainTime;

                orderVO.setOrderStateValue(MemberOrderListVO.getRealOrderStateValue(order.getOrderState(),
                        presellOrderExtend.getOrderSubState(), depositRemainTime, order.getOrderType()));
                orderVO.setOrderTypeValue(MemberOrderListVO.dealOrderTypeValue(order.getOrderType(), true));
            }
        }
        //阶梯团订单
        if (order.getOrderType() == PromotionConst.PROMOTION_TYPE_105) {
            LadderGroupOrderExtendExample groupOrderExtendExample = new LadderGroupOrderExtendExample();
            groupOrderExtendExample.setOrderSn(order.getOrderSn());
            List<LadderGroupOrderExtend> groupOrderExtendList = ladderGroupOrderExtendModel.getLadderGroupOrderExtendList(groupOrderExtendExample, null);
            AssertUtil.notEmpty(groupOrderExtendList, "获取阶梯团订单扩展信息为空");
            LadderGroupOrderExtend groupOrderExtend = groupOrderExtendList.get(0);
            if (order.getOrderState() == OrderConst.ORDER_STATE_10) {
                long time1 = groupOrderExtend.getRemainStartTime().getTime();
                long time2 = System.currentTimeMillis();
                long depositRemainTime = (time1 - time2) / 1000;
                depositRemainTime = depositRemainTime < 0 ? 0 : depositRemainTime;

                orderVO.setOrderStateValue(MemberOrderListVO.getRealOrderStateValue(order.getOrderState(),
                        groupOrderExtend.getOrderSubState(), depositRemainTime, order.getOrderType()));
            }
        }
        return SldResponse.success(orderVO);
    }

    @ApiOperation("订单导出")
    @OperationLogger(option = "订单导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderSn", value = "订单号", paramType = "query"),
            @ApiImplicitParam(name = "memberName", value = "会员名称", paramType = "query"),
            @ApiImplicitParam(name = "goodsName", value = "商品名称", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "下单开始时间", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "下单结束时间", paramType = "query"),
            @ApiImplicitParam(name = "orderState", value = "订单状态：0-已取消；10-未付款订单；20-已付款；30-已发货；40-已完成;50-已关闭", paramType = "query")
    })
    @GetMapping("export")
    public JsonResult<Object> export(HttpServletRequest request, HttpServletResponse response, String orderSn, String memberName,
                                     String goodsName, Date startTime, Date endTime, Integer orderState) throws IOException, InterruptedException {
        long l = System.currentTimeMillis();
        OrderExample example = new OrderExample();
        example.setOrderSnLikes(orderSn);
        example.setMemberNameLike(memberName);
        example.setGoodsNameLike(goodsName);
        example.setCreateTimeAfter(startTime);
        example.setCreateTimeBefore(endTime);
        example.setOrderState(orderState);
        String orderCode = stringRedisTemplate.opsForValue().get("order_list_code");
        OrderExportUtil util = new OrderExportUtil(orderModel, example, orderCode, request);
        Map<String, SXSSFWorkbook> excelMap = util.doExport();
        if (excelMap.size() == 1) {
            //导出一个excel文件，无需压缩
            FileDownloadUtils.setExcelHeadInfo(response, request, "导出订单-" + ExcelUtil.getSystemDate() + ".xls");
            excelMap.entrySet().iterator().next().getValue().write(response.getOutputStream());
        } else {
            //压缩
            FileDownloadUtils.setZipDownLoadHeadInfo(response, request, "导出订单-" + ExcelUtil.getSystemDate() + ".zip");
            ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());

            for (Map.Entry<String, SXSSFWorkbook> entry : excelMap.entrySet()) {
                String fileName = entry.getKey();
                SXSSFWorkbook sxssfWorkbook = entry.getValue();
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                sxssfWorkbook.write(os);
                zipOutputStream.putNextEntry(new ZipEntry(fileName));
                zipOutputStream.write(os.toByteArray());
                zipOutputStream.closeEntry();
                os.flush();
                os.close();
            }
            zipOutputStream.flush();
            zipOutputStream.close();
        }

        log.debug("耗时：{}ms", (System.currentTimeMillis() - l));
        return null;
    }

    @ApiOperation("获取聊天用户订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId", value = "会员id", required = true, paramType = "query"),
            @ApiImplicitParam(name = "storeId", value = "会员要咨询的供应商id", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("userOrders")
    public JsonResult<PageVO<ChatOrdersVO>> userOrders(HttpServletRequest request, Integer memberId, Long storeId) {

        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        OrderExample example = new OrderExample();
        if (!StringUtil.isNullOrZero(storeId)) {
            example.setStoreId(storeId);
        }
        example.setMemberId(memberId);
        List<Order> list = orderModel.getOrderList(example, pager);
        ArrayList<ChatOrdersVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(order -> {
                //查询货品列表
                OrderProductExample productExample = new OrderProductExample();
                productExample.setOrderSn(order.getOrderSn());
                productExample.setOrderBy("order_product_id ASC");
                List<OrderProduct> productList = orderProductModel.getOrderProductList(productExample, null);
                vos.add(new ChatOrdersVO(order, productList));
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    /***
     * @description:订单信息
     * @param day 近x天数据
     * @return: com.slodon.b2b2c.core.response.JsonResult<java.lang.String>
     * @author sunshihao
     * @date: 2025/9/1 16:33
     */
    @GetMapping("/orderList")
    public JsonResult<String> orderList(@RequestParam(value = "day", required = false) int day) {
        String result;
        try {
            result = orderProductModel.orderList(day);
        }catch (Exception e) {
            log.error(e.getMessage(),e);
            return SldResponse.fail("订单信息查询失败: " + e.getMessage());
        }
        return SldResponse.success(result);
    }
}
