package shop.alien.store.service.impl;

import com.alibaba.fastjson.JSONObject;
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.ObjectUtils;
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.apache.http.client.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.*;
import shop.alien.entity.store.dto.LifeGroupBuyDto;
import shop.alien.entity.store.vo.LifeGroupBuyNameThaliVo;
import shop.alien.entity.store.vo.LifeGroupBuyThaliVo;
import shop.alien.entity.store.vo.StoreMenuVo;
import shop.alien.mapper.*;
import shop.alien.store.service.LifeGroupBuyService;
import shop.alien.util.common.JwtUtil;
import shop.alien.util.type.LifeCollectIdentityQuery;
import shop.alien.util.type.TypeUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 团购
 */
@Service
@RequiredArgsConstructor
public class LifeGroupBuyServiceImpl extends ServiceImpl<LifeGroupBuyMainMapper, LifeGroupBuyMain> implements LifeGroupBuyService {

    private final LifeGroupBuyMainMapper lifeGroupBuyMainMapper;

    private final LifeGroupBuyThaliMapper lifeGroupBuyThaliMapper;

    private final StoreImgMapper storeImgMapper;

    private final EssentialHolidayComparisonMapper essentialHolidayComparisonMapper;

    private final StoreMenuMapper storeMenuMapper;

    private final LifeCollectMapper lifeCollectMapper;

    private final TypeUtil typeUtil;

    private final WebAuditMapper webAuditMapper;

    private final LifeUserOrderMapper lifeUserOrderMapper;

    @Override
    public boolean saveThali(LifeGroupBuyDto lifeGroupBuyDto) {
        JSONObject currentUserInfo = JwtUtil.getCurrentUserInfo();
        Integer userId = null;
        if (!ObjectUtils.isEmpty(currentUserInfo)) {
            userId = currentUserInfo.getInteger("userId");
        }
        LifeGroupBuyMain lifeGroupBuyMain = lifeGroupBuyDto.getLifeGroupBuyMain();
        List<LifeGroupBuyThali> lifeGroupBuyThalis = lifeGroupBuyDto.getLifeGroupBuyThalis();
        if (ObjectUtils.isEmpty(lifeGroupBuyMain.getId())) {
            Integer count = lifeGroupBuyMainMapper.selectCount(new LambdaQueryWrapper<LifeGroupBuyMain>().like(LifeGroupBuyMain::getCreatedTime, DateUtils.formatDate(new Date(), "yyyy-MM-dd")).eq(LifeGroupBuyMain::getStoreId, lifeGroupBuyMain.getStoreId()));
            lifeGroupBuyMain.setGroupNo("G" + DateUtils.formatDate(new Date(), "yyyyMMdd") + lifeGroupBuyMain.getStoreId() + org.apache.commons.lang3.StringUtils.leftPad(String.valueOf(count + 1), 5, "0"));
            lifeGroupBuyMain.setCreatedUserId(userId);
            lifeGroupBuyMainMapper.insert(lifeGroupBuyMain);
            if (ObjectUtils.isNotEmpty(lifeGroupBuyThalis)) {
                for (int i = 0; i < lifeGroupBuyThalis.size(); i++) {
                    LifeGroupBuyThali lifeGroupBuyThali = lifeGroupBuyThalis.get(i);
                    lifeGroupBuyThali.setParentId(lifeGroupBuyMain.getId().toString());
                    lifeGroupBuyThali.setDetailSort(i + 1);
                    lifeGroupBuyThali.setCreatedUserId(userId);
                    lifeGroupBuyThaliMapper.insert(lifeGroupBuyThali);
                }
            }
            return true;
        } else {
            lifeGroupBuyMain.setUpdatedUserId(userId);
            lifeGroupBuyMainMapper.updateById(lifeGroupBuyMain);
            lifeGroupBuyThaliMapper.update(null, new LambdaUpdateWrapper<LifeGroupBuyThali>().eq(LifeGroupBuyThali::getParentId, lifeGroupBuyMain.getId()).set(LifeGroupBuyThali::getDeleteFlag, 1));
            if (ObjectUtils.isNotEmpty(lifeGroupBuyThalis)) {
                for (int i = 0; i < lifeGroupBuyThalis.size(); i++) {
                    LifeGroupBuyThali lifeGroupBuyThali = lifeGroupBuyThalis.get(i);
                    lifeGroupBuyThali.setParentId(lifeGroupBuyMain.getId().toString());
                    lifeGroupBuyThali.setDetailSort(i + 1);
                    lifeGroupBuyThali.setCreatedUserId(userId);
                    lifeGroupBuyThaliMapper.insert(lifeGroupBuyThali);
                }
            }
            return true;
        }
    }

