package shop.alien.store.service.impl;

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.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.LifeReverseGroupBuyingStoreVo;
import shop.alien.entity.store.vo.LifeReverseGroupBuyingUserVo;
import shop.alien.store.config.GaoDeMapUtil;
import shop.alien.mapper.LifeReverseGroupBuyingMapper;
import shop.alien.store.service.*;
import shop.alien.util.common.DateUtils;
import shop.alien.util.common.UniqueRandomNumGenerator;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户反向团购表 服务实现类
 *
 * @author ssk
 * @since 2025-03-05
 */
@Service
@RequiredArgsConstructor
public class LifeReverseGroupBuyingServiceImpl extends ServiceImpl<LifeReverseGroupBuyingMapper, LifeReverseGroupBuying> implements LifeReverseGroupBuyingService {

    private final LifeReverseGroupBuyingMapper lifeReverseGroupBuyingMapper;

    private final LifeReverseGroupBiddingService lifeReverseGroupBiddingService;

    private final LifeCouponService lifeCouponService;

    private final StoreDictService dictService;

    private final StoreInfoService storeInfoService;

    private final GaoDeMapUtil gaoDeMapUtil;

    /**
     * 用户-反向团购列表
     *
     * @param pageNum  页数
     * @param pageSize 页容
     * @param userId   用户id
     * @param status   状态, 0:待审核, 1:未通过, 2:已通过, 3:待接单, 4,已完成
     * @return IPage
     */
    @Override
    public IPage<LifeReverseGroupBuyingUserVo> getUserList(Integer pageNum, Integer pageSize, Integer userId, Integer status) {
        QueryWrapper<LifeReverseGroupBuyingUserVo> wrapper = new QueryWrapper<>();
        wrapper.eq(null != userId, "a.user_id", userId)
                .eq(null != status, "a.status", status)
                .orderByDesc("a.created_time");
        IPage<LifeReverseGroupBuyingUserVo> page = lifeReverseGroupBuyingMapper.getUserPage(new Page<>(pageNum, pageSize), wrapper);
        page.setRecords(resultList(page.getRecords()));
        updateGroupStatus(page.getRecords());
        return page;
    }

    /**
     * 反向团购详情
     *
     * @param id 反向团购主键id
     * @return LifeReverseGroupBuyingVo
     */
    @Override
    public LifeReverseGroupBuyingUserVo getDetail(Integer id) {
        LifeReverseGroupBuying lifeReverseGroupBuying = lifeReverseGroupBuyingMapper.selectById(id);
        LifeReverseGroupBuyingUserVo lifeReverseGroupBuyingUserVo = new LifeReverseGroupBuyingUserVo();
        BeanUtils.copyProperties(lifeReverseGroupBuying, lifeReverseGroupBuyingUserVo);
        List<LifeReverseGroupBuyingUserVo> list = new ArrayList<>();
        list.add(lifeReverseGroupBuyingUserVo);
        return resultList(list).get(0);
    }

