package com.xinelu.manage.service.labelfieldinfo.impl;

import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.core.domain.entity.SysDictData;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.SecurityUtils;
import com.xinelu.manage.domain.labelfieldinfo.LabelFieldInfo;
import com.xinelu.manage.domain.taskpartitiondict.TaskPartitionDict;
import com.xinelu.manage.dto.labelfieldinfo.LabelFieldInfoAddDTO;
import com.xinelu.manage.mapper.labelfieldinfo.LabelFieldInfoMapper;
import com.xinelu.manage.mapper.taskpartitiondict.TaskPartitionDictMapper;
import com.xinelu.manage.mapper.tasktypedict.TaskTypeDictMapper;
import com.xinelu.manage.service.labelfieldinfo.ILabelFieldInfoService;
import com.xinelu.manage.vo.labelfieldinfo.LabelFieldTreeVO;
import com.xinelu.manage.vo.labelfieldinfo.LabelFieldVO;
import com.xinelu.manage.vo.tasktypedict.TaskTypeDictVO;
import com.xinelu.system.mapper.SysDictDataMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 标签字段信息Service业务层处理
 *
 * @author xinelu
 * @date 2024-03-11
 */
@Service
public class LabelFieldInfoServiceImpl implements ILabelFieldInfoService {
    @Resource
    private LabelFieldInfoMapper labelFieldInfoMapper;
    @Resource
    private TaskTypeDictMapper taskTypeDictMapper;
    @Resource
    private TaskPartitionDictMapper taskPartitionDictMapper;
    @Resource
    private SysDictDataMapper sysDictDataMapper;

    /**
     * 查询标签字段信息
     *
     * @param id 标签字段信息主键
     * @return 标签字段信息
     */
    @Override
    public LabelFieldInfo selectLabelFieldInfoById(Long id) {
        return labelFieldInfoMapper.selectLabelFieldInfoById(id);
    }

    /**
     * 查询标签字段信息列表
     *
     * @param labelFieldInfo 标签字段信息
     * @return 标签字段信息
     */
    @Override
    public List<LabelFieldInfo> selectLabelFieldInfoList(LabelFieldInfo labelFieldInfo) {
        List<LabelFieldInfo> labelFieldInfoList = labelFieldInfoMapper.selectLabelFieldInfoList(labelFieldInfo);
        List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataByType("field_type");
        for (LabelFieldInfo fieldInfo : labelFieldInfoList) {
            SysDictData sysDictData = sysDictDataList.stream().filter(Objects::nonNull).filter(item -> item.getDictValue().equals(fieldInfo.getFieldType())).findFirst().orElse(new SysDictData());
            if (StringUtils.isNotBlank(sysDictData.getDictLabel())) {
                fieldInfo.setFieldType(sysDictData.getDictLabel());
            }
        }
        return labelFieldInfoList;
    }

