package com.ruoyi.frequency.ordermessage.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.controller.req.MessageReadOrDeleteReq;
import com.ruoyi.controller.req.OrderMessagePageReq;
import com.ruoyi.controller.resp.MessageOrderPageResp;
import com.ruoyi.enums.message.OrderMessageEnums;
import com.ruoyi.frequency.ordermessage.entity.OrderMessage;
import com.ruoyi.frequency.ordermessage.mapper.OrderMessageMapper;
import com.ruoyi.frequency.ordermessage.service.OrderMessageService;
import com.ruoyi.push.service.PushService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.vo.PageBasic;
import com.ruoyi.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单消息Service业务层处理
 *
 * @author zj
 * @date 2023-10-13
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderMessageServiceImpl extends ServiceImpl<OrderMessageMapper, OrderMessage> implements OrderMessageService {
    @Autowired
    private OrderMessageMapper orderMessageMapper;

    /**
     * 查询订单消息
     *
     * @param id 订单消息主键
     * @return 订单消息
     */
    @Override
    public OrderMessage selectOrderMessageById(Long id) {
        return orderMessageMapper.selectOrderMessageById(id);
    }

    /**
     * 查询订单消息列表
     *
     * @param orderMessage 订单消息
     * @return 订单消息
     */
    @Override
    public List<OrderMessage> selectOrderMessageList(OrderMessage orderMessage) {
        return orderMessageMapper.selectOrderMessageList(orderMessage);
    }

    /**
     * 新增订单消息
     *
     * @param orderMessage 订单消息
     * @return 结果
     */
    @Override
    public int insertOrderMessage(OrderMessage orderMessage) {
        orderMessage.setCreateTime(DateUtils.getNowDate());
        return orderMessageMapper.insertOrderMessage(orderMessage);
    }

    /**
     * 修改订单消息
     *
     * @param orderMessage 订单消息
     * @return 结果
     */
    @Override
    public int updateOrderMessage(OrderMessage orderMessage) {
        orderMessage.setUpdateTime(DateUtils.getNowDate());
        return orderMessageMapper.updateOrderMessage(orderMessage);
    }

    /**
     * 批量删除订单消息
     *
     * @param ids 需要删除的订单消息主键
     * @return 结果
     */
    @Override
    public int deleteOrderMessageByIds(Long[] ids) {
        this.lambdaUpdate().set(OrderMessage::getDelFlag, PublicCommon.删除).in(OrderMessage::getId, ids).update();
        return ids.length;
    }

    /**
     * 删除订单消息信息
     *
     * @param id 订单消息主键
     * @return 结果
     */
    @Override
    public int deleteOrderMessageById(Long id) {
        this.lambdaUpdate().set(OrderMessage::getDelFlag, PublicCommon.删除).eq(OrderMessage::getId, id).update();
        return 1;
    }

    @Override
    public List<OrderMessage> orderMessageList(OrderMessagePageReq req, UserVo userVo) {
        List<OrderMessage> orderMessageList = this.baseMapper.selectList(new QueryWrapper<OrderMessage>().lambda()
                .eq(OrderMessage::getUserType, userVo.getUserType()).eq(OrderMessage::getUserId, userVo.getUserId())
                .eq(OrderMessage::getIsShow, PublicCommon.Message.未清空)
                .eq(OrderMessage::getOrderId, req.getOrderId())
                .eq(OrderMessage::getOrderType, req.getOrderType())
                .eq(OrderMessage::getDelFlag, PublicCommon.启用).orderByDesc(OrderMessage::getCreateTime));
        return orderMessageList;
    }


    @Override
    public ResponseData orderMessageReadOrDelete(MessageReadOrDeleteReq req, UserVo userVo) {
        //1 标记已读 2 删除消息
        switch (req.getType()) {
            case 1:
                this.update().set("is_read", PublicCommon.Message.已读)
                        .eq("user_type", userVo.getUserType())
                        .eq("user_id", userVo.getUserId())
                        .eq("is_read", PublicCommon.Message.未读)
                        .eq(req.getOrderId() != null, "order_id", req.getOrderId())
                        .eq(req.getOrderType() != null, "order_type", req.getOrderType())
                        .in(CollectionUtil.isNotEmpty(req.getIds()), "id", req.getIds()).update();
                break;
            case 2:

                this.update().set("is_show", PublicCommon.Message.清空)
                        .set("is_read", PublicCommon.Message.已读)
                        .eq("user_type", userVo.getUserType())
                        .eq("user_id", userVo.getUserId())
                        .eq("is_show", PublicCommon.Message.未清空)
                        .eq(req.getOrderId() != null, "order_id", req.getOrderId())
                        .eq(req.getOrderType() != null, "order_type", req.getOrderType())
                        .in(CollectionUtil.isNotEmpty(req.getIds()), "id", req.getIds()).update();
                break;

            default:
                throw new IllegalStateException("Unexpected value: " + req.getType());
        }
        return ResponseData.success();
    }

    @Autowired
    private PushService pushService;

    /**
     * 添加订单消息
     *
     * @param userVo
     * @param orderId
     * @param orderType
     */
    @Override
    public void addOrderMessage(UserVo userVo, Long orderId, String orderNo, Integer orderType, OrderMessageEnums orderMessageEnums) {

        OrderMessage orderMessage = new OrderMessage()
                .setMessageType(orderMessageEnums.getCode())
                .setTitle(orderMessageEnums.getTitle())
                .setContent(orderMessageEnums.getContent().replace("orderNo", orderNo))
                .setUserId(userVo.getUserId())
                .setUserType(userVo.getUserType())
                .setOrderId(orderId)
                .setOrderType(orderType);
        this.baseMapper.insert(orderMessage);

        //推送
        pushService.push(userVo, orderId, orderNo, orderMessage.getId(), orderMessageEnums);

    }


    @Override
    public void addOrderMessage(UserVo userVo, Long orderId, String orderNo, Integer orderType, OrderMessageEnums orderMessageEnums, String... content) {
        OrderMessage orderMessage = new OrderMessage()
                .setMessageType(orderMessageEnums.getCode())
                .setTitle(orderMessageEnums.getTitle())
                .setContent(String.format(orderMessageEnums.getContent(), content))
                .setUserId(userVo.getUserId())
                .setUserType(userVo.getUserType())
                .setOrderId(orderId)
                .setOrderType(orderType);

        this.baseMapper.insert(orderMessage);

        //推送
        pushService.push(userVo, orderId, orderNo, orderMessage.getId(), orderMessageEnums);
    }

    @Override
    public Page<MessageOrderPageResp> messageOrderPage(PageBasic req, UserVo userVo) {
        Page<MessageOrderPageResp> messageOrderPage = baseMapper.messageOrderPage(new Page<>(req.getPageNo(), req.getPageSize()), userVo);
        if (CollectionUtil.isEmpty(messageOrderPage.getRecords())) {
            return messageOrderPage;
        }
        List<Long> orderIds = new ArrayList<>();
        orderIds.add(-1L);

        List<Long> mallOrderIds = new ArrayList<>();
        mallOrderIds.add(-1L);

        List<Long> allOrderIds = new ArrayList<>();
        allOrderIds.add(-1L);

        Map<String, MessageOrderPageResp> messageOrderPageRespMap = new HashMap<>();

        messageOrderPage.getRecords().stream().forEach(s -> {
            if (ObjectUtil.equal(PublicCommon.Order.订单, s.getOrderType())) {
                orderIds.add(s.getOrderId());
            } else {
                mallOrderIds.add(s.getOrderId());
            }

            allOrderIds.add(s.getOrderId());

            messageOrderPageRespMap.put(s.getOrderType() + "," + s.getOrderId(), s);
        });

        // 是否有未读消息
        List<OrderMessage> orderMessageList = this.baseMapper.selectList(new QueryWrapper<OrderMessage>().lambda()
                .eq(OrderMessage::getUserType, userVo.getUserType()).eq(OrderMessage::getUserId, userVo.getUserId())
                .eq(OrderMessage::getIsShow, PublicCommon.Message.未清空)
                .in(OrderMessage::getOrderId, allOrderIds)
                .eq(OrderMessage::getIsRead, PublicCommon.Message.未读)
                .eq(OrderMessage::getDelFlag, PublicCommon.启用));

        Map<String, Boolean> hasNotReadMap = new HashMap<>();
        orderMessageList.stream().forEach(x -> {
            hasNotReadMap.put(x.getOrderType() + "," + x.getOrderId(), true);
        });

        messageOrderPage.getRecords().stream().forEach(s -> {
            s.setIsRead(hasNotReadMap.containsKey(s.getOrderType() + "," + s.getOrderId()) ? 1 : 2);
        });

        //最新消息
        orderMessageList = this.baseMapper.selectList(new QueryWrapper<OrderMessage>().lambda()
                .eq(OrderMessage::getUserType, userVo.getUserType()).eq(OrderMessage::getUserId, userVo.getUserId())
                .eq(OrderMessage::getIsShow, PublicCommon.Message.未清空)
                .in(OrderMessage::getOrderId, allOrderIds)
                .eq(OrderMessage::getDelFlag, PublicCommon.启用).orderByDesc(BaseEntity::getCreateTime));

        orderMessageList.stream().forEach(x -> {
            if (StrUtil.isNotBlank(x.getContent())) {

                MessageOrderPageResp messageOrderPageResp = messageOrderPageRespMap.get(x.getOrderType() + "," + x.getOrderId());
                if (messageOrderPageResp != null && StrUtil.isBlank(messageOrderPageResp.getTitle()) && StrUtil.isNotBlank(x.getTitle())) {
                    messageOrderPageResp.setContent(x.getContent());
                    messageOrderPageResp.setTitle(x.getTitle());
                    messageOrderPageResp.setMessageType(x.getMessageType());
                    messageOrderPageResp.setCreateTime(x.getCreateTime());
                }
            }
        });

        messageOrderPage.getRecords().stream().forEach(s -> {
            s.setIsRead(hasNotReadMap.containsKey(s.getOrderType() + "," + s.getOrderId()) ? 1 : 2);
        });

        return messageOrderPage;
    }

    public static void main(String[] args) {
        System.out.println((7350+8200) * 8 - 1750*8);
    }
}