    /**
     * 商家-反向团购列表
     *
     * @param pageNum  页数
     * @param pageSize 页容
     * @param distance 距离, 多少米以内
     * @param dateSort 时间排序, 0:倒序, 1:正序
     * @param price    价格, 多少钱以内
     * @param storeId  门店id
     * @return IPage
     */
    @Override
    public IPage<LifeReverseGroupBuyingStoreVo> getStoreList(Integer pageNum, Integer pageSize, Integer distance, Integer dateSort, String price, Integer storeId) {
        QueryWrapper<LifeReverseGroupBuyingStoreVo> lifeReverseGroupBuyingStoreVoQueryWrapper = new QueryWrapper<>();
        //时间排序
        if (dateSort != null && dateSort == 0) {
            lifeReverseGroupBuyingStoreVoQueryWrapper.orderByDesc("a.created_time");
        }
        if (dateSort != null && dateSort == 1) {
            lifeReverseGroupBuyingStoreVoQueryWrapper.orderByAsc("a.created_time");
        }
        lifeReverseGroupBuyingStoreVoQueryWrapper.groupBy("a.id");
        IPage<LifeReverseGroupBuyingStoreVo> storePage = lifeReverseGroupBuyingMapper.getStorePage(new Page<>(pageNum, pageSize), lifeReverseGroupBuyingStoreVoQueryWrapper);
        StoreInfo storeInfo = storeInfoService.getById(storeId);
        List<LifeReverseGroupBuyingStoreVo> records = storePage.getRecords();
        records.forEach(a -> a.setGroupMoneyStr(new BigDecimal(a.getGroupMoney()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString()));
        //距离
        if (null != distance) {
            records = records.stream().filter(a -> {
                String[] split = a.getPosition().split(",");
                //发布的经纬度, 门店的经纬度
                double storeDistance = gaoDeMapUtil.getDistance(split[0], split[1], storeInfo.getStorePosition().split(",")[0], storeInfo.getStorePosition().split(",")[1]);
                return distance >= storeDistance;
            }).collect(Collectors.toList());
        }
        //价格
        if (!StringUtils.isEmpty(price)) {
            records = records.stream()
                    .filter(a -> new BigDecimal(a.getGroupMoney()).compareTo(new BigDecimal(price).multiply(new BigDecimal(100))) <= 0)
                    .collect(Collectors.toList());
        }
        storePage.setRecords(records);
        return storePage;
    }

    /**
     * 用户-接受或拒绝商家
     *
     * @param id      反向团购主键id
     * @param userId  用户id
     * @param storeId 门店id
     * @param status  状态, 0:拒绝, 1:接收
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean receiveOrRefuse(Integer id, Integer userId, Integer storeId, Integer status) {
        try {
            LambdaUpdateWrapper<LifeReverseGroupBidding> lifeReverseGroupBidding = new LambdaUpdateWrapper<>();
            lifeReverseGroupBidding
                    .eq(LifeReverseGroupBidding::getReverseGroupId, id)
                    .eq(LifeReverseGroupBidding::getStoreId, storeId);
            if (status == 0) {
                //拒绝
                lifeReverseGroupBidding.set(LifeReverseGroupBidding::getBiddingType, 2);
            } else {
                //接收
                lifeReverseGroupBidding.set(LifeReverseGroupBidding::getBiddingType, 3);
                //修改用户反向团购状态
                this.update(new LambdaUpdateWrapper<LifeReverseGroupBuying>()
                        .eq(LifeReverseGroupBuying::getId, id)
                        //待使用
                        .set(LifeReverseGroupBuying::getStatus, 5));

            }
            //修改商家竞价状态
            lifeReverseGroupBiddingService.update(lifeReverseGroupBidding);
            //用户增加优惠券
            LifeReverseGroupBuying lifeReverseGroupBuying = this.getById(id);
            String code = UniqueRandomNumGenerator.generateUniqueCode(12);
            LifeCoupon lifeCoupon = new LifeCoupon();
            lifeCoupon.setCouponCode(code);
            lifeCoupon.setName(lifeReverseGroupBuying.getGroupTitle());
            lifeCoupon.setStoreId(storeId.toString());
            lifeCoupon.setPrice(new BigDecimal(lifeReverseGroupBuying.getGroupMoney()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
            lifeCoupon.setOffprice("0");
            //开始时间
            lifeCoupon.setStartDate(lifeReverseGroupBuying.getGroupStartTime());
            //结束时间(单时间为开始时间+1天)
            if (null == lifeReverseGroupBuying.getGroupEndTime()) {
                lifeCoupon.setEndDate(lifeReverseGroupBuying.getGroupStartTime());
            } else {
                lifeCoupon.setEndDate(lifeReverseGroupBuying.getGroupEndTime());
            }
            lifeCoupon.setSingleQty(1);
            lifeCoupon.setStatus(0);
            lifeCoupon.setType(2);
            lifeCouponService.save(lifeCoupon);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 商家-参与竞价
     *
     * @param lifeReverseGroupBidding 反向团购竞价表
     * @return boolean
     */
    @Override
    public boolean joinBidding(LifeReverseGroupBidding lifeReverseGroupBidding) {
        return lifeReverseGroupBiddingService.saveOrUpdate(lifeReverseGroupBidding);
    }

    /**
     * 列表拼接
     *
     * @param list 列表
     * @return List<LifeReverseGroupBuyingUserVo>
     */
    private List<LifeReverseGroupBuyingUserVo> resultList(List<LifeReverseGroupBuyingUserVo> list) {
        if (!list.isEmpty()) {
            //主类型
            LambdaQueryWrapper<StoreDictionary> homePageQuery = new LambdaQueryWrapper<>();
            homePageQuery.eq(StoreDictionary::getTypeName, "homePageType");
            List<StoreDictionary> homePageList = dictService.list(homePageQuery);

            //酒店标签
            LambdaQueryWrapper<StoreDictionary> hotelLabelQuery = new LambdaQueryWrapper<>();
            hotelLabelQuery.eq(StoreDictionary::getTypeName, "hotelLabel");
            List<StoreDictionary> hotelLabelList = dictService.list(hotelLabelQuery);

            //美食标签
            LambdaQueryWrapper<StoreDictionary> restaurantLabelQuery = new LambdaQueryWrapper<>();
            restaurantLabelQuery.eq(StoreDictionary::getTypeName, "restaurantLabel");
            List<StoreDictionary> restaurantLabelList = dictService.list(restaurantLabelQuery);

            for (LifeReverseGroupBuyingUserVo record : list) {
                record.setGroupMoneyStr(new BigDecimal(record.getGroupMoney()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
                record.setGroupTypeStr(homePageList.stream().filter(a -> a.getDictId().equals(record.getGroupType().toString())).collect(Collectors.toList()).get(0).getDictDetail());
                //团购类型
                StringBuilder groupTypeStr = new StringBuilder();
                String[] split = record.getDictId().split(",");
                switch (record.getGroupType()) {
                    //地方美食
                    case 1:
                        for (String s : split) {
                            for (StoreDictionary restaurantLabel : restaurantLabelList) {
                                if (s.equals(restaurantLabel.getDictId())) {
                                    groupTypeStr.append(restaurantLabel.getDictDetail()).append(",");
                                }
                            }
                        }
                        break;
                    //酒店/民宿
                    case 2:
                        for (String s : split) {
                            for (StoreDictionary hotelLabel : hotelLabelList) {
                                if (s.equals(hotelLabel.getDictId())) {
                                    groupTypeStr.append(hotelLabel.getDictDetail()).append(",");
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
                record.setDictDetail(groupTypeStr.substring(0, groupTypeStr.length() - 1));
                switch (record.getStatus()) {
                    case 0:
                        record.setStatusStr("待审核");
                        break;
                    case 1:
                        record.setStatusStr("未通过");
                        break;
                    case 2:
                        record.setStatusStr("已通过");
                        break;
                    case 3:
                        record.setStatusStr("待接单");
                        break;
                    case 4:
                        record.setStatusStr("未接单");
                        break;
                    case 5:
                        record.setStatusStr("待使用");
                        break;
                    case 6:
                        record.setStatusStr("已完成");
                        break;
                    default:
                        break;
                }
            }
        }
        return list;
    }

    /**
     * 老弟的订单没人接啊
     *
     * @param list 团购列表
     */
    private void updateGroupStatus(List<LifeReverseGroupBuyingUserVo> list) {
        for (LifeReverseGroupBuyingUserVo lifeReverseGroupBuyingVo : list) {
            if (DateUtils.dateCompare(new Date(), lifeReverseGroupBuyingVo.getBiddingEndTime()) && lifeReverseGroupBuyingVo.getStatus() == 3) {
                //状态, 0:待审核, 1:未通过, 2:已通过, 3:待接单, 4:未接单, 5:待使用, 6:已完成
                lifeReverseGroupBuyingVo.setStatus(4);
                this.updateById(lifeReverseGroupBuyingVo);
            }
        }
    }

}
