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.CommonTemplateVO;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.carouselMap.CarouselMapVO;
import com.gree.mall.manager.bean.template.TemplateBean;
import com.gree.mall.manager.bean.template.TemplateDetailBean;
import com.gree.mall.manager.commonmapper.CommonPageV2Mapper;
import com.gree.mall.manager.commonmapper.CustomGoodsMapper;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.exception.RemoteServiceException;
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.DateUtil;
import com.gree.mall.manager.utils.DateUtils;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
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;
    @Autowired
    CommonPageV2Mapper commonPageV2Mapper;


    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> companyWechatIds = adminUser.getCompanyWechatIds();

        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 (StringUtils.isBlank(adminUser.getCompanyWechatId())) {
            throw new RemoteServiceException("非租户账号不可操作当前信息");
        }

        CommonTemplate commonTemplate = new CommonTemplate();
        commonTemplate.setContent(templateBean.getContent());
        commonTemplate.setName(templateBean.getName());
        commonTemplate.setCreateTime(new Date());
        commonTemplate.setType(templateBean.getType());
        commonTemplate.setCompanyWechatId(adminUser.getCompanyWechatId());
        commonTemplate.setCompanyName(adminUser.getCompanyName());
        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());
            goodsTemplate.setCompanyWechatId(adminUser.getCompanyWechatId());
            goodsTemplate.setCompanyName(adminUser.getCompanyName());
            goodsTemplateList.add(goodsTemplate);
        }
        goodsTemplateService.saveBatch(goodsTemplateList);

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

        return commonTemplate.getCommonTemplateId();
    }

    public String updatePub(PubTemplate templateBean, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        if (StringUtils.isBlank(adminUser.getCompanyWechatId())) {
            throw new RemoteServiceException("非租户账号不可操作当前信息");
        }

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

    public PubTemplate queryPub(HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        if (StringUtils.isBlank(adminUser.getCompanyWechatId())) {
            throw new RemoteServiceException("非租户账号不可操作当前信息");
        }

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

    @Transactional
    public String update(TemplateBean templateBean, HttpServletRequest request) throws ParseException {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        if (StringUtils.isBlank(adminUser.getCompanyWechatId())) {
            throw new RemoteServiceException("非租户账号不可操作当前信息");
        }

        commonTemplateService.lambdaUpdate()
                .eq(CommonTemplate::getCommonTemplateId, templateBean.getCommonTemplateId())
                .set(templateBean.getContent() != null,CommonTemplate::getContent, templateBean.getContent())
                .set(templateBean.getName() != null,CommonTemplate::getName, templateBean.getName())
                .set(CommonTemplate::getUpdateTime, new Date())
                .set(templateBean.getLogo() != null,CommonTemplate::getLogo,templateBean.getLogo())
                .set(templateBean.getLogoStartTime() != null,CommonTemplate::getLogoStartTime,templateBean.getLogoStartTime())
                .set(templateBean.getLogoEndTime() != null,CommonTemplate::getLogoEndTime,templateBean.getLogoEndTime())
                .update();
        if (templateBean.getGoodsIds() == null || templateBean.getGoodsIds().size() < 1) {
            return templateBean.getCommonTemplateId();
        }
        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());
            goodsTemplate.setCompanyWechatId(adminUser.getCompanyWechatId());
            goodsTemplate.setCompanyName(adminUser.getCompanyName());
            goodsTemplateList.add(goodsTemplate);
        }
        goodsTemplateService.saveBatch(goodsTemplateList);

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

        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;
    }


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

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

        return carouselMapVOIPage;
    }
}
