package jnpf.qualifications.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jnpf.base.service.SuperServiceImpl;
import jnpf.entity.qualifications.QualificationsField;
import jnpf.entity.qualifications.QualificationsFieldCategory;
import jnpf.entity.qualifications.QualificationsFieldItem;
import jnpf.model.qualifications.vo.QualificationsCategoryVo;
import jnpf.qualifications.mapper.QualificationsFieldCategoryMapper;
import jnpf.qualifications.service.QualificationsFieldCategoryService;
import jnpf.qualifications.service.QualificationsFieldItemService;
import jnpf.qualifications.service.QualificationsFieldService;
import jnpf.util.ServiceException;
import jnpf.util.StringUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

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

/**
 * todo
 *
 * @author Flynn Chan
 * @create 2024-03-04
 */
@Service
@Slf4j
public class QualificationsFieldCategoryServiceImpl extends SuperServiceImpl<QualificationsFieldCategoryMapper, QualificationsFieldCategory> implements QualificationsFieldCategoryService {

    private final QualificationsFieldCategoryMapper qualificationsFieldCategoryMapper;

    private final QualificationsFieldItemService qualificationsFieldItemService;

    private final QualificationsFieldService qualificationsFieldService;

    @Lazy
    public QualificationsFieldCategoryServiceImpl(QualificationsFieldCategoryMapper qualificationsFieldCategoryMapper, QualificationsFieldItemService qualificationsFieldItemService, QualificationsFieldService qualificationsFieldService) {
        this.qualificationsFieldCategoryMapper = qualificationsFieldCategoryMapper;
        this.qualificationsFieldItemService = qualificationsFieldItemService;
        this.qualificationsFieldService = qualificationsFieldService;
    }

    @Override
    public void create(QualificationsFieldCategory qualificationsFieldCategory){
        QualificationsFieldCategory build = QualificationsFieldCategory.builder()
                .name(qualificationsFieldCategory.getName())
                .fieldNum(qualificationsFieldCategory.getFieldNum())
                .description(qualificationsFieldCategory.getDescription())
                .sortCode(qualificationsFieldCategory.getSortCode())
                .propertyJson(qualificationsFieldCategory.getPropertyJson()).build();
        this.save(build);
    }

    @Override
    public QualificationsFieldCategory getCategoryById(String id) {
        return this.getById(id);
    }

    @Override
    public Long deleteCategoryById(String id) {
        QualificationsFieldCategory categoryById = this.getCategoryById(id);
        ServiceException.notNull(categoryById, "当前分类不存在");
        if(0==categoryById.getFieldNum()){
            this.removeById(id);
            return categoryById.getFieldNum();
        }
        return categoryById.getFieldNum();
    }

    @Override
    public List<QualificationsCategoryVo> getQualificationsFieldPages(String keyWord, String categoryId, Integer currentPage, Integer pageSize) {
        List<QualificationsCategoryVo> qualificationsFieldPages = qualificationsFieldCategoryMapper.getQualificationsFieldPages(keyWord, categoryId);
        //根据FieldId查询每个字段下有多少个字段 将对应的FieldId和ItemNum封装到map中
        Map<String,Long> countMap = new HashMap<>();
        if(!qualificationsFieldPages.isEmpty()){
            qualificationsFieldPages.forEach(item->{
                Long l = qualificationsFieldItemService.getBaseMapper().selectCount(new LambdaQueryWrapper<QualificationsFieldItem>().eq(QualificationsFieldItem::getFieldId, item.getFieldId()));
                countMap.put(item.getFieldId(),l);
            });
            if(!countMap.isEmpty()){
                Set<String> fieldIds = countMap.keySet();
                for (String fieldId : fieldIds) {
                    LambdaUpdateWrapper<QualificationsField> updateWrapper = Wrappers.<QualificationsField>update()
                            .lambda()
                            .set(QualificationsField::getItemNum, countMap.get(fieldId));
                    updateWrapper.eq(QualificationsField::getFId, fieldId);
                    qualificationsFieldService.getBaseMapper().update(null, updateWrapper);
                }
            }
        }
        PageHelper.startPage(currentPage,pageSize);
        return qualificationsFieldCategoryMapper.getQualificationsFieldPages(keyWord, categoryId);
    }

    @Override
    public List<QualificationsFieldCategory> getCategoryList() {
        List<QualificationsFieldCategory> fCreatorTime = baseMapper.selectList(Wrappers.<QualificationsFieldCategory>query()
                .orderByDesc("F_CreatorTime"));
        //获取分类下字段数量
        Map<String,Long> countMap = new HashMap<>();
        if(!fCreatorTime.isEmpty()){
            fCreatorTime.forEach(f->{
                Long l = qualificationsFieldService.getBaseMapper().selectCount(new LambdaQueryWrapper<QualificationsField>().eq(QualificationsField::getCategoryId, f.getId()));
                countMap.put(f.getId(),l);
            });
            if(!countMap.isEmpty()){
                Set<String> categoryIds = countMap.keySet();
                for (String categoryId : categoryIds) {
                    // 检查是否有对应的值，避免null值
                    Long fieldNum = countMap.get(categoryId);
                    if (fieldNum != null) {
                        LambdaUpdateWrapper<QualificationsFieldCategory> updateWrapper = Wrappers.<QualificationsFieldCategory>update()
                                .lambda()
                                .set(QualificationsFieldCategory::getFieldNum, fieldNum);
                        updateWrapper.eq(QualificationsFieldCategory::getId, categoryId);
                        this.getBaseMapper().update(null, updateWrapper);
                    }
                }
            }
        }
        return baseMapper.selectList(Wrappers.<QualificationsFieldCategory>query()
                .orderByDesc("F_CreatorTime"));
    }
}
