package cn.lihongjie.coal.jobPost.service;

import cn.lihongjie.coal.base.dto.CommonQuery;
import cn.lihongjie.coal.base.dto.IdRequest;
import cn.lihongjie.coal.base.entity.BaseEntity;
import cn.lihongjie.coal.base.mapper.CommonMapper;
import cn.lihongjie.coal.base.service.BaseService;
import cn.lihongjie.coal.common.CollectionUtils;
import cn.lihongjie.coal.common.Ctx;
import cn.lihongjie.coal.exception.BizException;
import cn.lihongjie.coal.jobPost.dto.CreateJobPostDto;
import cn.lihongjie.coal.jobPost.dto.JobPostDto;
import cn.lihongjie.coal.jobPost.dto.UpdateJobPostDto;
import cn.lihongjie.coal.jobPost.entity.JobPostEntity;
import cn.lihongjie.coal.jobPost.mapper.JobPostMapper;
import cn.lihongjie.coal.jobPost.repository.JobPostRepository;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
@Transactional
public class JobPostService extends BaseService<JobPostEntity, JobPostRepository> {
    @Autowired
    private CommonMapper commonMapper;
    @Autowired private JobPostRepository repository;

    @Autowired private JobPostMapper mapper;

    @Autowired private ConversionService conversionService;

    public JobPostDto create(CreateJobPostDto request) {
        JobPostEntity entity = mapper.toEntity(request);

        this.repository.save(entity);
        return getById(entity.getId());
    }

    public JobPostDto update(UpdateJobPostDto request) {
        JobPostEntity entity = this.repository.get(request.getId());
        this.mapper.updateEntity(entity, request);

        this.repository.save(entity);

        return getById(entity.getId());
    }

    public void delete(IdRequest request) {


        if (this.repository.isLinked(request.getIds())){
            throw new BizException("部分数据已被关联，无法删除");
        }

        this.repository.deleteAllById(request.getIds());
    }

    public JobPostDto getById(String id) {
        JobPostEntity entity = repository.get(id);

        return mapper.toDto(entity);
    }

    public Page<JobPostDto> list(CommonQuery query) {
        Page<JobPostEntity> page =
                repository.findAll(
                        query.specification(conversionService),
                        PageRequest.of(
                                query.getPageNo(),
                                query.getPageSize(),
                                Sort.by(query.getOrders())));

        Page<JobPostDto> page1 = page.map(this.mapper::toDto);
        List<Map> selfEmpIds =
                repository.getSelfEmpIds(CollectionUtils.map(page.getContent(), BaseEntity::getId));

        selfEmpIds =
                selfEmpIds.stream()
                        .map(
                                x -> {
                                    HashMap<Object, Object> map = new HashMap<>();
                                    map.put("id", x.get("id"));
                                    map.put("empIds", Stream.of((byte[]) x.get("empIds")).map(commonMapper::toString).collect(Collectors.toList()));
                                    return (Map) map;
                                })
                        .toList();

        List<Map> finalSelfEmpIds = selfEmpIds;
        page1.forEach(
                x -> {
                    finalSelfEmpIds.stream()
                            .filter(y -> y.get("id").equals(x.getId()))
                            .findFirst()
                            .ifPresent(
                                    y -> x.setSelfEmpIds(CollectionUtils.toList(y.get("empIds")).stream().map(commonMapper::toString).collect(Collectors.toList())));
                });
        return page1;
    }

    public JobPostDto findByName(String name) {

        JobPostEntity post =
                repository.findByNameAndOrganizationId(name, Ctx.currentUser().getOrganizationId());

        return mapper.toDto(post);
    }
}
