package shop.alien.store.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.LifeBrandedCard;
import shop.alien.entity.store.LifeCoupon;
import shop.alien.entity.store.LifeUserOrder;
import shop.alien.entity.store.vo.StoreInfoVo;
import shop.alien.mapper.LifeBrandedCardMapper;
import shop.alien.mapper.LifeCouponMapper;
import shop.alien.mapper.LifeUserOrderMapper;
import shop.alien.mapper.StoreInfoMapper;
import shop.alien.util.common.UniqueRandomNumGenerator;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@RequiredArgsConstructor
public class LifeUserBrandedCardService {

    private final LifeCouponMapper lifeCouponMapper;

    private final LifeBrandedCardMapper lifeBrandedCardMapper;

    private final LifeUserOrderMapper lifeUserOrderMapper;

    private final StoreInfoMapper storeInfoMapper;

    public IPage<Map<String, Object>> getBrandedCardList(int page, int size) {
        IPage<Map<String, Object>> iPage = new Page();
        List<Map<String, Object>> brandedCardList = new ArrayList<>();
        IPage<LifeBrandedCard> cardPage = new Page<>(page, size);
        LambdaQueryWrapper<LifeBrandedCard> cardWrapper = new LambdaQueryWrapper<>();
        cardWrapper.eq(LifeBrandedCard::getStatus, 0);
        cardWrapper.orderByDesc(LifeBrandedCard::getCreatedTime);
        IPage<LifeBrandedCard> cardList = lifeBrandedCardMapper.selectPage(cardPage, cardWrapper);
        if (cardList.getRecords().isEmpty()) {
            return iPage;
        }
        for (LifeBrandedCard card : cardList.getRecords()) {
            Map<String, Object> map = new HashedMap<>();
            map.put("cardId", card.getId());
            String quanIds = card.getQuanIds();
            String[] itemsArray = quanIds.split(",");
            List<String> quanIdList = Arrays.asList(itemsArray);
            LambdaUpdateWrapper<LifeCoupon> wrapper = new LambdaUpdateWrapper<>();
            wrapper.in(LifeCoupon::getId, quanIdList);
            List<LifeCoupon> quanList = lifeCouponMapper.selectList(wrapper);
            double totalPrice = quanList.stream()
                    .mapToDouble(quan -> Double.parseDouble(quan.getPrice()))
                    .sum();
            map.put("cardPrice", card.getCurrentPrice());
            double totalOffPrice = quanList.stream()
                    .mapToDouble(quan -> Double.parseDouble(quan.getOffprice()))
                    .sum();
            map.put("cardOffPrice", totalPrice);
            map.put("totalQty", card.getTotalQty());
            map.put("soldQty", card.getTotalQty() - card.getRemainQty());
            map.put("images", card.getImages());
            brandedCardList.add(map);
        }
        iPage.setRecords(brandedCardList);
        iPage.setTotal(cardPage.getTotal());
        iPage.setCurrent(cardPage.getCurrent());
        iPage.setSize(cardPage.getSize());
        iPage.setPages(cardPage.getPages());
        return iPage;
    }

    public Map<String, Object> getBrandedCardDetail(String cardId) {
        Map<String, Object> returnMap = new HashedMap<>();
        LifeBrandedCard card = lifeBrandedCardMapper.selectById(cardId);
        returnMap.put("cardName", card.getName());
        returnMap.put("soldQty", card.getTotalQty() - card.getRemainQty());
        returnMap.put("onTime", card.getOnTime());
        returnMap.put("images", card.getImages());
        String quanIds = card.getQuanIds();
        String[] itemsArray = quanIds.split(";");
        List<String> quanIdList = Arrays.asList(itemsArray);
        LambdaUpdateWrapper<LifeCoupon> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(LifeCoupon::getId, quanIdList);
        List<LifeCoupon> quanList = lifeCouponMapper.selectList(wrapper);
        double totalPrice = quanList.stream()
                .mapToDouble(quan -> Double.parseDouble(quan.getPrice()))
                .sum();
        returnMap.put("cardPrice", totalPrice);
        double totalOffPrice = quanList.stream()
                .mapToDouble(quan -> Double.parseDouble(quan.getOffprice()))
                .sum();
        returnMap.put("cardOffPrice", totalOffPrice);
        List<Map<String, Object>> quanMapList = new ArrayList<>();
        for (LifeCoupon quan : quanList) {
            Map<String, Object> quanMap = new HashedMap<>();
            quanMap.put("quanId", quan.getId());
            quanMap.put("quanName", quan.getName());
            quanMap.put("type", quan.getType());
            quanMap.put("quanImage", quan.getImagePath());

            QueryWrapper<StoreInfoVo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("a.id", quan.getStoreId());
            StoreInfoVo storeInfoVoOne = storeInfoMapper.getStoreInfoVoOne(queryWrapper);
            quanMap.put("storeName", null != storeInfoVoOne ? storeInfoVoOne.getStoreName() : "");
            quanMapList.add(quanMap);
        }
        returnMap.put("quanList", quanMapList);
        return returnMap;
    }

