package cn.com.poc.agent_application.rest.impl;

import cn.com.poc.agent_application.aggregate.AgentApplicationMallService;
import cn.com.poc.agent_application.convert.BizAgentApplicationMallConvert;
import cn.com.poc.agent_application.dto.AgentApplicationMallCategoryDto;
import cn.com.poc.agent_application.dto.AgentApplicationMallInfoDto;
import cn.com.poc.agent_application.dto.AgentApplicationMallQueryDto;
import cn.com.poc.agent_application.dto.BizAgentApplicationMallDto;
import cn.com.poc.agent_application.entity.BizAgentApplicationCategoryEntity;
import cn.com.poc.agent_application.entity.BizAgentApplicationMallEntity;
import cn.com.poc.agent_application.entity.BizAgentApplicationPublishEntity;
import cn.com.poc.agent_application.entity.BizMemberAgentApplicationCollectEntity;
import cn.com.poc.agent_application.query.MallAgentApplicationQueryCondition;
import cn.com.poc.agent_application.query.MallAgentApplicationQueryItem;
import cn.com.poc.agent_application.query.MemberCollectQueryCondition;
import cn.com.poc.agent_application.query.MemberCollectQueryItem;
import cn.com.poc.agent_application.rest.BizAgentApplicationMallRest;
import cn.com.poc.agent_application.service.BizAgentApplicationCategoryService;
import cn.com.poc.agent_application.service.BizAgentApplicationMallService;
import cn.com.poc.agent_application.service.BizAgentApplicationPublishService;
import cn.com.poc.agent_application.service.BizMemberAgentApplicationCollectService;
import cn.com.poc.common.annotation.RedisLimit;
import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.constant.XLangConstant;
import cn.com.poc.common.utils.BlContext;
import cn.com.poc.common.utils.StringUtils;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import cn.com.yict.framemax.data.model.PagingInfo;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class BizAgentApplicationMallRestImpl implements BizAgentApplicationMallRest {

    @Resource
    private AgentApplicationMallService agentApplicationMallService;

    @Resource
    private BizMemberAgentApplicationCollectService bizMemberAgentApplicationCollectService;


    @Resource
    private BizAgentApplicationPublishService bizAgentApplicationPublishService;

    @Resource
    private BizAgentApplicationMallService bizAgentApplicationMallService;

    @Resource
    private BizAgentApplicationCategoryService bizAgentApplicationCategoryService;


    @Override
    public void publishAgentToMall(BizAgentApplicationMallDto dto) throws Exception {
        Assert.notNull(dto);
        Assert.notNull(dto.getAgentPublishId());
        Assert.notNull(dto.getCategoryId());
        Assert.notNull(dto.getIsCopy());
        BizAgentApplicationPublishEntity publishEntity = bizAgentApplicationPublishService.get(dto.getAgentPublishId());
        if (publishEntity == null) {
            throw new I18nMessageException("exception/publication.failed");
        }
        dto.setIsSale(CommonConstant.IsDeleted.Y);
        // 判断当前应用之前是否上架了
        BizAgentApplicationMallEntity mallEntity = bizAgentApplicationMallService.getByAgentPublishId(dto.getAgentPublishId());


        // 查询当前应用的收藏情况
        BizMemberAgentApplicationCollectEntity collectEntity = new BizMemberAgentApplicationCollectEntity();
        collectEntity.setAgentId(publishEntity.getAgentId());
        collectEntity.setIsCollect(CommonConstant.YOrN.Y);
        collectEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizMemberAgentApplicationCollectEntity> collectEntities = bizMemberAgentApplicationCollectService.findByExample(collectEntity, null);

        if (mallEntity != null) {
            mallEntity.setIsSale(CommonConstant.IsDeleted.Y);
            mallEntity.setCategoryId(dto.getCategoryId());
            mallEntity.setIsCopy(dto.getIsCopy());
            mallEntity.setCollectNumber(collectEntities.size());
            // 如果上架过，则update操作
            bizAgentApplicationMallService.update(mallEntity);
        } else {
            // 如果没上架过，则save操作
            // 把应用存入应用市场表中
            dto.setCollectNumber(collectEntities.size());
            bizAgentApplicationMallService.save(BizAgentApplicationMallConvert.dtoToEntity(dto));
        }
    }

    public BizAgentApplicationMallDto getById(java.lang.Integer id) throws Exception {
        Assert.notNull(id);
        return BizAgentApplicationMallConvert.entityToDto(bizAgentApplicationMallService.get(id));
    }

    @Override
    public List<BizAgentApplicationMallDto> getListByExample(BizAgentApplicationMallDto example, PagingInfo pagingInfo) throws Exception {
        return null;
    }

    @Override
    public List<BizAgentApplicationMallDto> getList(AgentApplicationMallQueryDto dto, PagingInfo pagingInfo) throws Exception {
        List<BizAgentApplicationMallDto> resultList = new ArrayList<>();
        //查询应用广场的应用
        MallAgentApplicationQueryCondition mallAgentApplicationQueryCondition = new MallAgentApplicationQueryCondition();
        mallAgentApplicationQueryCondition.setIsSale(CommonConstant.YOrN.Y);
        if (dto != null) {
            if (StringUtils.isNotBlank(dto.getSearch())) {
                mallAgentApplicationQueryCondition.setQuery(dto.getSearch());
            }
            if (StringUtils.isNotBlank(dto.getAgentType())) {
                mallAgentApplicationQueryCondition.setAgentType(dto.getAgentType());
            }
            if (dto.getCategoryId() != null) {
                mallAgentApplicationQueryCondition.setCategoryId(dto.getCategoryId());
            }
        }
        List<MallAgentApplicationQueryItem> items = bizAgentApplicationMallService.mallAgentApplicationQuery(mallAgentApplicationQueryCondition, pagingInfo);

        //查询当前用户的收藏情况
        MemberCollectQueryCondition collectQueryCondition = new MemberCollectQueryCondition();
        collectQueryCondition.setMemberId(BlContext.getCurrentUserNotException().getUserId());
        collectQueryCondition.setIsCollect(CommonConstant.YOrN.Y);
        List<MemberCollectQueryItem> memberCollectQueryItems = bizMemberAgentApplicationCollectService.queryMemberCollect(collectQueryCondition, null);

        // 把查询结果封装到DTO中
        for (MallAgentApplicationQueryItem item : items) {
            BizAgentApplicationMallDto mallDto = BizAgentApplicationMallConvert.itemToDto(item);
            String agentId = mallDto.getBaseInfo().getAgentId();
            mallDto.setIsCollect(memberCollectQueryItems.stream().anyMatch(v -> agentId.equals(v.getAgentId())) ? CommonConstant.YOrN.Y : CommonConstant.YOrN.N);
            resultList.add(mallDto);
        }
        return resultList;
    }

    public BizAgentApplicationMallDto update(BizAgentApplicationMallDto dto) throws Exception {
        Assert.notNull(dto);
        BizAgentApplicationMallEntity entity = BizAgentApplicationMallConvert.dtoToEntity(dto);
        return BizAgentApplicationMallConvert.entityToDto(bizAgentApplicationMallService.update(entity));
    }

    public void deletedById(java.lang.Integer id) throws Exception {
        Assert.notNull(id);
        bizAgentApplicationMallService.deletedById(id);
    }

    @Override
    @RedisLimit(currentUser = true, key = "collect:agent", count = 1, timeout = 1, exceptionInfo = "exception/collect.limit.message")
    public void collectOrCancelAgentInMall(Integer id) throws Exception {
        Assert.notNull(id);
        agentApplicationMallService.collectOrCancelAgentInMall(id);
    }

    @Override
    public void unSaleAgentInMall(Integer agentPublishId) throws Exception {
        Assert.notNull(agentPublishId);
        BizAgentApplicationMallEntity mallEntity = bizAgentApplicationMallService.getByAgentPublishId(agentPublishId);
        mallEntity.setIsSale(CommonConstant.IsDeleted.N);
        bizAgentApplicationMallService.update(mallEntity);
    }

    @Override
    public List<AgentApplicationMallCategoryDto> getMallCategoryList(HttpServletRequest httpServletRequest) throws Exception {
        List<AgentApplicationMallCategoryDto> result = new ArrayList<>();
        String lang = httpServletRequest.getHeader("x-lang");
        if (StringUtils.isEmpty(lang)) {
            lang = XLangConstant.ZH_CN;
        }
        List<BizAgentApplicationCategoryEntity> bizAgentApplicationCategoryEntities = bizAgentApplicationCategoryService.findByExample(new BizAgentApplicationCategoryEntity(), null);
        for (BizAgentApplicationCategoryEntity entity : bizAgentApplicationCategoryEntities) {
            AgentApplicationMallCategoryDto dto = new AgentApplicationMallCategoryDto();
            switch (lang) {
                case XLangConstant.EN:
                    dto.setId(entity.getId());
                    dto.setCategoryName(entity.getCategoryEn());
                    result.add(dto);
                    break;
                case XLangConstant.ZH_CN:
                    dto.setId(entity.getId());
                    dto.setCategoryName(entity.getCategory());
                    result.add(dto);
                    break;
                case XLangConstant.ZH_TW:
                    dto.setId(entity.getId());
                    dto.setCategoryName(entity.getCategoryTw());
                    result.add(dto);
                    break;
                default:
                    throw new I18nMessageException("not support lang");
            }
        }
        return result;
    }

    @Override
    public AgentApplicationMallInfoDto getMallInfoByAgentId(String agentId) throws Exception {
        Assert.notNull(agentId);
        BizAgentApplicationMallEntity agentPublishInfo = agentApplicationMallService.getAgentPublishInfo(agentId);
        if (agentPublishInfo == null) {
            return null;
        }
        AgentApplicationMallInfoDto dto = BizAgentApplicationMallConvert.entityToInfoDto(agentPublishInfo);
        dto.setAgentId(agentId);
        return dto;
    }
}