    /**
     * 查询标签字段信息列表树图
     *
     * @param fieldType 字段类型
     * @return AjaxResult
     */
    @Override
    public List<LabelFieldTreeVO> labelFieldList(Long taskPartitionDictId, String fieldType) {
        if (Objects.isNull(taskPartitionDictId)) {
            return new ArrayList<>();
        }
        int i = 1;
        //根据细分id查询细分标签
        List<LabelFieldVO> labelFieldList = labelFieldInfoMapper.selectLabelFieldList(taskPartitionDictId, fieldType);
        List<Long> taskPartitionDictIds = labelFieldList.stream().filter(Objects::nonNull).map(LabelFieldVO::getTaskPartitionDictId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        if (taskPartitionDictIds.size() == 0) {
            return new ArrayList<>();
        }
        List<LabelFieldVO> collect = labelFieldList.stream().filter(Objects::nonNull).collect(Collectors.toList());
        //根据细分查询画像
        List<LabelFieldVO> labelFieldInfoList = labelFieldInfoMapper.selectLabelFieldNameByTaskPartitionDictIds(taskPartitionDictIds);
        List<LabelFieldVO> labelFieldVOS = new ArrayList<>();
        labelFieldVOS.addAll(collect);
        labelFieldVOS.addAll(labelFieldInfoList);
        //组装编号用于前端判断
        for (LabelFieldVO labelFieldVO : labelFieldVOS) {
            labelFieldVO.setCode(i);
            i++;
        }
        //组装数据
        for (LabelFieldVO labelField : collect) {
            if (Objects.nonNull(labelField.getTaskPartitionDictId()) && StringUtils.isNotBlank(labelField.getTaskPartitionDictName()) && StringUtils.isNotBlank(labelField.getLabel())) {
                List<LabelFieldVO> collectLabelFieldInfoList = labelFieldInfoList.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getTaskPartitionDictId()) && labelField.getTaskPartitionDictId().equals(item.getTaskPartitionDictId())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(collectLabelFieldInfoList)) {
                    labelField.setLabelFieldList(collectLabelFieldInfoList);
                }
            }
        }
        //树图
        return collect.stream().map(LabelFieldTreeVO::new).collect(Collectors.toList());
    }

    /**
     * 新增标签字段信息
     *
     * @param labelFieldInfo 标签字段信息
     * @return 结果
     */
    @Override
    public int insertLabelFieldInfo(LabelFieldInfo labelFieldInfo) {
        labelFieldInfo.setCreateTime(LocalDateTime.now());
        return labelFieldInfoMapper.insertLabelFieldInfo(labelFieldInfo);
    }

    /**
     * 修改标签字段信息
     *
     * @param labelFieldInfo 标签字段信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateLabelFieldInfo(LabelFieldInfo labelFieldInfo) {
        // 检查id对应的标签信息是否存在
        LabelFieldInfo fieldInfo = labelFieldInfoMapper.selectLabelFieldInfoById(labelFieldInfo.getId());
        if (ObjectUtils.isEmpty(fieldInfo)) {
            throw new ServiceException("当前标签信息不存在，无法修改，请联系管理员");
        }
        // 执行修改操作
        labelFieldInfo.setUpdateBy(SecurityUtils.getUsername());
        labelFieldInfo.setUpdateTime(LocalDateTime.now());
        return labelFieldInfoMapper.updateLabelFieldInfo(labelFieldInfo);
    }

    /**
     * 批量删除标签字段信息
     *
     * @param ids 需要删除的标签字段信息主键
     * @return 结果
     */
    @Override
    public int deleteLabelFieldInfoByIds(Long[] ids) {
        return labelFieldInfoMapper.deleteLabelFieldInfoByIds(ids);
    }

    /**
     * 删除标签字段信息信息
     *
     * @param id 标签字段信息主键
     * @return 结果
     */
    @Override
    public int deleteLabelFieldInfoById(Long id) {
        return labelFieldInfoMapper.deleteLabelFieldInfoById(id);
    }

    /**
     * 批量新增标签字段信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertLabelFieldInfoList(LabelFieldInfoAddDTO labelFieldInfoAddDTO) {
        // 如果对象为空，提示请填加标签字段信息
        List<LabelFieldInfo> fieldInfoList = labelFieldInfoAddDTO.getLabelFieldInfoList();
        if (CollectionUtils.isEmpty(fieldInfoList)) {
            throw new ServiceException("请填加标签字段信息");
        }
        // 如果不存在，执行新增操作
        for (LabelFieldInfo labelFieldInfo : fieldInfoList) {
            labelFieldInfo.setCreateBy(SecurityUtils.getUsername());
            labelFieldInfo.setCreateTime(LocalDateTime.now());
            if (labelFieldInfoMapper.insertLabelFieldInfo(labelFieldInfo) <= 0) {
                throw new ServiceException("新增标签字段信息失败");
            }
        }
        return 1;
    }

    /**
     * 查询字段信息
     *
     * @return AjaxResult
     */
    @Override
    public AjaxResult taskTypeGrouping() {
        //查询任务类型
        List<TaskTypeDictVO> taskTypeDictList = taskTypeDictMapper.selectTaskTypeDicts();
        List<Long> ids = taskTypeDictList.stream().filter(Objects::nonNull).map(TaskTypeDictVO::getTaskTypeId).filter(Objects::nonNull).collect(Collectors.toList());
        //查询细分类型
        if (CollectionUtils.isEmpty(taskTypeDictList)) {
            return AjaxResult.success(taskTypeDictList);
        }
        List<TaskPartitionDict> taskPartitionDicts = taskPartitionDictMapper.selectTaskPartitionList(ids);
        if (CollectionUtils.isEmpty(taskPartitionDicts)) {
            return AjaxResult.success(taskPartitionDicts);
        }
        //组装
        for (TaskTypeDictVO taskTypeDictVO : taskTypeDictList) {
            List<TaskPartitionDict> collect = taskPartitionDicts.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getTaskTypeId()) && taskTypeDictVO.getTaskTypeId().equals(item.getTaskTypeId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                taskTypeDictVO.setTaskPartitionDictList(collect);
            }
        }
        return AjaxResult.success(taskTypeDictList);
    }
}