    public Map<String, Object> buyBrandedCard(String cardId, String userId) {
        Map<String, Object> returnMap = new HashedMap<>();
        Date now = new Date();
        LifeBrandedCard card = lifeBrandedCardMapper.selectById(cardId);
        String quanIds = card.getQuanIds();
        String[] itemsArray = quanIds.split(";");
        List<String> quanIdList = Arrays.asList(itemsArray);
        LambdaUpdateWrapper<LifeCoupon> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(LifeCoupon::getId, quanIdList);
        List<LifeCoupon> quanList = lifeCouponMapper.selectList(wrapper);
        for (LifeCoupon quan : quanList) {
            LifeUserOrder userOrder = new LifeUserOrder();
            userOrder.setUserId(userId);
            userOrder.setStoreId(quan.getStoreId());
            userOrder.setQuanId(quan.getId());
            String code = UniqueRandomNumGenerator.generateUniqueCode(12);
            userOrder.setQuanCode(code);
            String orderNo = UniqueRandomNumGenerator.generateUniqueCode(19);
            userOrder.setOrderNo(orderNo);
            userOrder.setStatus(0);
            userOrder.setPrice(quan.getPrice());
            userOrder.setFinalPrice(quan.getPrice());
            userOrder.setBuyTime(now);
            userOrder.setPayTime(now);
            userOrder.setPayMethod("微信支付");
            userOrder.setCreatedTime(now);
            userOrder.setUpdatedTime(now);
            lifeUserOrderMapper.insert(userOrder);
            quan.setStockQty(quan.getStockQty() - 1);
            lifeCouponMapper.updateById(quan);
        }
        card.setRemainQty(card.getRemainQty() - 1);
        lifeBrandedCardMapper.updateById(card);
        returnMap.put("success", "购买成功");
        return returnMap;
    }

    public Map<String, Object> buyBrandedCardCheck(String cardId, String userId) throws ParseException {
        Map<String, Object> returnMap = new HashedMap<>();
        LifeBrandedCard card = lifeBrandedCardMapper.selectById(cardId);
        if (card.getStatus() != 0) {
            returnMap.put("success", "不可支付");
            returnMap.put("reason", "联名卡已下架");
            return returnMap;
        }
        if (card.getRemainQty() == 0) {
            returnMap.put("success", "不可支付");
            returnMap.put("reason", "联名卡已售完");
            return returnMap;
        }
        String quanIds = card.getQuanIds();
        String[] itemsArray = quanIds.split(";");
        List<String> quanIdList = Arrays.asList(itemsArray);
        LambdaUpdateWrapper<LifeCoupon> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(LifeCoupon::getId, quanIdList);
        List<LifeCoupon> quanList = lifeCouponMapper.selectList(wrapper);
        if (quanList.isEmpty()) {
            returnMap.put("success", "不可支付");
            returnMap.put("reason", "联名卡中没有套餐");
            return returnMap;
        }
        boolean hasNonOneStatus = quanList.stream().anyMatch(quan -> quan.getStatus() != 1);
        if (hasNonOneStatus) {
            returnMap.put("success", "不可支付");
            returnMap.put("reason", "联名卡中有套餐状态不正确");
            return returnMap;
        }
        boolean has0stockRty = quanList.stream().anyMatch(quan -> quan.getStockQty() <= 0);
        if (has0stockRty) {
            returnMap.put("success", "不可支付");
            returnMap.put("reason", "联名卡中有套餐没有库存");
            return returnMap;
        }
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = sdf.format(now);
        Date dateOnly = sdf.parse(dateString);
        boolean hasOverEndDate = quanList.stream().anyMatch(quan -> dateOnly.compareTo(quan.getEndDate()) > 0);
        if (hasOverEndDate) {
            returnMap.put("success", "不可支付");
            returnMap.put("reason", "联名卡中有套餐过期");
            return returnMap;
        }
        returnMap.put("success", "可以支付");
        return returnMap;
    }

}