package com.ai.da.service.impl;

import com.ai.da.common.config.exception.BusinessException;
import com.ai.da.common.enums.CollectionLevel1TypeEnum;
import com.ai.da.common.enums.DesignTypeEnum;
import com.ai.da.common.utils.CopyUtil;
import com.ai.da.common.utils.DateUtil;
import com.ai.da.common.utils.MinioUtil;
import com.ai.da.mapper.primary.CollectionMapper;
import com.ai.da.mapper.primary.entity.Collection;
import com.ai.da.mapper.primary.entity.CollectionElement;
import com.ai.da.model.vo.CollectionColorVO;
import com.ai.da.model.vo.CollectionElementVO;
import com.ai.da.model.vo.UserLikeCollectionVO;
import com.ai.da.service.CollectionElementService;
import com.ai.da.service.CollectionService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author yanglei
 * @since 2022-09-30
 */
@Slf4j
@Service
public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, Collection> implements CollectionService {
    @Resource
    private CollectionMapper collectionMapper;
    @Resource
    private CollectionElementService collectionElementService;
    @Resource
    private MinioUtil minioUtil;

    @Transactional
    @Override
    public Long saveCollection(Long accountId, String timeZone, String moodTemplateId) {
        Collection collection = new Collection();
        collection.setAccountId(accountId);
        collection.setCreateDate(DateUtil.getByTimeZone(timeZone));
        collection.setMoodTemplateId(moodTemplateId);
        if (collectionMapper.insert(collection) <= 0) {
            throw new BusinessException("save.collection.failed");
        }
        return collection.getId();
    }

    @Override
    public Collection findById(Long id) {
        return collectionMapper.selectById(id);
    }

    @Override
    public UserLikeCollectionVO chooseCollection(Long id) {
        UserLikeCollectionVO response = new UserLikeCollectionVO();
        Collection collection = getById(id);
        if (Objects.isNull(collection)) {
            throw new BusinessException("collection.not.found");
        }
        List<CollectionElement> collectionElements = collectionElementService.getByCollectionId(id);
        if (CollectionUtils.isEmpty(collectionElements)) {
            throw new BusinessException("collectionElements.not.found");
        }
        response.setCollectionId(id);
        response.setMoodTemplateId(collection.getMoodTemplateId());
        if (collection.getMoodTemplateId() != null) {
            CollectionElement byId = collectionElementService.getById(response.getMoodTemplateId());
            if (Objects.nonNull(byId)) {
                response.setMoodTemplateName(byId.getName());
                response.setMoodTemplateUrl(minioUtil.getPresignedUrl(byId.getUrl(), 24 * 60));
            }
        }
        Map<String, List<CollectionElement>> maps = collectionElements
                .stream()
                .collect(Collectors.groupingBy(CollectionElement::getLevel1Type));
        maps.forEach((k, v) -> {
            CollectionLevel1TypeEnum level1TypeEnum = CollectionLevel1TypeEnum.uploadOf(k);
            if (Objects.isNull(level1TypeEnum)) {
                throw new BusinessException("unknown.level1TypeEnum");
            }
            switch (level1TypeEnum) {
                case MOOD_BOARD:
                    response.setMoodBoards(CopyUtil.copyList(v, CollectionElementVO.class, (o, d) -> {
                        d.setDesignType(DesignTypeEnum.COLLECTION.getRealName());
                        d.setUrl(minioUtil.getPresignedUrl(o.getUrl(), 24 * 60));
                    }));
                    break;
                case PRINT_BOARD:
                    response.setPrintBoards(CopyUtil.copyList(v, CollectionElementVO.class, (o, d) -> {
                        d.setIsPin(o.getHasPin());
                        d.setDesignType(DesignTypeEnum.COLLECTION.getRealName());
                        d.setUrl(minioUtil.getPresignedUrl(o.getUrl(), 24 * 60));
                    }));
                    break;
                case SKETCH_BOARD:
                    response.setSketchBoards(CopyUtil.copyList(v, CollectionElementVO.class, (o, d) -> {
                        d.setIsPin(o.getHasPin());
                        d.setDesignType(DesignTypeEnum.COLLECTION.getRealName());
                        d.setUrl(minioUtil.getPresignedUrl(o.getUrl(), 24 * 60));
                        String url = o.getUrl();
                        if (url.contains(".")) {
                            String[] split = url.split("\\.");
                            d.setUrlWithWhiteSide(minioUtil.getPresignedUrl(split[0] + "-show." + split[1], 24 * 60));
                        }else {
                            d.setUrlWithWhiteSide(minioUtil.getPresignedUrl(url + "-show", 24 * 60));
                        }
                    }));
                    break;
                case COLOR_BOARD:
                    response.setColorBoards(resolveColorBoard(v));
                    break;
                case MARKETING_SKETCH:
                    response.setMarketingSketchs(CopyUtil.copyList(v, CollectionElementVO.class, (o, d) -> {
                        d.setDesignType(DesignTypeEnum.COLLECTION.getRealName());
                    }));
                    break;
                default:
            }
        });
        return response;
    }

    private List<CollectionColorVO> resolveColorBoard(List<CollectionElement> collectionElements) {
        return CopyUtil.copyList(collectionElements, CollectionColorVO.class, (o, d) -> {
            String name = o.getName();
            if (StringUtils.isBlank(name)) {
                d.setId(null);
                d.setName(null);
            } else {
                String[] idName = name.split("_");
                if (idName.length > 1) {
                    if (idName[0].equals("null")) {
                        d.setId(null);
                    }else {
                        d.setId(StringUtil.isNullOrEmpty(idName[0]) ? null : Integer.valueOf(idName[0]));
                    }
                    d.setName(idName[1]);
                    d.setTcx(idName[2]);
                }
            }
            d.setRgbValue(o.getColorRgb());
        });
    }
}
