package com.fuint.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.fuint.common.dto.ext.PageResult;
import com.fuint.common.service.ShopAlertService;
import com.fuint.common.service.TableService;
import com.fuint.common.util.I18nUtil;
import com.fuint.common.vo.OrderVO;
import com.fuint.common.vo.ShopDetailVO;
import com.fuint.common.vo.ShopVO;
import com.fuint.framework.exception.BusinessCheckException;
import com.fuint.repository.mapper.MtOrderMapper;
import com.fuint.repository.mapper.MtStoreMapper;
import com.fuint.repository.mapper.MtTableMapper;
import com.fuint.repository.model.MtOrder;
import com.fuint.repository.model.MtStore;
import com.fuint.repository.model.MtTable;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Survive
 * @date 2025/3/12
 * @description TODO
 */
@Service
@AllArgsConstructor
public class ShopAlertServiceImpl extends ServiceImpl<MtStoreMapper, MtStore> implements ShopAlertService {


    private MtStoreMapper shopMapper;

    private MtOrderMapper orderMapper;

    @Override
    @Transactional
    public void addShopAlert(Long shopId, String mail, BigDecimal threshold) throws BusinessCheckException {
        // 1. 校验店铺存在性
        MtStore shop = shopMapper.selectById(shopId);
        if (shop == null) {
            throw new BusinessCheckException(I18nUtil.getMessage("storeNonexistent"));
        }
        // 2. 更新字段
        shop.setMail(mail);
        shop.setThreshold(threshold);

        // 3. 持久化到数据库
        int rows = shopMapper.updateById(shop);
    }

    @Override
    @Transactional
    public MtStore updateShopAlert(Long id, String mail, BigDecimal threshold) throws BusinessCheckException{
        // 1. 验证店铺存在性
        MtStore shop = shopMapper.selectById(id);
        if (shop == null) {
            throw new BusinessCheckException(I18nUtil.getMessage("storeNonexistent"));
        }

        // 2. 数据更新
        shop.setMail(mail);
        shop.setThreshold(threshold);
        shop.setUpdateTime(new Date()); // 更新时间戳

        int rows = shopMapper.updateById(shop);
        if (rows == 0){
            throw new BusinessCheckException(I18nUtil.getMessage("updateFail"));
        }
        return shop;
    }

    @Override
    @Transactional
    public MtStore clearAlertConfig(Long shopId) throws BusinessCheckException{
        // 1. 验证店铺存在性
        MtStore shop = shopMapper.selectById(shopId);
        if (shop == null) {
            throw new BusinessCheckException(I18nUtil.getMessage("storeNonexistent"));
        }

        // 2. 清除预警配置
        shop.setMail("");          // 清空邮箱
        shop.setThreshold(BigDecimal.ZERO);  // 重置阈值
        shop.setUpdateTime(new Date());
        int rows = shopMapper.updateById(shop);
        return shop;
    }


    /**
     * 店铺详情
     * @param shopId
     * @param withOrders 否携带当日订单
     * @return
     */
    @Override
    public ShopDetailVO getShopDetail(Long shopId, Boolean withOrders) throws BusinessCheckException{
        // 1. 查询基础信息
        MtStore shop = shopMapper.selectById(shopId);
        if (shop == null) {
            throw new BusinessCheckException(I18nUtil.getMessage("storeNonexistent"));
        }

        // 2. 构建VO对象
        ShopDetailVO vo = new ShopDetailVO()
                .setId(shop.getId())
                .setName(shop.getName())
                .setMail(shop.getMail())
                .setThreshold(shop.getThreshold())
                .setCreateTime(shop.getCreateTime())
                .setUpdateTime(shop.getUpdateTime());

        // 3. 查询当日订单（按需加载）
        if (Boolean.TRUE.equals(withOrders)) {
            List<MtOrder> orders = orderMapper.selectList(
                    new LambdaQueryWrapper<MtOrder>()
                            .eq(MtOrder::getStoreId, shopId)
                            .ge(MtOrder::getCreateTime, LocalDate.now().atStartOfDay())
            );
            vo.setOrdersToday(convertToOrderVO(orders));
        }
        return vo;
    }

    /**
     * 分页查询店铺列表
     * @param page
     * @param size
     * @param name
     * @return
     */
    @Override
    public PageResult<ShopVO> listShops(Integer page, Integer size, String name) {
        // 1. 构建分页参数
        Page<MtStore> pageParam = new Page<>(page, size);

        // 2. 构建查询条件
        LambdaQueryWrapper<MtStore> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(name), MtStore::getName, name)
                .select(MtStore::getId, MtStore::getName, MtStore::getMail,
                        MtStore::getContact, MtStore::getPhone,
                        MtStore::getThreshold, MtStore::getUpdateTime);

        // 3. 执行分页查询
        Page<MtStore> shopPage = (Page<MtStore>) shopMapper.selectPage(pageParam, wrapper);

        //计算每个店铺的总收益额
        // 4. 转换VO对象
        List<ShopVO> vos = shopPage.getRecords().stream()
                .map(shop -> new ShopVO(
                        shop.getId(),
                        shop.getName(),
                        shop.getMail(),
                        shop.getPhone(),
                        shop.getContact(),
                        shop.getThreshold(),
                        shop.getUpdateTime()
                ))
                .collect(Collectors.toList());

        // 5. 封装分页结果
        return new PageResult<>(
                shopPage.getCurrent(),
                shopPage.getSize(),
                shopPage.getTotal(),
                vos
        );
    }


    /**
     * 参数转换  MtOrder-》vo
     * @param orders
     * @return
     */
    private List<OrderVO> convertToOrderVO(List<MtOrder> orders) {
        return orders.stream()
                .map(o -> new OrderVO(o.getId(), o.getAmount(), o.getCreateTime()))
                .collect(Collectors.toList());
    }
}