package com.changhu.service.impl;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.changhu.common.exception.MessageException;
import com.changhu.common.pojo.vo.SelectNodeVo;
import com.changhu.module.management.pojo.entity.EnterprisesUnit;
import com.changhu.module.management.service.ServiceProjectService;
import com.changhu.pojo.dto.EnterprisesUnitDetailDTO;
import com.changhu.pojo.dto.ServiceProjectDTO;
import com.changhu.service.OpenApiService;
import com.changhu.support.mybatisplus.pojo.entity.BaseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 20252
 * @createTime 2024/10/9 下午5:29
 * @desc OpenApiServiceImpl...
 */
@Service
public class OpenApiServiceImpl implements OpenApiService {

    @Autowired
    private ServiceProjectService serviceProjectService;

    @Override
    public List<SelectNodeVo<Long>> getEnterprisesUnit(String code, Integer level) {
        return Db.lambdaQuery(EnterprisesUnit.class)
                .eq(level == 1, EnterprisesUnit::getProvince, code)
                .eq(level == 2, EnterprisesUnit::getCity, code)
                .eq(level == 3, EnterprisesUnit::getDistricts, code)
                .eq(level == 4, EnterprisesUnit::getStreet, code)
                .list()
                .stream()
                .map(item -> SelectNodeVo.<Long>builder()
                        .value(item.getSnowFlakeId())
                        .label(item.getName())
                        .build())
                .toList();
    }

    @Override
    public EnterprisesUnitDetailDTO enterprisesUnitDetailById(Long enterprisesUnitId) {
        return Db.lambdaQuery(EnterprisesUnit.class)
                .eq(BaseEntity::getSnowFlakeId, enterprisesUnitId)
                .oneOpt()
                .map(item -> EnterprisesUnitDetailDTO.builder()
                        .snowFlakeId(item.getSnowFlakeId())
                        .name(item.getName())
                        .address(item.getAddress())
                        .contactPersonInfo(item.getContactPersonInfo())
                        .remark(item.getRemark())
                        .serviceProjectList(serviceProjectService.getServiceProjectByEnterprisesUnitId(item.getSnowFlakeId()))
                        .createTime(item.getCreateTime())
                        .build())
                .orElseThrow(() -> new MessageException("企事业单位不存在"));
    }
}
