package com.fzm.mall.server.front.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.SystemClock;
import com.fzm.mall.server.front.base.PageVO;
import com.fzm.mall.server.front.goods.model.Auction;
import com.fzm.mall.server.front.goods.mapper.AuctionMapper;
import com.fzm.mall.server.front.goods.model.GoodSpu;
import com.fzm.mall.server.front.goods.model.qo.UserAuctionQO;
import com.fzm.mall.server.front.goods.model.vo.PageVo;
import com.fzm.mall.server.front.goods.model.vo.UserAuctionVO;
import com.fzm.mall.server.front.goods.service.IAuctionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.front.goods.service.IGoodSpuService;
import com.fzm.mall.server.front.order.model.BiddingRecord;
import com.fzm.mall.server.front.order.model.Deposit;
import com.fzm.mall.server.front.order.service.IBiddingRecordService;
import com.fzm.mall.server.front.order.service.IDepositService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品拍卖 服务实现类
 * </p>
 *
 * @author fzm
 * @since 2021-09-02
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AuctionServiceImpl extends ServiceImpl<AuctionMapper, Auction> implements IAuctionService {
    private final IGoodSpuService goodSpuService;
    private final IBiddingRecordService biddingRecordService;
    private final IDepositService depositService;

    @Override
    public Auction getByGoodsId(String goodsId) {
        QueryWrapper<Auction> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(Auction::getGoodsId, goodsId)
                .ne(Auction::getStatus, 0);
        Auction auction = getOne(qw);
        return auction;
    }


    @Override
    public Auction getByAuctionId(String auctionId) {
        QueryWrapper<Auction> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(Auction::getAuctionId, auctionId)
                .ne(Auction::getStatus, 0);
        Auction auction = getOne(qw);
        return auction;
    }

    public PageVO<UserAuctionVO> goodsAuctionList(String status, PageVo pageVo) {
        Integer size = pageVo.getSize();
        Integer page = pageVo.getPage();
        int start = (page - 1) * size;
        List<UserAuctionVO> list = new ArrayList<>();
        QueryWrapper<Auction> q = new QueryWrapper<>();
        //1.进行中 2.已结束 3.未开始
        if (status.equals("3")) {
            q.gt("start_time", SystemClock.now());
        } else {
            q.eq("status", status);
        }
        q.orderByDesc("create_time");
        int count = count(q);
        q.last("limit " + start + "," + size);
        List<Auction> auctions = list(q);
        if (CollectionUtils.isEmpty(auctions)) {
            return null;
        }
        for (Auction a : auctions) {
            UserAuctionVO userAuction = new UserAuctionVO();
            BeanUtils.copyProperties(a, userAuction);
            list.add(userAuction);
        }

        PageVO<UserAuctionVO> pageVO = new PageVO<>();
        pageVO.init(page, size, count, list);
        return pageVO;
    }

    public PageVO<UserAuctionVO> getMyAuction(UserAuctionQO qo) {
        int count=0;
        String uid = qo.getUid();
        Integer page = qo.getPage();
        Integer size = qo.getSize();
        int begin = qo.getBegin();
        Integer type = qo.getType();
        List<UserAuctionVO> list = new ArrayList<>();
        List<BiddingRecord> bidlist = new ArrayList<>();
        PageVO<BiddingRecord> userAuctionVOPageList=new PageVO<>();
        QueryWrapper<BiddingRecord> q = new QueryWrapper<>();
        q.eq("uid", uid);
        q.orderByDesc("create_time");
        if (type == 0) {
            //待交保证金
            List<Deposit> depositlist = depositService.getDepositByUidAndStatus(uid, "0");
        } else if (type == 1) {
            //已拍下
            qo.setFinalUid(uid);
            userAuctionVOPageList = biddingRecordService.listUserAuctionOrder(qo);
        } else if (type == 2) {
            //已结束
            qo.setStatus("2");
            userAuctionVOPageList = biddingRecordService.listUserAuctionOrder(qo);
        } else if (type == 3) {
            //竞拍中
            qo.setStatus("1");
            //查询已经交了保证金的用户的拍卖单
            List<Deposit> depositlist = depositService.getDepositByUidAndStatus(uid, "1");
            List<String> auctionIds = depositlist.stream().distinct().map(Deposit::getAuctionId).collect(Collectors.toList());
            qo.setAuctionIds(auctionIds);
            userAuctionVOPageList = biddingRecordService.listUserAuctionOrder(qo);
        }
        bidlist = userAuctionVOPageList.getData();
        count = userAuctionVOPageList.getTotalSize();
        list = buildBidList(bidlist);
        PageVO<UserAuctionVO> pageVO = new PageVO<>();
        pageVO.init(page, size, count, list);
        return pageVO;
    }


    //数据处理

    public List<UserAuctionVO> buildBidList (List<BiddingRecord> bidlist){
        List<UserAuctionVO> list = new ArrayList<>();
        Map<String, List<BiddingRecord>> biddingRecords = bidlist.stream().distinct().collect(Collectors.groupingBy(BiddingRecord::getAuctionId));
        if (CollectionUtils.isEmpty(biddingRecords)) {
            return null;
        }
        for (Map.Entry<String, List<BiddingRecord>> a : biddingRecords.entrySet()) {
            List<BiddingRecord> bidList = a.getValue();
            String uid = bidList.get(0).getUid();
            //取当前最大值
            BiddingRecord biddingRecord = bidList.stream().max(Comparator.comparing(BiddingRecord -> BiddingRecord.getCurrentPrice())).get();
            BigDecimal currentPrice = BigDecimal.ZERO;
            if (biddingRecord != null) {
                currentPrice = biddingRecord.getCurrentPrice();
            }
            String auctionId = a.getKey();
            Auction auction = getByAuctionId(auctionId);
            if (auction != null) {
                UserAuctionVO userAuctionVO = new UserAuctionVO();
                BeanUtils.copyProperties(auction, userAuctionVO);
                Integer auctionStatus = auction.getStatus();
                if (auctionStatus == 2) {
                    //拍卖结束判断用户是否拍到
                    String finalUid = auction.getFinalUid();
                    if (finalUid.equals(uid)) {
                        userAuctionVO.setStatus(5);//已完成
                    }
                }
                String goodsId = auction.getGoodsId();
                GoodSpu spu = goodSpuService.goodSpu(goodsId);
                userAuctionVO.setThumb(spu.getThumb());
                userAuctionVO.setGoodsName(spu.getName());
                userAuctionVO.setGoodsId(goodsId);
                userAuctionVO.setCurrentPrice(currentPrice);
                list.add(userAuctionVO);
            }
        }
        return list;
    }
}
