package com.gree.mall.manager.logic.goods;

import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.CommonTemplateVO;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.carouselMap.CarouselMapVO;
import com.gree.mall.manager.bean.goods.*;
import com.gree.mall.manager.commonmapper.CommonPageV2Mapper;
import com.gree.mall.manager.enums.GoodsNewsCategoryGoodsTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class GoodsNewsCategoryLogic {

    @Autowired
    private GoodsNewsCategoryService goodsNewsCategoryService;
    @Autowired
    private GoodsNewsCategoryGoodsService goodsNewsCategoryGoodsService;

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsSpecService goodsSpecService;
    @Autowired
    CommonLogic commonLogic;

    @Autowired
    CommonPageV2Mapper commonPageV2Mapper;



    /**
     * 分页获取商品新维度分类
     */
    public IPage<GoodsNewsCategory> pageGoodsNewsCategory(HttpServletRequest request, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();

        return goodsNewsCategoryService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(companyWechatIds), GoodsNewsCategory::getCompanyWechatId, companyWechatIds)
                .orderByAsc(GoodsNewsCategory::getSortNum)
                .page(new Page<>(pageNum, pageSize));
    }

    /**
     * 添加新维度分类
     */
    public GoodsNewsCategory addGoodsNewsCategory(HttpServletRequest request, String mainTitle, String subTitle,Integer type,Integer sortNum) {

        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        String loginCompanyWechatId = adminUser.getCompanyWechatId();
        if (StringUtils.isBlank(loginCompanyWechatId)) {
            throw new RemoteServiceException("无添加新维度分类权限");
        }
        if (goodsNewsCategoryService.lambdaQuery()
                .eq(GoodsNewsCategory::getCompanyWechatId,adminUser.getCompanyWechatId())
                .eq(sortNum !=null,GoodsNewsCategory::getSortNum,sortNum).count() > 0)
            throw new RemoteServiceException("排序重复，请修改");

        GoodsNewsCategory goodsNewsCategory = new GoodsNewsCategory();
        goodsNewsCategory.setMainTitle(mainTitle);
        goodsNewsCategory.setSubTitle(subTitle);
        goodsNewsCategory.setType(type);
        goodsNewsCategory.setCreateBy(adminUser.getAdminUserId());
        goodsNewsCategory.setCompanyWechatId(loginCompanyWechatId);
        goodsNewsCategory.setCompanyName(adminUser.getCompanyName());
        goodsNewsCategory.setSortNum(sortNum);
        goodsNewsCategory.insert();

        return goodsNewsCategory;

    }


    /**
     * 编辑新维度分类
     */
    @Transactional(rollbackFor = Exception.class)
    public void vimGoodsNewsCategory(HttpServletRequest request, GoodsNewsCategoryVimBean reqDto) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        String loginCompanyWechatId = adminUser.getCompanyWechatId();
        if (StringUtils.isBlank(loginCompanyWechatId)) {
            throw new RemoteServiceException("无编辑新维度分类权限");
        }
        String goodsNewsCategoryId = reqDto.getGoodsNewsCategoryId();
        if (StringUtils.isBlank(goodsNewsCategoryId)) {
            throw new RemoteServiceException("无效新维度分类");
        }
        if (reqDto.getSortNum()!= null && goodsNewsCategoryService.lambdaQuery()
                .eq(GoodsNewsCategory::getCompanyWechatId,adminUser.getCompanyWechatId())
                .eq(reqDto.getSortNum() !=null,GoodsNewsCategory::getSortNum,reqDto.getSortNum())
                .ne(GoodsNewsCategory::getGoodsNewsCategoryId,reqDto.getGoodsNewsCategoryId()).count() > 0)
            throw new RemoteServiceException("排序重复，请修改");

        //清除原先所有关系
 /*       initGoodsNewsCategory(goodsNewsCategoryId, loginCompanyWechatId, GoodsNewsCategoryGoodsTypeEnum.news.getCode());*/

        //更新新维度分类
        reqDto.updateById();

        //添加商品
 /*       addNewsCategoryGoods(goodsNewsCategoryId, loginCompanyWechatId, adminUser.getCompanyName(),
                GoodsNewsCategoryGoodsTypeEnum.news.getCode(), reqDto.getGoodsList());*/
    }

    /**
     * 添加活动商品
     */
    public void addActiveGoods(HttpServletRequest request, ActiveGoodsAddReqBean activeGoodsAddReqBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        String loginCompanyWechatId = adminUser.getCompanyWechatId();
        if (StringUtils.isBlank(loginCompanyWechatId)) {
            throw new RemoteServiceException("无编辑权限");
        }
        //初始化活动商品
        initGoodsNewsCategory(activeGoodsAddReqBean.getObjectId(), loginCompanyWechatId, activeGoodsAddReqBean.getType());

        //添加活动商品
        addNewsCategoryGoods(activeGoodsAddReqBean.getObjectId(), loginCompanyWechatId, adminUser.getCompanyName(),
                activeGoodsAddReqBean.getType(), activeGoodsAddReqBean.getGoodsList()
               );
    }

    /**
     * 添加分类商品  1=新维度分类，2=首页弹窗， 3=活动专区1，4=活动专区2左侧，5=活动专区2右侧，6=专场专区1，7=专场专区2 ， 8=专场专区3 ， 9=专场专区4
     */
    public void addNewsCategoryGoods(String objectId, String companyWechatId, String companyName,
                                     Integer type, List<Goods> goodsList) {

        //添加新维度分类的商品
        if (!CollectionUtils.isNotEmpty(goodsList))
            return;

        //添加新维度分类的商品
        List<GoodsNewsCategoryGoods> newsCategoryGoodsList = new ArrayList<>();
        for (Goods goods : goodsList) {
            GoodsNewsCategoryGoods goodsNewsCategoryGoods = new GoodsNewsCategoryGoods();
            newsCategoryGoodsList.add(goodsNewsCategoryGoods);

            goodsNewsCategoryGoods.setObjId(objectId);
            goodsNewsCategoryGoods.setType(type);
            goodsNewsCategoryGoods.setGoodsId(goods.getGoodsId());
            goodsNewsCategoryGoods.setGoodsName(goods.getGoodsName());
            goodsNewsCategoryGoods.setCompanyWechatId(companyWechatId);
            goodsNewsCategoryGoods.setCompanyName(companyName);
            goodsNewsCategoryGoods.setCreateTime(new Date());

        }
        goodsNewsCategoryGoodsService.saveBatch(newsCategoryGoodsList);

    }

    /**
     * 初始化分类商品  1=新维度分类，2=首页弹窗， 3=活动专区1，4=活动专区2左侧，5=活动专区2右侧，6=专场专区1，7=专场专区2 ， 8=专场专区3 ， 9=专场专区4
     */
    private void initGoodsNewsCategory(String objecId, String companyWechatId, Integer type) {

        List<GoodsNewsCategoryGoods> list = goodsNewsCategoryGoodsService.lambdaQuery()
                .select(GoodsNewsCategoryGoods::getGoodsNewsCategoryGoodsId)
                .eq(GoodsNewsCategoryGoods::getCompanyWechatId, companyWechatId)
                .eq(GoodsNewsCategoryGoods::getObjId, objecId)
                .eq(GoodsNewsCategoryGoods::getType, type)
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        List<String> newsCategoryGoodsIdList = list.stream().map(GoodsNewsCategoryGoods::getGoodsNewsCategoryGoodsId).collect(Collectors.toList());

        //删除与新维度分类商品
        goodsNewsCategoryGoodsService.lambdaUpdate()
                .in(GoodsNewsCategoryGoods::getGoodsNewsCategoryGoodsId, newsCategoryGoodsIdList)
                .remove();

    }


    /**
     * 新维度分类详情
     */
    public GoodsNewsCategoryDetailBean detail(String newsCategoryId) {
        GoodsNewsCategoryDetailBean respDto = new GoodsNewsCategoryDetailBean();
        String allTag = null;

        GoodsNewsCategory byId = goodsNewsCategoryService.getById(newsCategoryId);
        if (byId == null) {
            return respDto;
        }
        BeanUtils.copyProperties(byId, respDto);

        GoodsActiveDetail goodsActiveDetail = getGoodsActiveDetail(byId.getGoodsNewsCategoryId(), GoodsNewsCategoryGoodsTypeEnum.news.getCode());
        respDto.setGoodsList(goodsActiveDetail.getActiveGoodsList());
        return respDto;

    }

    /**
     * 获取活动商品详情 1=新维度分类，2=首页弹窗， 3=活动专区1，4=活动专区2左侧，5=活动专区2右侧，6=专场专区1，7=专场专区2 ， 8=专场专区3 ， 9=专场专区4
     */
    public GoodsActiveDetail getGoodsActiveDetail(String objectId, Integer type) {

        //活动商品
        List<GoodsNewsCategoryGoods> list = goodsNewsCategoryGoodsService.lambdaQuery()
                .eq(GoodsNewsCategoryGoods::getObjId, objectId)
                .eq(GoodsNewsCategoryGoods::getType, type)
                .list();


        List<GoodsNewsCategoryGoodsDetailBean> respNewsCategoryGoodsList = new ArrayList<>();
        for (GoodsNewsCategoryGoods newsCategoryGoods : list
        ) {
            GoodsNewsCategoryGoodsDetailBean respNewsCategoryGood = new GoodsNewsCategoryGoodsDetailBean();
            BeanUtils.copyProperties(newsCategoryGoods, respNewsCategoryGood);
            respNewsCategoryGoodsList.add(respNewsCategoryGood);

            //商品
            Goods goods = goodsService.getById(newsCategoryGoods.getGoodsId());
            respNewsCategoryGood.setGoods(goods);

            //商品规格
            List<GoodsSpec> goodsSpecList = goodsSpecService.lambdaQuery().eq(GoodsSpec::getGoodsId, newsCategoryGoods.getGoodsId()).list();
            respNewsCategoryGood.setGoodsSpecs(goodsSpecList);

        }

        GoodsActiveDetail goodsActiveDetail = new GoodsActiveDetail();
        goodsActiveDetail.setActiveGoodsList(respNewsCategoryGoodsList);
        return goodsActiveDetail;
    }

    @Transactional(rollbackFor = Exception.class)
    public void editStatus(String goodsNewsCategoryId, Boolean status, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        String loginCompanyWechatId = adminUser.getCompanyWechatId();
        GoodsNewsCategoryVimBean goodsNewsCategoryVimBean = new GoodsNewsCategoryVimBean();
        goodsNewsCategoryVimBean.setGoodsNewsCategoryId(goodsNewsCategoryId);
        goodsNewsCategoryVimBean.setStatus(status);

        if (StringUtils.isBlank(loginCompanyWechatId)) {
            throw new RemoteServiceException("无编辑新维度分类权限");
        }
        if (StringUtils.isBlank(goodsNewsCategoryId)) {
            throw new RemoteServiceException("无效新维度分类");
        }

        //更新新维度分类
        goodsNewsCategoryVimBean.updateById();
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(String goodsNewsCategoryId, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        String loginCompanyWechatId = adminUser.getCompanyWechatId();
        if (StringUtils.isBlank(loginCompanyWechatId)) {
            throw new RemoteServiceException("无编辑新维度分类权限");
        }
        if (StringUtils.isBlank(goodsNewsCategoryId)) {
            throw new RemoteServiceException("无效新维度分类");
        }
        //清除原先所有关系
        initGoodsNewsCategory(goodsNewsCategoryId, loginCompanyWechatId, GoodsNewsCategoryGoodsTypeEnum.news.getCode());

        GoodsNewsCategoryVimBean goodsNewsCategoryVimBean = new GoodsNewsCategoryVimBean();
        goodsNewsCategoryVimBean.setGoodsNewsCategoryId(goodsNewsCategoryId);
        //删除新维度分类
        goodsNewsCategoryVimBean.deleteById();
    }

    public IPage<GoodsNewsCategoryVO> pageV2(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();

        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean, GoodsNewsCategoryVO.class);
        IPage<GoodsNewsCategoryVO> carouselMapVOIPage = commonPageV2Mapper.pageV2GoodsNewsCategory(new Page(zfireParamBean.getPageNum(),
                        zfireParamBean.getPageSize()),
                zfireParam
                , companyWechatIds);

        return carouselMapVOIPage;

    }
}
