package com.zbkj.service.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.model.home.Home;
import com.zbkj.common.model.home.HomeItem;
import com.zbkj.common.model.product.StoreProduct;
import com.zbkj.common.request.*;
import com.zbkj.common.response.*;
import com.zbkj.common.utils.RedisUtil;
import com.zbkj.common.vo.HomeItemVo;
import com.zbkj.common.vo.HomeVo;
import com.zbkj.common.vo.product.ProductInfoVo;
import com.zbkj.service.dao.HomeDao;
import com.zbkj.service.dao.HomeItemDao;
import com.zbkj.service.service.CategoryService;
import com.zbkj.service.service.EbHomeItemService;
import com.zbkj.service.service.EbHomeService;
import com.zbkj.service.service.StoreProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

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


@Service
public class EbHomeServiceImpl extends ServiceImpl<HomeDao, Home> implements EbHomeService {

    @Autowired private RedisUtil redisUtil;
    @Autowired private HomeDao dao;
    @Autowired private HomeItemDao homeItemDao;
    @Autowired private EbHomeItemService homeItemService;
    @Autowired private StoreProductService productService;
    @Autowired private CategoryService categoryService;

    @Override
    public List<HomeVo> getIndexHomeList(Integer storeId) {
        List<HomeVo> homeVos = dao.selectPageFloor(new FloorRequest(Constants.HOME_TYPE_1, storeId + ""));
        for (HomeVo homeVo : homeVos) {
            // 默认展示5个
            PageParamRequest fpPage = new PageParamRequest();
            fpPage.setPage(1);
            fpPage.setLimit(5);
            FloorProRequest fp = new FloorProRequest();
            fp.setHomeId(homeVo.getId());
            List<HomeItemVo> fpResult = selectPageFloorItem(fp, fpPage);
            homeVo.setItems(fpResult);
        }
        return homeVos;
    }

    @Override
    public List<SetMealResponse> selectPageSetMealType(SetMealRequest entity, PageParamRequest page) {
        PageHelper.startPage(page.getPage(), page.getLimit());
        return dao.selectPageSetMealType(entity);
    }

    @Override
    public List<HomeVo> selectPageFloor(FloorRequest entity, PageParamRequest page) {
        PageHelper.startPage(page.getPage(), page.getLimit());
        List<HomeVo> list = dao.selectPageFloor(entity);
        PageHelper.clearPage();
        for (HomeVo home : list) {
            // 默认展示5个
            PageParamRequest fpPage = new PageParamRequest();
            fpPage.setPage(1);
            fpPage.setLimit(5);
            FloorProRequest fp = new FloorProRequest();
            fp.setHomeId(home.getId());
            List<HomeItemVo> fpResult = selectPageFloorItem(fp, fpPage);
            home.setItems(fpResult);
        }
        return list;
    }

    @Override
    public List<HomeItemVo> selectPageFloorItem(FloorProRequest entity, PageParamRequest page) {
        List<HomeItemVo> list = selectFloorItem(entity, page);
        List<HomeItemVo> proList = list.stream().filter(i -> i.getType() == 0).collect(Collectors.toList());
        if (!proList.isEmpty()) {
            List<Integer> pIds = proList.stream().map(HomeItemVo::getJumpIds).map(Integer::valueOf).collect(Collectors.toList());
            Map<Integer, StoreProduct> h5Detail = productService.getH5Detail(pIds);
            for (HomeItemVo itemVo : list) {
                if (itemVo.getType() != 0) { continue; }
                StoreProduct storeProduct = h5Detail.get(Integer.parseInt(itemVo.getJumpIds()));
                ProductInfoVo productInfoVo = JSON.parseObject(JSON.toJSONString(storeProduct), ProductInfoVo.class);
                productInfoVo.setTagList(StringUtils.isNotBlank(productInfoVo.getTags()) ? Arrays.asList(productInfoVo.getTags().split(",")) : new ArrayList<>());
                itemVo.setProductInfo(productInfoVo);
            }
        }
        return list;
    }

    @Override
    public List<HomeItemVo> selectFloorItem(FloorProRequest entity, PageParamRequest page) {
        PageHelper.startPage(page.getPage(), page.getLimit());
        List<HomeItemVo> list = homeItemDao.selectHomeItem(entity.getHomeId());
        PageHelper.clearPage();
        return list;
    }

    @Override
    public List<HomeVo> getAdminList(HomeRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<Home> lambdaQueryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(request.getName())) {
            lambdaQueryWrapper.and(i -> i
                    .or().like(Home::getName, request.getName())
                    .or().like(Home::getTitle, request.getName()));
        }
        if (null != request.getJumpType()) {
            lambdaQueryWrapper.eq(Home::getJumpType, request.getJumpType());
        }
        if (StringUtils.isNotBlank(request.getChannel())) {
            lambdaQueryWrapper.apply( "FIND_IN_SET ('" + request.getChannel() + "', channel)");
        }
        lambdaQueryWrapper.orderByDesc(Home::getOrderNo).orderByDesc(Home::getId);
        List<Home> homeList = dao.selectList(lambdaQueryWrapper);
        if (homeList.isEmpty()) {
            return new ArrayList<>();
        }
        Map<Integer, String> cateMap = new HashMap<>();
        Map<Integer, String> prodMap = new HashMap<>();
        List<Integer> cateIds = homeList.stream().filter(i -> i.getJumpType() == 2).map(i -> Integer.parseInt(i.getJumpIds())).collect(Collectors.toList());
        List<Integer> prodIds = homeList.stream().filter(i -> i.getJumpType() == 1 ||  i.getJumpType() == 3).map(Home::getJumpIds).flatMap(scores -> Arrays.stream(scores.split(","))).map(Integer::parseInt).collect(Collectors.toList());
        if (!cateIds.isEmpty()) { cateMap = categoryService.getListInId(cateIds); }
        if (!prodIds.isEmpty()) { prodMap = productService.getName(prodIds); }
        Map<Integer, String> finalCateMap = cateMap;
        Map<Integer, String> finalProdMap = prodMap;
        return homeList.stream().map(i-> {
            HomeVo vo = new HomeVo();
            BeanUtils.copyProperties(i, vo);
            Map<Integer, String> jumpIdsMap = new HashMap<>();
            if (i.getJumpType() == 1 || i.getJumpType() == 3) {
                String[] pSplit = i.getJumpIds().split(",");
                for (String pId : pSplit) {
                    Integer productId = Integer.parseInt(pId);
                    jumpIdsMap.put(productId, finalProdMap.get(productId));
                }
            } else if (i.getJumpType() == 2) {
                Integer cateId = Integer.parseInt(i.getJumpIds());
                jumpIdsMap.put(cateId, finalCateMap.get(cateId));
            }
            vo.setJumpIdsMap(jumpIdsMap);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public boolean deleteById(Integer id) {
        dao.deleteById(id);

        LambdaQueryWrapper<HomeItem> lq = new LambdaQueryWrapper<>();
        lq.eq(HomeItem::getHomeId, id);
        List<HomeItem> homeItems = homeItemDao.selectList(lq);
        homeItems.forEach(i-> homeItemDao.deleteById(i.getId()));
        return true;
    }
}
