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.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.LifeFansVo;
import shop.alien.entity.store.vo.LifeStoreVo;
import shop.alien.entity.store.vo.LifeUserVo;
import shop.alien.entity.store.vo.StoreInfoVo;
import shop.alien.mapper.*;
import shop.alien.store.config.BaseRedisService;
import shop.alien.util.common.ListToPage;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * 门店
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LifeStoreService {

    private final LifeCollectMapper lifeCollectMapper;

    private final LifeUserMapper lifeUserMapper;

    private final LifeFansMapper lifeFansMapper;

    private final StoreInfoMapper storeInfoMapper;

    private final StoreInfoService storeInfoService;

    private final StoreUserService storeUserService;

    private final StoreImgService storeImgService;

    private final LifeUserService lifeUserService;

    private final LifeUserDynamicsMapper lifeUserDynamicsMapper;

    private final LifeBlacklistMapper lifeBlacklistMapper;

    private final BaseRedisService baseRedisService;

    public LifeUser loginByPhone(String phone) {
        LambdaUpdateWrapper<LifeUser> wrapperFans = new LambdaUpdateWrapper<>();
        wrapperFans.eq(LifeUser::getUserPhone, phone);
        List<LifeUser> userList = lifeUserMapper.selectList(wrapperFans);
        if (!CollectionUtils.isEmpty(userList)) {
            return userList.get(0);
        }
        return null;
    }

    /**
     * 我的关注
     */
    public IPage<LifeFansVo> getMyFollowed(String fansId, String name, int page, int size) {QueryWrapper<LifeFansVo> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), "foll.name", name)
                .or(StringUtils.isNotEmpty(name))
                .like(StringUtils.isNotEmpty(name), "foll.phoneId", name);
        wrapper.groupBy("foll.phoneId");
        String blockerType = "";
        String blockerId = "";
        if ("user".equals(fansId.split("_")[0])) {
            String myselfUserPhone = fansId.split("_")[1];
            blockerType = "2";
            LifeUser myLifeUser = lifeUserService.getUserByPhone(myselfUserPhone);
            blockerId = String.valueOf(myLifeUser.getId());
        } else {
            String myselfStorePhone = fansId.split("_")[1];
            blockerType = "1";
            StoreUser myStoreUser = storeUserService.getUserByPhone(myselfStorePhone);
            blockerId = String.valueOf(myStoreUser.getId());
        }
        IPage<LifeFansVo> myFollowed = lifeFansMapper.getMyFollowed(new Page<>(page, size), fansId, blockerType, blockerId, wrapper);
        // 过滤掉我拉黑的
        List<LifeFansVo> collect = myFollowed.getRecords().stream().filter(x -> null == x.getBlackListid()).collect(Collectors.toList());
        myFollowed.setRecords(collect);
        myFollowed.setTotal(collect.size());
        return myFollowed;
    }

    /**
     * 我的关注所有
     */
    public List<LifeFansVo> getMyFollowedAll(String fansId) {
        return lifeFansMapper.getMyFollowedAll(fansId);
    }

    /**
     * 我的粉丝
     */
    public IPage<LifeFansVo> getMyFans(String fansId, String name, int page, int size) {
        QueryWrapper<LifeFansVo> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), "foll.name", name);
        wrapper.groupBy("foll.phoneId");
        String blockerType = "";
        String blockerId = "";
        if ("user".equals(fansId.split("_")[0])) {
            String myselfUserPhone = fansId.split("_")[1];
            blockerType = "2";
            LifeUser myLifeUser = lifeUserService.getUserByPhone(myselfUserPhone);
            blockerId = String.valueOf(myLifeUser.getId());
        } else {
            String myselfStorePhone = fansId.split("_")[1];
            blockerType = "1";
            StoreUser myStoreUser = storeUserService.getUserByPhone(myselfStorePhone);
            blockerId = String.valueOf(myStoreUser.getId());
        }
        IPage<LifeFansVo> myFans = lifeFansMapper.getMyFans(new Page<>(page, size), fansId, blockerType, blockerId, wrapper);
        List<LifeFansVo> collect = myFans.getRecords().stream().filter(x -> null == x.getBlackListid()).collect(Collectors.toList());
        myFans.setRecords(collect);
        myFans.setTotal(collect.size());
        return myFans;
    }

    /**
     * 我的商家粉丝
     */
    public IPage<LifeFansVo> getMyStoreFans(String fansId, String name, int page, int size) {
        QueryWrapper<LifeFansVo> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), "foll.name", name);
        wrapper.groupBy("foll.phoneId");
        IPage<LifeFansVo> myStoreFans = lifeFansMapper.getMyStoreFans(new Page<>(page, size), fansId, wrapper);
        filterBlocked(fansId, myStoreFans);
        List<LifeFansVo> collect = myStoreFans.getRecords().stream().filter(x -> x.getIsBlocked().equals("0")).collect(Collectors.toList());
        myStoreFans.setRecords(collect);
        myStoreFans.setTotal(collect.size());
        return myStoreFans;
    }

    /**
     * 我的用户粉丝
     */
    public IPage<LifeFansVo> getMyUserFans(String fansId, String name, int page, int size) {
        QueryWrapper<LifeFansVo> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), "foll.name", name);
        wrapper.groupBy("foll.phoneId");
        IPage<LifeFansVo> myUserFans = lifeFansMapper.getMyUserFans(new Page<>(page, size), fansId, wrapper);
        filterBlocked(fansId, myUserFans);
        List<LifeFansVo> collect = myUserFans.getRecords().stream().filter(x -> x.getIsBlocked().equals("0")).collect(Collectors.toList());
        myUserFans.setRecords(collect);
        myUserFans.setTotal(collect.size());
        return myUserFans;
    }

    /**
     * 互相关注
     */
    public IPage<LifeFansVo> getMutualAttention(String fansId, String name, int page, int size) {
        QueryWrapper<LifeFansVo> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), "foll.name", name);
        wrapper.groupBy("foll.phoneId");
        String blockerType = "";
        String blockerId = "";
        if ("user".equals(fansId.split("_")[0])) {
            String myselfUserPhone = fansId.split("_")[1];
            blockerType = "2";
            LifeUser myLifeUser = lifeUserService.getUserByPhone(myselfUserPhone);
            blockerId = String.valueOf(myLifeUser.getId());
        } else {
            String myselfStorePhone = fansId.split("_")[1];
            blockerType = "1";
            StoreUser myStoreUser = storeUserService.getUserByPhone(myselfStorePhone);
            blockerId = String.valueOf(myStoreUser.getId());
        }
        IPage<LifeFansVo> mutualAttention = lifeFansMapper.getMutualAttention(new Page<>(page, size), fansId, blockerType, blockerId, wrapper);
        List<LifeFansVo> collect = mutualAttention.getRecords().stream().filter(x -> null == x.getBlackListid()).collect(Collectors.toList());
        mutualAttention.setRecords(collect);
        mutualAttention.setTotal(collect.size());
        return mutualAttention;
    }

    /**
     * 互相关注（仅用户)
     */
    public IPage<LifeFansVo> getMutualAttentionUser(String fansId, String name, int page, int size) {
        QueryWrapper<LifeFansVo> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), "foll.name", name);
        wrapper.groupBy("foll.phoneId");
        IPage<LifeFansVo> mutualAttention = lifeFansMapper.getMutualAttentionUser(new Page<>(page, size), fansId, wrapper);
        filterBlocked(fansId, mutualAttention);
        List<LifeFansVo> collect = mutualAttention.getRecords().stream().filter(x -> x.getIsBlocked().equals("0")).collect(Collectors.toList());
        mutualAttention.setRecords(collect);
        mutualAttention.setTotal(collect.size());
        return mutualAttention;
    }

    public LifeFansVo getHomePageInfo(String phoneId) {
        QueryWrapper<LifeFansVo> wrapper = new QueryWrapper<>();
        wrapper.groupBy("foll.phoneId");

        // 判断自己的拉黑type
        String blockerType = "";
        String blockerId = "";
        if ("user".equals(phoneId.split("_")[0])) {
            String myselfUserPhone = phoneId.split("_")[1];
            blockerType = "2";
            LifeUser myLifeUser = lifeUserService.getUserByPhone(myselfUserPhone);
            blockerId = String.valueOf(myLifeUser.getId());
        } else {
            String myselfStorePhone = phoneId.split("_")[1];
            blockerType = "1";
            StoreUser myStoreUser = storeUserService.getUserByPhone(myselfStorePhone);
            blockerId = String.valueOf(myStoreUser.getId());
        }

        IPage<LifeFansVo> myFollowed = lifeFansMapper.getMyFollowed(new Page<>(1, Integer.MAX_VALUE), phoneId, blockerType, blockerId, wrapper);
        int followedNum = myFollowed.getRecords().stream().filter(x -> null == x.getBlackListid()).collect(Collectors.toList()).size();

        IPage<LifeFansVo> myFans = lifeFansMapper.getMyFans(new Page<>(1, Integer.MAX_VALUE), phoneId, blockerType, blockerId, wrapper);
        int fansNum = myFans.getRecords().stream().filter(x -> null == x.getBlackListid()).collect(Collectors.toList()).size();

        IPage<LifeFansVo> mutualAttention = lifeFansMapper.getMutualAttention(new Page<>(1, Integer.MAX_VALUE), phoneId, blockerType, blockerId, wrapper);
        int friendNum = mutualAttention.getRecords().stream().filter(x -> null == x.getBlackListid()).collect(Collectors.toList()).size();

        LifeFansVo lifeFansVo = lifeFansMapper.getHomePageInfo(phoneId);
        lifeFansVo.setFollowNum(String.valueOf(followedNum));
        lifeFansVo.setFansNum(String.valueOf(fansNum));
        lifeFansVo.setFriendNum(String.valueOf(friendNum));

        return lifeFansVo;
    }

    /**
     * 用户粉丝
     *
     * @param storeId
     * @param name
     * @param page
     * @param size
     * @return
     */
    public IPage<LifeUserVo> getUserFans(String storeId, String name, int page, int size) {
        List<LifeUser> mapList = null;
        LambdaUpdateWrapper<LifeFans> wrapperFans = new LambdaUpdateWrapper<>();
        wrapperFans.eq(LifeFans::getFollowedId, storeId);
        wrapperFans.eq(LifeFans::getFansType, "1");
        List<LifeFans> userfans = lifeFansMapper.selectList(wrapperFans);
        if (!CollectionUtils.isEmpty(userfans)) {
            List<String> userIds = userfans.stream().map(LifeFans::getFansId).collect(Collectors.toList());
            LambdaUpdateWrapper<LifeUser> wrapperUser = new LambdaUpdateWrapper<>();
            wrapperUser.like(StringUtils.isNotEmpty(name), LifeUser::getUserName, name);
            wrapperUser.in(LifeUser::getId, userIds);
            mapList = lifeUserMapper.selectList(wrapperUser);
        }
        LambdaUpdateWrapper<LifeFans> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(LifeFans::getFollowedId, storeId);
        List<LifeUserVo> mapListVo = new ArrayList<>();
        if (!CollectionUtils.isEmpty(mapList)) {
            for (LifeUser store : mapList) {
                wrapper.eq(LifeFans::getFansId, store.getId());
                List<LifeFans> lifeFans = lifeFansMapper.selectList(wrapper);
                LifeUserVo vo = new LifeUserVo();
                BeanUtils.copyProperties(store, vo);
                if (CollectionUtils.isEmpty(lifeFans)) {
                    vo.setIsGuanzhu("0");
                } else {
                    vo.setIsGuanzhu("1");
                }
                mapListVo.add(vo);
            }
        }
        return ListToPage.setPage(mapListVo, page, size);
    }

    public List<LifeStoreVo> getStores(String storeName, String storeContact,
                                       String storePhone, String storeType, String userId) {
        checkAndUpdateExpiredRecords();
        QueryWrapper<StoreInfoVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!storeName.isEmpty(), "a.store_name", storeName);
        queryWrapper.like(!storeContact.isEmpty(), "a.store_contact", storeContact);
        queryWrapper.like(!storePhone.isEmpty(), "b.phone", storePhone);
        queryWrapper.like(!storeType.isEmpty(), "a.store_type", storeType).eq("a.delete_flag", 0);
        queryWrapper.orderByDesc("created_time");
        List<StoreInfoVo> result = storeInfoMapper.getStoreInfoVoList(queryWrapper);
        List<LifeStoreVo> resultVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(result)) {
            for (StoreInfoVo store : result) {
                LifeStoreVo vo = new LifeStoreVo();
                BeanUtils.copyProperties(store, vo);
                LambdaUpdateWrapper<LifeCollect> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(LifeCollect::getStoreId, store.getId());
                wrapper.eq(LifeCollect::getUserId, userId);
                List<LifeCollect> storeShoucangs = lifeCollectMapper.selectList(wrapper);
                if (!CollectionUtils.isEmpty(storeShoucangs)) {
                    vo.setIsShoucang("1");
                } else {
                    vo.setIsShoucang("0");
                }
                resultVos.add(vo);
            }
        }
        return resultVos;
    }

    /**
     * 根据过期时间修改状态
     */
    public void checkAndUpdateExpiredRecords() {
        LambdaUpdateWrapper<StoreInfo> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.isNotNull(StoreInfo::getExpirationTime)
                .lt(StoreInfo::getExpirationTime, LocalDateTime.now())
                .eq(StoreInfo::getBusinessStatus, 0)
                .set(StoreInfo::getBusinessStatus, 99);
        storeInfoService.update(queryWrapper);
    }

    public boolean modifyPassword(String phone, String passWord) {
        LambdaUpdateWrapper<StoreUser> wrapperFans = new LambdaUpdateWrapper<>();
        wrapperFans.eq(StoreUser::getPhone, phone);
        wrapperFans.set(StoreUser::getPassword, passWord);
        return storeUserService.update(null, wrapperFans);
    }

    /**
     * 商户粉丝
     *
     * @param storeId
     * @param storeContact
     * @param page
     * @param size
     * @return
     */
    public IPage<LifeStoreVo> getStoreFans(String storeId, String storeContact, int page, int size) {
        LambdaUpdateWrapper<LifeFans> wrapperFans = new LambdaUpdateWrapper<>();
        wrapperFans.eq(LifeFans::getFollowedId, storeId);
        wrapperFans.eq(LifeFans::getFansType, "2");
        List<LifeFans> userFans = lifeFansMapper.selectList(wrapperFans);
        if (!CollectionUtils.isEmpty(userFans)) {
            List<String> storeIds = userFans.stream().map(LifeFans::getFansId).collect(Collectors.toList());
            QueryWrapper<StoreInfoVo> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("a.id", storeIds).eq("a.delete_flag", 0).eq("b.name", storeContact);
            List<StoreInfoVo> storeInfoVoList = storeInfoMapper.getStoreInfoVoList(queryWrapper);
            List<LifeStoreVo> mapListVo = new ArrayList<>();
            if (!CollectionUtils.isEmpty(storeInfoVoList)) {
                for (StoreInfoVo store : storeInfoVoList) {
                    LambdaUpdateWrapper<LifeFans> wrapper = new LambdaUpdateWrapper<>();
                    wrapper.eq(LifeFans::getFollowedId, store.getId());
                    wrapper.eq(LifeFans::getFansId, storeId);
                    wrapper.eq(LifeFans::getFollowedId, store.getId());
                    List<LifeFans> lifeFans = lifeFansMapper.selectList(wrapper);
                    LifeStoreVo vo = new LifeStoreVo();
                    BeanUtils.copyProperties(store, vo);
                    if (CollectionUtils.isEmpty(lifeFans)) {
                        vo.setIsGuanzhu("0");
                    } else {
                        vo.setIsGuanzhu("1");
                    }
                    mapListVo.add(vo);
                }
            }
            return ListToPage.setPage(mapListVo, page, size);
        }
        return null;
    }

    public boolean deleteLunbotu(String id) {
        LambdaQueryWrapper<StoreImg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(StoreImg::getStoreId, id);
        return storeImgService.remove(lambdaQueryWrapper);
    }

    public List<String> getLunbotu() {
        LambdaQueryWrapper<StoreImg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StoreImg::getDeleteFlag, 0);
        List<StoreImg> list = storeImgService.list(lambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            return list.stream().map(StoreImg::getImgUrl).collect(Collectors.toList());
        }
        return null;
    }

    public boolean uploadLunbotu(String storeId, String lunbotu) {
        LambdaUpdateWrapper<StoreImg> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(StoreImg::getStoreId, storeId)
                .set(StoreImg::getImgUrl, lunbotu);
        return storeImgService.update(null, updateWrapper);
    }


    private void filterBlocked(String fansId, IPage<LifeFansVo> myFollowed) {

        // 判断自己的拉黑type
        LifeUser myLifeUser = null;
        StoreUser myStoreUser = null;
        if ("user".equals(fansId.split("_")[0])) {
            String myselfUserPhone = fansId.split("_")[1];
            myLifeUser = lifeUserService.getUserByPhone(myselfUserPhone);
        } else {
            String myselfStorePhone = fansId.split("_")[1];
            myStoreUser = storeUserService.getUserByPhone(myselfStorePhone);
        }

        LambdaQueryWrapper<LifeBlacklist> lifeBlacklistWrapper = new LambdaQueryWrapper<>();
        if (null != myLifeUser) {
            lifeBlacklistWrapper.eq(LifeBlacklist::getBlockerType, "2");
            lifeBlacklistWrapper.eq(LifeBlacklist::getBlockerId, myLifeUser.getId());
        } else {
            lifeBlacklistWrapper.eq(LifeBlacklist::getBlockerType, "1");
            lifeBlacklistWrapper.eq(LifeBlacklist::getBlockerId, myStoreUser.getId());
        }
        List<LifeBlacklist> lifeBlacklist = lifeBlacklistMapper.selectList(lifeBlacklistWrapper);
        Map<String, List<LifeBlacklist>> collect = lifeBlacklist.stream().collect(Collectors.groupingBy(x -> x.getBlockedId()));
        for (LifeFansVo lifeFansVo : myFollowed.getRecords()) {
            // 判断被拉黑的type
            LifeUser lifeUser = null;
            StoreUser storeUser = null;
            if ("user".equals(lifeFansVo.getPhoneId().split("_")[0])) {
                String userPhone = lifeFansVo.getPhoneId().split("_")[1];
                lifeUser = lifeUserService.getUserByPhone(userPhone);
            } else {
                String storePhone = lifeFansVo.getPhoneId().split("_")[1];
                storeUser = storeUserService.getUserByPhone(storePhone);
            }
            //查询是否已拉黑
            String blockedId = "";
            String blockedType = "";
            if (null != lifeUser) {
                blockedId = String.valueOf(lifeUser.getId());
                blockedType = "2";
            } else {
                blockedId = String.valueOf(storeUser.getId());
                blockedType = "1";
            }
            lifeFansVo.setIsBlocked("0");
            if (collect.containsKey(blockedId)) {
                String finalBlockedType = blockedType;
                Optional<LifeBlacklist> first = collect.get(blockedId).stream().filter(x -> x.getBlockedType().equals(finalBlockedType)).findFirst();
                if (first.isPresent()) {
                    lifeFansVo.setIsBlocked("1");
                }
            }
        }
    }
}
