package com.cool.store.service.impl;

import com.cool.store.context.CurrentUserHolder;
import com.cool.store.dto.label.LabelAddDTO;
import com.cool.store.dto.label.LabelDeleteDTO;
import com.cool.store.dto.label.LabelListDTO;
import com.cool.store.dto.label.LabelUpdateDTO;
import com.cool.store.entity.HyPartnerLabelDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.exception.ApiException;
import com.cool.store.mapper.HyPartnerLabelMapper;
import com.cool.store.service.LabelService;
import com.cool.store.vo.LabelGroupVO;
import com.cool.store.vo.LabelListVo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Fun Li 2023/8/10 14:24
 * @version 1.0
 */
@Service
@Slf4j
public class LabelServiceImpl implements LabelService {

    @Autowired
    private HyPartnerLabelMapper labelMapper;



    @Value("${ec.sync.createUserId:null}")
    private String createUserId;

    /**
     * 获取数组列表
     *
     * @param dto 查询条件
     */
    @Override
    public List<LabelListVo> getLabelList(LabelListDTO dto) {
        return labelMapper.getLabelList(dto);
    }

    /**
     * 添加标签组
     * @param dto 新增标签组信息
     */
    @Override
    public void addLabel(LabelAddDTO dto) throws ApiException {
        HyPartnerLabelDO labelDO = new HyPartnerLabelDO();
        labelDO.setLabelName(dto.getLabelName());
        if (whetherLabelRepeat(labelDO)) {
            throw new ApiException(ErrorCodeEnum.LABEL_EXIST);
        }
        String userId = CurrentUserHolder.getUserId();
        labelDO.setLabelGroupId(dto.getLabelGroupId());
        labelDO.setEditUserId(userId);
        labelDO.setEditDate(new Date());
        labelDO.setCreateUserId(userId);
        labelDO.setUpdateUserId(userId);
        labelMapper.insertSelective(labelDO);
    }

    /**
     * 修改标签信息
     * @param dto 新标签信息
     */
    @Override
    public void updateLabel(LabelUpdateDTO dto) throws ApiException {
        HyPartnerLabelDO labelDO = new HyPartnerLabelDO();
        labelDO.setId(dto.getId());
        labelDO.setLabelName(dto.getLabelName());
        if (whetherLabelRepeat(labelDO)) {
            throw new ApiException(ErrorCodeEnum.LABEL_EXIST);
        }
        String userId = CurrentUserHolder.getUserId();
        labelDO.setLabelGroupId(dto.getLabelGroupId());
        labelDO.setEditUserId(userId);
        labelDO.setEditDate(new Date());
        labelDO.setUpdateUserId(userId);
        labelMapper.updateByPrimaryKeySelective(labelDO);
    }

    /**
     * 删除标签
     * @param dto
     */
    @Override
    public void deleteLabel(LabelDeleteDTO dto) {
        HyPartnerLabelDO labelDO = new HyPartnerLabelDO();
        String userId = CurrentUserHolder.getUserId();
        labelDO.setId(dto.getId());
        labelDO.setEditUserId(userId);
        labelDO.setEditDate(new Date());
        labelDO.setUpdateUserId(userId);
        labelDO.setDeleted(Boolean.TRUE);
        labelMapper.updateByPrimaryKeySelective(labelDO);
    }

    @Override
    public HyPartnerLabelDO selectByPrimaryKey(Long classId) {
        return labelMapper.selectByPrimaryKey(classId);
    }

    @Override
    public void addEcLabel(HyPartnerLabelDO hyPartnerLabelDO) {
        hyPartnerLabelDO.setEditDate(new Date()).setCreateTime(new Date()).setEditUserId(createUserId).setCreateUserId(createUserId)
                        .setUpdateUserId(createUserId);
        labelMapper.insertSelective(hyPartnerLabelDO);
    }

