package cn.lihongjie.coal.warehouseGoodsUnit.service;

import cn.lihongjie.coal.base.dto.CommonQuery;
import cn.lihongjie.coal.base.dto.IdRequest;
import cn.lihongjie.coal.base.mapper.CommonMapper;
import cn.lihongjie.coal.base.service.BaseService;
import cn.lihongjie.coal.exception.BizException;
import cn.lihongjie.coal.warehouseGoodsUnit.dto.BatchAddRequest;
import cn.lihongjie.coal.warehouseGoodsUnit.dto.CreateWarehouseGoodsUnitDto;
import cn.lihongjie.coal.warehouseGoodsUnit.dto.UpdateWarehouseGoodsUnitDto;
import cn.lihongjie.coal.warehouseGoodsUnit.dto.WarehouseGoodsUnitDto;
import cn.lihongjie.coal.warehouseGoodsUnit.entity.WarehouseGoodsUnitEntity;
import cn.lihongjie.coal.warehouseGoodsUnit.mapper.WarehouseGoodsUnitMapper;
import cn.lihongjie.coal.warehouseGoodsUnit.repository.WarehouseGoodsUnitRepository;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;

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.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.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WarehouseGoodsUnitService
        extends BaseService<WarehouseGoodsUnitEntity, WarehouseGoodsUnitRepository> {
    @PersistenceContext EntityManager em;
    @Autowired private WarehouseGoodsUnitRepository repository;

    @Autowired private WarehouseGoodsUnitMapper mapper;

    @Autowired private ConversionService conversionService;

    public WarehouseGoodsUnitDto create(CreateWarehouseGoodsUnitDto request) {
        WarehouseGoodsUnitEntity entity = mapper.toEntity(request);

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

    public WarehouseGoodsUnitDto update(UpdateWarehouseGoodsUnitDto request) {
        WarehouseGoodsUnitEntity 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 WarehouseGoodsUnitDto getById(String id) {
        WarehouseGoodsUnitEntity entity = repository.get(id);

        return mapper.toDto(entity);
    }

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

        return page.map(this.mapper::toDto);
    }
    @Autowired private CommonMapper commonMapper;

    public void batchAdd(BatchAddRequest request) {

        if (CollectionUtils.isNotEmpty(request.getNames())) {

            Set<String> set =
                    request.getNames().stream()
                            .distinct()
                            .map(StringUtils::trim)
                            .filter(StringUtils::isNotBlank)
                            .collect(Collectors.toSet());

            List<String> exists =
                    em.createQuery(
                                    "select distinct name from WarehouseGoodsUnitEntity",
                                    String.class)
                            .getResultList();
            set.removeAll(exists);
            if (CollectionUtils.isNotEmpty(set)) {
                set.forEach(
                        name -> {
                            WarehouseGoodsUnitEntity entity = new WarehouseGoodsUnitEntity();
                            entity.setName(name);
                            this.repository.save(entity);
                        });
            }
        }
    }

    public void init(String orgId) {

        List<WarehouseGoodsUnitEntity> all = this.repository.findByOrganizationId(orgId);

        if (!all.isEmpty()) {
            return;
        }

        Set<String> units =
                Set.of(
                        "吨", "千克", "克", "升", "毫升", "个", "件", "台", "套", "箱", "包", "袋", "桶", "瓶", "罐",
                        "卷", "支", "根", "条", "片", "块", "颗", "粒", "对", "双", "只", "张", "本", "盒");

        for (String unit : units) {
            WarehouseGoodsUnitEntity entity = new WarehouseGoodsUnitEntity();
            entity.setName(unit);
            entity.setOrganizationId(orgId);
            this.repository.save(entity);
        }
    }
}