    @Override
    public LifeGroupBuyThali saveThaliNew(LifeGroupBuyDto lifeGroupBuyDto) {
        JSONObject currentUserInfo = JwtUtil.getCurrentUserInfo();
        Integer userId = null;
        if (!ObjectUtils.isEmpty(currentUserInfo)) {
            userId = currentUserInfo.getInteger("userId");
        }
        LifeGroupBuyMain lifeGroupBuyMain = lifeGroupBuyDto.getLifeGroupBuyMain();
        List<LifeGroupBuyThali> lifeGroupBuyThalis = lifeGroupBuyDto.getLifeGroupBuyThalis();
        LifeGroupBuyThali lifeGroupBuyThali = null;
        if (ObjectUtils.isEmpty(lifeGroupBuyMain.getId())) {
            Integer count = lifeGroupBuyMainMapper.selectCount(new LambdaQueryWrapper<LifeGroupBuyMain>().like(LifeGroupBuyMain::getCreatedTime, DateUtils.formatDate(new Date(), "yyyy-MM-dd")).eq(LifeGroupBuyMain::getStoreId, lifeGroupBuyMain.getStoreId()));
            lifeGroupBuyMain.setGroupNo("G" + DateUtils.formatDate(new Date(), "yyyyMMdd") + lifeGroupBuyMain.getStoreId() + org.apache.commons.lang3.StringUtils.leftPad(String.valueOf(count + 1), 5, "0"));
            lifeGroupBuyMain.setCreatedUserId(userId);
            lifeGroupBuyMain.setCreatedTime(new Date());
            lifeGroupBuyMainMapper.insert(lifeGroupBuyMain);
            if (ObjectUtils.isNotEmpty(lifeGroupBuyThalis)) {
                for (int i = 0; i < lifeGroupBuyThalis.size(); i++) {
                    lifeGroupBuyThali = lifeGroupBuyThalis.get(i);
                    lifeGroupBuyThali.setParentId(lifeGroupBuyMain.getId().toString());
                    lifeGroupBuyThali.setDetailSort(i + 1);
                    lifeGroupBuyThali.setCreatedUserId(userId);
                    lifeGroupBuyThali.setCreatedTime(new Date());
                    lifeGroupBuyThaliMapper.insert(lifeGroupBuyThali);
                }
            }
            return lifeGroupBuyThali;
        } else {
            lifeGroupBuyMain.setUpdatedUserId(userId);
            lifeGroupBuyMain.setCreatedTime(new Date());
            lifeGroupBuyMainMapper.updateById(lifeGroupBuyMain);
            lifeGroupBuyThaliMapper.update(null, new LambdaUpdateWrapper<LifeGroupBuyThali>().eq(LifeGroupBuyThali::getParentId, lifeGroupBuyMain.getId()).set(LifeGroupBuyThali::getDeleteFlag, 1).set(LifeGroupBuyThali::getCreatedTime, new Date()));
            if (ObjectUtils.isNotEmpty(lifeGroupBuyThalis)) {
                for (int i = 0; i < lifeGroupBuyThalis.size(); i++) {
                    lifeGroupBuyThali = lifeGroupBuyThalis.get(i);
                    lifeGroupBuyThali.setParentId(lifeGroupBuyMain.getId().toString());
                    lifeGroupBuyThali.setDetailSort(i + 1);
                    lifeGroupBuyThali.setCreatedUserId(userId);
                    lifeGroupBuyThaliMapper.insert(lifeGroupBuyThali);
                }
            }
            return lifeGroupBuyThali;
        }
    }

