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

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.admin.AdminUserCom;
import com.gree.mall.manager.bean.template.TemplateBean;
import com.gree.mall.manager.bean.template.TemplateDetailBean;
import com.gree.mall.manager.commonmapper.CustomGoodsMapper;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.goods.GoodsLogic;
import com.gree.mall.manager.plus.entity.CommonTemplate;
import com.gree.mall.manager.plus.entity.GoodsTemplate;
import com.gree.mall.manager.plus.entity.PubTemplate;
import com.gree.mall.manager.plus.service.CommonTemplateService;
import com.gree.mall.manager.plus.service.GoodsTemplateService;
import com.gree.mall.manager.plus.service.PubTemplateService;
import com.gree.mall.manager.utils.DateUtils;
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.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TemplateLogic {
    @Autowired
    private CommonTemplateService commonTemplateService;
    @Autowired
    private CustomGoodsMapper customGoodsMapper;
    @Autowired
    private PubTemplateService pubTemplateService;
    @Autowired
    private GoodsTemplateService goodsTemplateService;
    @Autowired
    private CommonLogic commonLogic;
    @Autowired
    GoodsLogic goodsLogic;


    public IPage<CommonTemplate> list(Integer type,Integer pageNum, Integer pageSize, HttpServletRequest request) {
        if(type == null){
            type = 1;
        }
        //获取当前登录企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyIds = adminUser.getAdminCompanyIds();

        return commonTemplateService.lambdaQuery()
                .orderByAsc(CommonTemplate::getCommonTemplateId)
                .orderByDesc(CommonTemplate::getCreateTime)
                .eq(CommonTemplate::getType,type)
              //  .in(CollectionUtils.isNotEmpty(companyWechatIds), CommonTemplate::getCompanyWechatId, companyWechatIds)
                .page(new Page<>(pageNum, pageSize));
    }

    @Transactional
    public String save(TemplateBean templateBean, HttpServletRequest request) throws ParseException {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        if(templateBean.getType() == null){
            templateBean.setType(1);
        }
        CommonTemplate commonTemplate = new CommonTemplate();
        commonTemplate.setContent(templateBean.getContent());
        commonTemplate.setName(templateBean.getName());
        commonTemplate.setCreateTime(new Date());
        commonTemplate.setType(templateBean.getType());

        commonTemplate.setLogo(templateBean.getLogo());
        if(templateBean.getLogoStartTime() != null) {
            commonTemplate.setLogoStartTime(DateUtils.parseDate(templateBean.getLogoStartTime()));
        }
        if(templateBean.getLogoEndTime() != null) {
            commonTemplate.setLogoEndTime(DateUtils.parseDate(templateBean.getLogoEndTime()));
        }
        commonTemplateService.save(commonTemplate);
        if (templateBean.getGoodsIds() == null || templateBean.getGoodsIds().size() < 1) {
            return commonTemplate.getCommonTemplateId();
        }
        List<GoodsTemplate> goodsTemplateList = new ArrayList<>();
        for (String goodsId : templateBean.getGoodsIds()) {
            GoodsTemplate goodsTemplate = new GoodsTemplate();
            goodsTemplate.setGoodsId(goodsId);
            goodsTemplate.setTemplateId(commonTemplate.getCommonTemplateId());
            goodsTemplate.setCreateTime(new Date());
            goodsTemplateList.add(goodsTemplate);
        }
        goodsTemplateService.saveBatch(goodsTemplateList);

        //全量更新商品的logo
        if(templateBean.getType() != null && templateBean.getType() == 2){
            goodsLogic.updateGoodsLogo(templateBean.getGoodsIds(),templateBean.getLogo(),templateBean.getLogoStartTime(),templateBean.getLogoEndTime(), true);
        }

        return commonTemplate.getCommonTemplateId();
    }

    public String updatePub(PubTemplate templateBean, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);


        PubTemplate pubTemplate = new PubTemplate();
        pubTemplate.setPubTemplateId(null);
        pubTemplate.setContent(templateBean.getContent());
        pubTemplate.setName("公共模块");
        pubTemplate.setCreateTime(new Date());
        pubTemplateService.saveOrUpdate(pubTemplate);
        return pubTemplate.getPubTemplateId();
    }

    public PubTemplate queryPub(HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        return pubTemplateService.lambdaQuery()
                //.in(CollectionUtils.isNotEmpty(adminUser.getAdminCompanyIds()),PubTemplate::getCompanyWechatId,adminUser.getAdminCompanyIds())
                .one();
    }

    @Transactional
    public String update(TemplateBean templateBean, HttpServletRequest request) throws ParseException {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);


        final CommonTemplate oldTemplate = commonTemplateService.getById(templateBean.getCommonTemplateId());

        commonTemplateService.lambdaUpdate()
                .eq(CommonTemplate::getCommonTemplateId, templateBean.getCommonTemplateId())
                .set(CommonTemplate::getContent, templateBean.getContent())
                .set(CommonTemplate::getName, templateBean.getName())
                .set(CommonTemplate::getType,templateBean.getType())
                .set(CommonTemplate::getUpdateTime, new Date())
                .set(CommonTemplate::getLogo,templateBean.getLogo())
                .set(CommonTemplate::getLogoStartTime,templateBean.getLogoStartTime())
                .set(CommonTemplate::getLogoEndTime,templateBean.getLogoEndTime())
                .update();
        if (templateBean.getGoodsIds() == null || templateBean.getGoodsIds().size() < 1) {
            return templateBean.getCommonTemplateId();
        }

        List<GoodsTemplate> oldTemplateList = new ArrayList<>();
        if (Objects.nonNull(templateBean.getType()) && templateBean.getType() == 2) {
            oldTemplateList = goodsTemplateService.lambdaQuery()
                    .select(GoodsTemplate::getGoodsId)
                    .eq(GoodsTemplate::getTemplateId, templateBean.getCommonTemplateId())
                    .list();
        }
        goodsTemplateService.lambdaUpdate()
                .eq(GoodsTemplate::getTemplateId, templateBean.getCommonTemplateId())
                .remove();

        List<GoodsTemplate> goodsTemplateList = new ArrayList<>();
        for (String goodsId : templateBean.getGoodsIds()) {
            GoodsTemplate goodsTemplate = new GoodsTemplate();
            goodsTemplate.setGoodsId(goodsId);
            goodsTemplate.setTemplateId(templateBean.getCommonTemplateId());
            goodsTemplate.setCreateTime(new Date());
            goodsTemplateList.add(goodsTemplate);
        }
        goodsTemplateService.saveBatch(goodsTemplateList);

        //全量更新商品的logo
        if(templateBean.getType() != null && templateBean.getType() == 2){
            // 旧历史不为空查出需要移除水印信息的商品id
            if (CollectionUtils.isNotEmpty(oldTemplateList)) {

                final List<String> oldGoodsIds = oldTemplateList.stream().map(GoodsTemplate::getGoodsId).collect(Collectors.toList());
                List<String> clearGoodsIds = new ArrayList();
                for (String oldGoodsId : oldGoodsIds) {
                    if (!templateBean.getGoodsIds().contains(oldGoodsId)) {
                        clearGoodsIds.add(oldGoodsId);
                    }
                }
                if (CollectionUtils.isNotEmpty(clearGoodsIds)) {
                    goodsLogic.updateGoodsLogo(clearGoodsIds, null, null, null, true);
                }
            }
            goodsLogic.updateGoodsLogo(templateBean.getGoodsIds(), templateBean.getLogo(), templateBean.getLogoStartTime(), templateBean.getLogoEndTime(), oldTemplate.getLogo().equals(templateBean.getLogo()));
        }

        return templateBean.getCommonTemplateId();
    }

    public String delete(String commonTemplateId) {
        commonTemplateService.removeById(commonTemplateId);
        goodsTemplateService.lambdaUpdate().eq(GoodsTemplate::getTemplateId, commonTemplateId).remove();
        return commonTemplateId;
    }

    public TemplateDetailBean detail(String commonTemplateId) {
        CommonTemplate commonTemplate = commonTemplateService.getById(commonTemplateId);
        TemplateDetailBean templateDetailBean = new TemplateDetailBean();
        BeanUtils.copyProperties(commonTemplate, templateDetailBean);
        templateDetailBean.setGoodsList(customGoodsMapper.list(commonTemplateId));
        return templateDetailBean;
    }


}