    @Override
    public List<LabelGroupVO> getAllGroupAndLabelList() {
        List<LabelListVo> labelList = labelMapper.getLabelList(new LabelListDTO());
        if (CollectionUtils.isEmpty(labelList)) {
            log.info("标签列表为空");
            return Lists.newArrayList(new LabelGroupVO());
        }
        Map<Long, List<LabelListVo>> idForVo = labelList.stream().collect(Collectors.groupingBy(LabelListVo::getLabelGroupId));
        List<LabelGroupVO> result = idForVo.entrySet().stream().map(entry -> {
            LabelGroupVO vo = new LabelGroupVO();
            vo.setId(entry.getKey());
            vo.setLabelGroupName(entry.getValue().get(0).getLabelGroupName());
            vo.setGroupCreateTime(entry.getValue().get(0).getGroupCreateTime());
            List<LabelGroupVO.LabelVO> labelList1 = entry.getValue().stream().map(label -> {
                LabelGroupVO.LabelVO labelVO = new LabelGroupVO.LabelVO();
                labelVO.setId(label.getId());
                labelVO.setLabelName(label.getLabelName());
                labelVO.setLabelCreateTime(label.getLabelCreateTime());
                return labelVO;
            }).sorted(Comparator.comparing(LabelGroupVO.LabelVO::getLabelCreateTime))
                    .collect(Collectors.toList());
            vo.setLabelList(labelList1);
            return vo;
        }).sorted(Comparator.comparing(LabelGroupVO::getGroupCreateTime).thenComparing(LabelGroupVO::getId)).collect(Collectors.toList());
        return result;
    }

    private Boolean whetherLabelRepeat(HyPartnerLabelDO label) throws ApiException {
        Long id = label.getId();
        label.setId(null);
        List<HyPartnerLabelDO> hyPartnerLabelDOS = labelMapper.selectSelective(label);
        label.setId(id);
        //如果修改后的标签名与原标签名一致也不算重复，但是要记录更新人
        if (hyPartnerLabelDOS != null && hyPartnerLabelDOS.size() > 0) {
            //更新操作还要检查是否与原标签信息相同，相同的话也不算重复
            if (hyPartnerLabelDOS.get(0).getId().equals(id)) {
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Override
    public Map<Long,String> getUserPortraitMap(List<String> userPortraitStrList){
        if(CollectionUtils.isEmpty(userPortraitStrList)){
            return Maps.newHashMap();
        }
        Set<Long> userPortraitIdList = new HashSet<>();
        for (String userPortrait:userPortraitStrList) {
            if(StringUtils.isBlank(userPortrait)){
                continue;
            }
            String[] parts = userPortrait.split(",");
            for (String part : parts) {
                String trimmedPart = part.trim();
                if (!trimmedPart.isEmpty()) {
                    try {
                        Long value = Long.parseLong(trimmedPart);
                        userPortraitIdList.add(value);
                    } catch (NumberFormatException e) {
                        log.info("Invalid format: {}" , trimmedPart);
                    }
                }
            }
        }
        List<HyPartnerLabelDO> labelListByIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(userPortraitIdList)){
            labelListByIds = labelMapper.getLabelListByIds(new ArrayList<>(userPortraitIdList));
        }
        return labelListByIds.stream().collect(Collectors.toMap(HyPartnerLabelDO::getId,HyPartnerLabelDO::getLabelName));
    }

    @Override
    public List<String> getUserPortraitList(Map<Long, String> userPortraitMap, String userPortraitStr) {
        List<String> userPortraitList= new ArrayList<>();
        if(StringUtils.isNotEmpty(userPortraitStr)){
            String[] parts = userPortraitStr.split(",");
            for (String part : parts) {
                String trimmedPart = part.trim();
                if (!trimmedPart.isEmpty()) {
                    try {
                        if (userPortraitMap.get(Long.valueOf(part)) != null){
                            userPortraitList.add(userPortraitMap.get(Long.valueOf(part)));
                        }
                    } catch (NumberFormatException e) {
                        log.info("Invalid format: {}" , trimmedPart);
                    }
                }
            }
        }
        return userPortraitList;
    }
}
