package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.LifeCoupon;
import shop.alien.entity.store.LifeUser;
import shop.alien.entity.store.LifeUserOrder;
import shop.alien.mapper.LifeCouponMapper;
import shop.alien.mapper.LifeUserOrderMapper;
import shop.alien.mapper.StoreInfoMapper;
import shop.alien.store.service.LifeStoreOrderService;
import shop.alien.store.service.LifeUserService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ssk
 * @version 1.0
 * @date 2024/12/25 10:08
 */
@Service
@RequiredArgsConstructor
public class LifeStoreOrderServiceImpl extends ServiceImpl<LifeUserOrderMapper, LifeUserOrder> implements LifeStoreOrderService {

    private final LifeUserOrderMapper lifeUserOrderMapper;

    private final LifeCouponMapper lifeCouponMapper;

    private final LifeUserService lifeUserService;

    private final StoreInfoMapper storeInfoMapper;

    /**
     * @param page
     * @param size
     * @param storeId
     * @param status  订单状态,0.待使用, 1.已核销, 2.已过期, 3.待退款,4.已退款
     * @return
     */
    @Override
    public Map<String, Object> getOrderListByStatus(int page, int size, String storeId, String status) {
        Map<String, Object> returnMap = new HashMap<>();
        IPage<LifeUserOrder> orderPage = new Page<>(page, size);
        List<Map<String, Object>> returnList = new ArrayList<>();
        LambdaUpdateWrapper<LifeUserOrder> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(storeId != null && !storeId.isEmpty(), LifeUserOrder::getStoreId, storeId);
        wrapper.eq(status != null && !status.isEmpty(), LifeUserOrder::getStatus, status);
        wrapper.orderByDesc(LifeUserOrder::getUpdatedTime);
        IPage<LifeUserOrder> lifeUserOrders = lifeUserOrderMapper.selectPage(orderPage, wrapper);
        if (lifeUserOrders.getRecords().isEmpty()) {
            return returnMap;
        }
        List<Map<String, Object>> orderList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        for (LifeUserOrder order : lifeUserOrders.getRecords()) {
            Map<String, Object> map = new HashMap<>();
            LifeCoupon quan = lifeCouponMapper.selectById(order.getQuanId());
            calendar.setTime(order.getBuyTime());
            calendar.add(Calendar.DAY_OF_MONTH, quan.getExpirationDate());
            Date expirationDate = calendar.getTime();
            Date youxiaoqiTime = expirationDate.compareTo(quan.getEndDate()) > 0 ? quan.getEndDate()
                    : expirationDate;
            map.put("id", order.getId());
            map.put("orderNo", order.getOrderNo());
            map.put("quanId", order.getQuanId());
            map.put("quanName", quan.getName());
            map.put("youxiaoqi", youxiaoqiTime);
            map.put("status", order.getStatus());
            LambdaUpdateWrapper<LifeUser> lifeUserWrapper = new LambdaUpdateWrapper<>();
            lifeUserWrapper.eq(LifeUser::getId, order.getUserId()).in(LifeUser::getDeleteFlag, Arrays.asList(0, 1));
            LifeUser lifeUser = lifeUserService.getOne(lifeUserWrapper);
            map.put("phoneNum", lifeUser.getUserPhone());
            map.put("price", order.getFinalPrice());
            map.put("userId", lifeUser.getId());
            orderList.add(map);
        }
        Map<String, List<Map<String, Object>>> groupedByPhoneNum =
                orderList.stream()
                        .collect(Collectors.groupingBy(order -> (String) order.get("phoneNum")));
        groupedByPhoneNum.forEach((phoneNum, orders) -> {
            double totalPrice = orders.stream()
                    .mapToDouble(order -> Double.parseDouble((String) order.get("price")))
                    .sum();
            double expectedIncome = totalPrice * 0.97;
            Map<String, Object> details = new HashMap<>();
            details.put("phoneNum", phoneNum);
            details.put("totalPrice", totalPrice);

            BigDecimal bigDecimal = new BigDecimal(expectedIncome);
            details.put("expectedIncome", bigDecimal.setScale(2, RoundingMode.HALF_UP));
            List<Map<String, Object>> ordersList = new ArrayList<>();
            for (Map<String, Object> order : orders) {
                Map<String, Object> orderDetails = new HashMap<>();
                orderDetails.put("id", order.get("id"));
                orderDetails.put("quanName", order.get("quanName"));
                orderDetails.put("youxiaoqi", order.get("youxiaoqi"));
                orderDetails.put("status", order.get("status"));
                LifeCoupon quan = lifeCouponMapper.selectById((String) order.get("quanId"));
                orderDetails.put("image", quan.getImagePath());
                orderDetails.put("cnt", 1);
                orderDetails.put("userId", order.get("userId"));
                ordersList.add(orderDetails);
            }
            details.put("quanList", ordersList);
            returnList.add(details);
        });
        returnMap.put("records", returnList);
        returnMap.put("total", lifeUserOrderMapper.selectCount(wrapper));
        returnMap.put("current", orderPage.getCurrent());
        returnMap.put("size", orderPage.getSize());
        returnMap.put("pages", orderPage.getPages());
        return returnMap;
    }

    @Override
    public List<Map<String, Object>> getOrderById(String userId, int status, String storeId) {
        List<Map<String, Object>> returnList = new ArrayList<>();
        if (status == 1) {
            LambdaUpdateWrapper<LifeUserOrder> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(LifeUserOrder::getUserId, userId)
                    .eq(LifeUserOrder::getStatus, 1)
                    .eq(LifeUserOrder::getStoreId, storeId);
            List<LifeUserOrder> orders = lifeUserOrderMapper.selectList(wrapper);
            if (orders.isEmpty()) {
                return returnList;
            }
            for (LifeUserOrder order : orders) {
                Map<String, Object> map = new HashMap<>();
                map.put("usedTime", order.getUsedTime());
                map.put("usedStore", storeInfoMapper.selectById(order.getStoreId()).getStoreName());
                map.put("usedCnt", 1);
                map.put("quanCode", order.getQuanCode());
                map.put("orderNo", order.getOrderNo());
                returnList.add(map);
            }
        } else if (status == 4) {
            LambdaUpdateWrapper<LifeUserOrder> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(LifeUserOrder::getUserId, userId)
                    .in(LifeUserOrder::getStatus, Arrays.asList("2", "4"))
                    .eq(LifeUserOrder::getStoreId, storeId);
            List<LifeUserOrder> orders = lifeUserOrderMapper.selectList(wrapper);
            if (orders.isEmpty()) {
                return returnList;
            }
            for (LifeUserOrder order : orders) {
                Map<String, Object> map = new HashMap<>();
                map.put("refundTime", order.getRefundTime());
                map.put("refundCnt", 1);
                map.put("refundPrice", order.getFinalPrice());
                map.put("quanCode", order.getQuanCode());
                map.put("orderNo", order.getOrderNo());
                returnList.add(map);
            }
        }
        return returnList;
    }
}
