package com.kcim.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kcim.common.exception.CostException;
import com.kcim.common.util.UserContext;
import com.kcim.dao.mapper.ResponsibilityDepartmentMapper;
import com.kcim.dao.model.Responsibility;
import com.kcim.dao.model.ResponsibilityDepartment;
import com.kcim.dao.model.dto.DepartDTO;
import com.kcim.dao.model.dto.SysDepartment;
import com.kcim.service.CenterService;
import com.kcim.service.ResponsibilityDepartmentService;
import com.kcim.service.ResponsibilityService;
import com.kcim.vo.CenterDepartmentVO;
import com.kcim.vo.ResponsibilityDepartIdVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service("responsibilityDepartmentService")
public class ResponsibilityDepartmentServiceImpl
        extends ServiceImpl<ResponsibilityDepartmentMapper, ResponsibilityDepartment> implements ResponsibilityDepartmentService {

    private ResponsibilityService responsibilityService;

    private CenterService centerService;

    public ResponsibilityDepartmentServiceImpl(ResponsibilityService responsibilityService, CenterService centerService) {
        this.responsibilityService = responsibilityService;
        this.centerService = centerService;
    }

    /**
     * 获取责任中心对照列表
     * @return
     */
    @Override
    public List<CenterDepartmentVO> getCenterDepart() {
        return responsibilityService.getParentSon();
    }

    /**
     * 保存或修改责任中心对照
     *
     * @param departDTO
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void saveCenterDepart(DepartDTO departDTO) {
        Long responsibilityId = departDTO.getResponsibilityId();
        Long hospId = UserContext.getHospId();
        List<ResponsibilityDepartment> list = this.list(
                new LambdaQueryWrapper<ResponsibilityDepartment>().select(ResponsibilityDepartment::getId)
                        .eq(ResponsibilityDepartment::getResponsibilityId, responsibilityId)
                        .eq(ResponsibilityDepartment::getHospId, hospId)
        );
        if (CollUtil.isNotEmpty(list)) {
            this.removeByIds(list.stream().map(ResponsibilityDepartment::getId).collect(Collectors.toList()));
        }
        List<Long> departmentIds = departDTO.getDepartmentIds();
        if (CollUtil.isEmpty(departmentIds)) {
            return ;
        }
        List<Long> remove = departmentIds.stream().filter(Objects::isNull).collect(Collectors.toList());
        departmentIds.removeAll(remove);
        Responsibility byId = responsibilityService.getById(responsibilityId);
        if (Objects.isNull(byId)) {
            throw new CostException(500, "责任中心不存在或已被移除");
        }
        if (byId.getIsGatherCenter() == 1) {
            throw new CostException(500, "汇总中心不允许添加对照关系，请先修改");
        }

        List<SysDepartment> departmentByDepartmentIds = centerService.getDepartmentByDepartmentIds(departmentIds);
        List<ResponsibilityDepartment> data = departmentByDepartmentIds.stream().map(item -> {
            ResponsibilityDepartment centerDepart = new ResponsibilityDepartment();
            return centerDepart.setResponsibilityId(responsibilityId).setCreateTime(System.currentTimeMillis()).setHospId(hospId)
                    .setDepartmentId(Long.valueOf(item.getId())).setDepartmentCode(item.getCode()).setResponsibilityCode(byId.getResponsibilityCode());
        }).collect(Collectors.toList());

        this.saveBatch(data);
    }


    /**
     * 获取责任中心科室对照信息
     * @return
     */
    @Override
    public List<ResponsibilityDepartIdVO> getResponsibilityDepart(){
        Long hospId = UserContext.getHospId();
        //获取责任中心科室对照信息
        List<ResponsibilityDepartIdVO> responsibilityDepartIdVOS = baseMapper.getResponsibility(hospId);
        if(CollectionUtils.isEmpty(responsibilityDepartIdVOS))
        {
            responsibilityDepartIdVOS=new ArrayList<>();
            return  responsibilityDepartIdVOS;
        }
        //获取对照的科室字典
        List<SysDepartment> departmentByDepartmentIds =centerService.getDepartmentFilter(null);
        if(CollectionUtils.isEmpty(departmentByDepartmentIds))
        {
            return  responsibilityDepartIdVOS;
        }
        //组装科室代码和科室名称
        responsibilityDepartIdVOS.stream().forEach(responsibilityDepartIdVO -> {
            Optional<SysDepartment> firstDepartment = departmentByDepartmentIds.stream().filter(sysDepartment ->Long.valueOf(sysDepartment.getId()).equals(responsibilityDepartIdVO.getDepartmentId())).findFirst();
            if(firstDepartment.isPresent()){
                responsibilityDepartIdVO.setDepartmentCode(firstDepartment.get().getCode());
                responsibilityDepartIdVO.setDepartmentName(firstDepartment.get().getName());
            }
        });
        //只取有对应科室数据的记录
        List<ResponsibilityDepartIdVO> activeResponsibilityDeparts = responsibilityDepartIdVOS.stream().filter(responsibilityDepartIdVO -> !Objects.isNull(responsibilityDepartIdVO.getDepartmentCode())).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(activeResponsibilityDeparts))
        {
            activeResponsibilityDeparts=new ArrayList<>();
            return  activeResponsibilityDeparts;
        }
        return  activeResponsibilityDeparts;
    }


}