    @Override
    public IPage<LifeGroupBuyThaliVo> getThaliList(int page, int size, String storeId, String status, String groupName, String groupType) {
        QueryWrapper<LifeGroupBuyThaliVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(storeId), "store_id", storeId);
        if (status.equals("8")) {
            queryWrapper.in(StringUtils.isNotEmpty(status), "status", 2, 6);
        } else {
            queryWrapper.eq(StringUtils.isNotEmpty(status), "status", status);
        }
        queryWrapper.eq(StringUtils.isNotEmpty(groupType), "group_type", groupType);
        queryWrapper.like(StringUtils.isNotEmpty(groupName), "group_name", groupName);
        queryWrapper.eq("delete_flag", 0);
        queryWrapper.orderByDesc("created_time");
        IPage<LifeGroupBuyThaliVo> lifeGroupBuyThaliVoIPage = new Page<>(page, size);
        IPage<LifeGroupBuyThaliVo> voIPage = lifeGroupBuyMainMapper.selectPageByThaliVo(lifeGroupBuyThaliVoIPage, queryWrapper);
        voIPage.getRecords().forEach(this::getMainImgAndDisableDate);
        return voIPage;
    }

    @Override
    public LifeGroupBuyThaliVo getThaliById(String id, String userId) {
        LifeGroupBuyMain lifeGroupBuyMain = lifeGroupBuyMainMapper.selectById(id);
        LifeGroupBuyThaliVo lifeGroupBuyThaliVo = new LifeGroupBuyThaliVo();
        BeanUtils.copyProperties(lifeGroupBuyMain, lifeGroupBuyThaliVo);
        List<LifeGroupBuyThali> lifeGroupBuyThalis = lifeGroupBuyThaliMapper.selectList(new LambdaQueryWrapper<LifeGroupBuyThali>().eq(LifeGroupBuyThali::getParentId, id).eq(LifeGroupBuyThali::getDeleteFlag, 0));

        // 是否收藏了该团购
        LambdaQueryWrapper<LifeCollect> collectQuery = new LambdaQueryWrapper<>();
        LifeCollectIdentityQuery.applyUserSide(collectQuery, LifeCollectIdentityQuery.resolve(userId, typeUtil));
        collectQuery.eq(LifeCollect::getCouponId, id);
        LifeCollect lifeCollect = lifeCollectMapper.selectOne(collectQuery);
        lifeGroupBuyThaliVo.setIsCollect("0");
        if (!Objects.isNull(lifeCollect)) {
            lifeGroupBuyThaliVo.setIsCollect("1");
        }
        //美食
        if (lifeGroupBuyMain.getGroupType() == 1) {
            for (LifeGroupBuyThali lifeGroupBuyThali : lifeGroupBuyThalis) {
                if (StringUtils.isNotEmpty(lifeGroupBuyThali.getDetailId())) {
                    StoreMenuVo menuInfo = storeMenuMapper.getMenuInfo(Integer.parseInt(lifeGroupBuyThali.getDetailId()));
                    if (ObjectUtils.isNotEmpty(menuInfo)) {
                        lifeGroupBuyThali.setDishName(menuInfo.getDishName());
                        lifeGroupBuyThali.setDishImg(menuInfo.getImgUrl());
                        lifeGroupBuyThali.setDishPrice(menuInfo.getDishPrice().toString());
                        lifeGroupBuyThali.setDishesUnit(menuInfo.getDishesUnit());
                    }
                }
            }
        }

        Map<String, List<LifeGroupBuyThali>> collect = lifeGroupBuyThalis.stream().collect(Collectors.groupingBy(LifeGroupBuyThali::getGroupName));
        List<LifeGroupBuyNameThaliVo> resultMap = new ArrayList<>();
        List<String> keys = collect.entrySet().stream().sorted(Comparator.comparingInt(i -> i.getValue().get(0).getDetailSort())).map(Map.Entry::getKey).collect(Collectors.toList());
        for (String key : keys) {
            LifeGroupBuyNameThaliVo lifeGroupBuyNameThaliVo = new LifeGroupBuyNameThaliVo();
            lifeGroupBuyNameThaliVo.setGroupName(key);
            lifeGroupBuyNameThaliVo.setDetails(collect.get(key).stream().sorted(Comparator.comparingInt(LifeGroupBuyThali::getDetailSort)).collect(Collectors.toList()));
            resultMap.add(lifeGroupBuyNameThaliVo);
        }
        lifeGroupBuyThaliVo.setDetails(resultMap);
        getMainImgAndDisableDate(lifeGroupBuyThaliVo);

        //已售数量
        lifeGroupBuyThaliVo.setSaleNum(lifeUserOrderMapper.countBuyGroup(id));

        return lifeGroupBuyThaliVo;
    }

    @Override
    public boolean updateStatus(String id, String status, String approvalComments) {
        LambdaUpdateWrapper<LifeGroupBuyMain> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(LifeGroupBuyMain::getId, id);
        lambdaUpdateWrapper.set(LifeGroupBuyMain::getStatus, status);
        lambdaUpdateWrapper.set(LifeGroupBuyMain::getApprovalComments, approvalComments);
        if(status.equals("5")){
            LifeGroupBuyMain lifeGroupBuyMain = lifeGroupBuyMainMapper.selectById(id);
            if(lifeGroupBuyMain !=null && lifeGroupBuyMain.getStatus()==2){
                lambdaUpdateWrapper.set(LifeGroupBuyMain::getStartTimeValue, new Date());
            }
        }
            lifeGroupBuyMainMapper.update(null,lambdaUpdateWrapper);
        //处理中台审核记录
        if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(status) && (status.equals("2") || status.equals("3"))) {
            LambdaUpdateWrapper<WebAudit> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(WebAudit::getLifeGroupPackageId, id);
            wrapper.set(WebAudit::getStatus, "1");
            webAuditMapper.update(null, wrapper);
        }
        return true;
    }

    @Override
    public boolean delThaliById(String id, String groupType) {
        if ("1".equals(groupType)) {
            lifeGroupBuyThaliMapper.update(null, new LambdaUpdateWrapper<LifeGroupBuyThali>().eq(LifeGroupBuyThali::getParentId, id).set(LifeGroupBuyThali::getDeleteFlag, 1));
        }
        lifeGroupBuyMainMapper.update(null, new LambdaUpdateWrapper<LifeGroupBuyMain>().eq(LifeGroupBuyMain::getId, id).set(LifeGroupBuyMain::getDeleteFlag, 1));
        return true;
    }

    @Override
    public boolean updateNum(String id, String num) {
        //判断库存数为0 增加库存数修改状态为进行中
        LambdaQueryWrapper<LifeGroupBuyMain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LifeGroupBuyMain :: getId, id);
        LifeGroupBuyMain lifeGroupBuyMain = lifeGroupBuyMainMapper.selectOne(lambdaQueryWrapper);

        if(lifeGroupBuyMain.getInventoryNum() == 0){
            LambdaUpdateWrapper<LifeGroupBuyMain> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(LifeGroupBuyMain :: getId, id);
            lambdaUpdateWrapper.set(LifeGroupBuyMain :: getStatus, 5);
            lambdaUpdateWrapper.set(LifeGroupBuyMain :: getInventoryNum, num);
            lifeGroupBuyMainMapper.update(null, lambdaUpdateWrapper);
        }
        else {
            LambdaUpdateWrapper<LifeGroupBuyMain> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(LifeGroupBuyMain::getId, id);
            lambdaUpdateWrapper.set(LifeGroupBuyMain::getInventoryNum, num);
            lifeGroupBuyMainMapper.update(null, lambdaUpdateWrapper);
        }

        return true;
    }

    private void getMainImgAndDisableDate(LifeGroupBuyThaliVo record) {
        //图片
        if (StringUtils.isNotEmpty(record.getImageId())) {
            List<String> imgIds = Arrays.asList(record.getImageId().split(","));
            List<StoreImg> storeImgs = storeImgMapper.selectList(new LambdaQueryWrapper<StoreImg>().in(StoreImg::getId, imgIds));
            if (ObjectUtils.isNotEmpty(storeImgs)) {
                /*String imgs = storeImgs.stream()
                        .map(StoreImg::getImgUrl)
                        .collect(Collectors.joining("*"));
                record.setImageValueStr(imgs);*/
                record.setImageValueStr(storeImgs.stream().map(StoreImg::getImgUrl).collect(Collectors.toList()));
            }
        }
        //不可用日期
        if (ObjectUtils.isNotEmpty(record.getDisableDateType())) {
            if (record.getDisableDateType() == 1) {
                List<String> valueList = Arrays.asList(record.getDisableDateValue().split(";"));
                String holiday = "";
                if (valueList.size() > 1) {
                    List<String> list = Arrays.asList(valueList.get(1).split(","));
                    List<EssentialHolidayComparison> essentialHolidayComparisons = essentialHolidayComparisonMapper.selectList(new LambdaQueryWrapper<EssentialHolidayComparison>().in(EssentialHolidayComparison::getId, list));
                    holiday = essentialHolidayComparisons.stream().map(EssentialHolidayComparison::getFestivalName).collect(Collectors.joining(","));
                }
                if (StringUtils.isNotEmpty(valueList.get(0)) && StringUtils.isNotEmpty(holiday)) {
                    record.setDisableDateValueStr(valueList.get(0) + ";" + holiday);
                }
                if (StringUtils.isEmpty(valueList.get(0))) {
                    record.setDisableDateValueStr(holiday);
                }
                if (StringUtils.isEmpty(holiday)) {
                    record.setDisableDateValueStr(valueList.get(0));
                }
            }
        }
    }
}
