package com.ruoyi.api.controller.info;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.api.controller.common.AbstractApiController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.info.hospital.domain.bo.HospitalDepartmentBo;
import com.ruoyi.info.hospital.domain.vo.DepartmentOrderCountVo;
import com.ruoyi.info.hospital.domain.vo.DepartmentOrderStatisticsVo;
import com.ruoyi.info.hospital.domain.vo.DepartmentSimpleInfoVo;
import com.ruoyi.info.hospital.domain.vo.HospitalDepartmentVo;
import com.ruoyi.info.hospital.domain.vo.HospitalVo;
import com.ruoyi.info.hospital.service.IHospitalDepartmentService;
import com.ruoyi.info.hospital.service.IHospitalService;
import com.ruoyi.info.management.domain.TeacherDepartmentRel;
import com.ruoyi.info.management.service.ITeacherDepartmentRelService;
import com.ruoyi.info.order.service.IOrderService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;

import static com.ruoyi.common.utils.CollectionUtils.convertSet;
import static com.ruoyi.common.utils.CollectionUtils.findFirst;

/**
 * @author fucheng.bai
 * @date 2025/9/22
 */
@Validated
@Api(value = "API 科室管理控制器", tags = {"科室管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/info/hospitalDepartment")
public class ApiHospitalDepartmentController extends AbstractApiController {

    private final IHospitalService iHospitalService;

    private final IHospitalDepartmentService iHospitalDepartmentService;

    private final ITeacherDepartmentRelService iTeacherDepartmentRelService;

    private final IOrderService iOrderService;

    /**
     * 获取科室列表
     */
    @ApiOperation("获取科室列表")
    @GetMapping("/list")
    public R<List<HospitalDepartmentVo>> list(@Validated(QueryGroup.class) HospitalDepartmentBo bo) {
        bo.setRackStatus("0");
        return R.ok(iHospitalDepartmentService.queryByHospitalId(bo));
    }

    @ApiOperation("获取管理老师关联的科室列表")
    @GetMapping("/teacher/simpleList")
    public R<List<DepartmentSimpleInfoVo>> getTeacherSimpleInfo(@RequestParam(value = "hospitalId", required = false) Long hospitalId) {
        Long teacherId = getTeacherId();

        List<TeacherDepartmentRel> teacherDepartmentRelList = iTeacherDepartmentRelService.queryByTeacherId(teacherId);
        Set<Long> departmentIds = teacherDepartmentRelList.stream()
            .filter(item -> hospitalId == null || item.getHospitalId().equals(hospitalId))
            .map(TeacherDepartmentRel::getDepartmentId).collect(Collectors.toSet());

        List<HospitalDepartmentVo> departmentList = iHospitalDepartmentService.queryListByIds(departmentIds);
        List<DepartmentSimpleInfoVo> simpleDepartmentList = BeanCopyUtils.copyList(departmentList, DepartmentSimpleInfoVo.class);
        return R.ok(simpleDepartmentList);
    }

    @ApiOperation("获取管理老师关联的科室订单统计")
    @GetMapping("/teacher/statistics")
    public R<DepartmentOrderStatisticsVo> getTeacherStatistics(
        @RequestParam(value = "hospitalId", required = false) Long hospitalId,
        @RequestParam(value = "departmentId", required = false) Long departmentId) {
        Long teacherId = getTeacherId();

        Set<Long> departmentIds = new HashSet<>();
        // 如果没有传科室id，则需要查询了管理老师可管理的科室id列表
        if (departmentId == null) {
            List<TeacherDepartmentRel> teacherDepartmentRelList = iTeacherDepartmentRelService.queryByTeacherId(teacherId);
            departmentIds = teacherDepartmentRelList.stream()
                .filter(item -> hospitalId == null || item.getHospitalId().equals(hospitalId))
                .map(TeacherDepartmentRel::getDepartmentId).collect(Collectors.toSet());
        } else {
            departmentIds.add(departmentId);
        }
        List<DepartmentOrderCountVo> departmentOrderCountList = iOrderService.queryDepartmentOrderCount(departmentIds);

        // 获取医院以及科室名称
        Set<Long> hospitalIds = convertSet(departmentOrderCountList, DepartmentOrderCountVo::getHospitalId);
        List<HospitalVo> hospitalList = iHospitalService.queryListByIds(hospitalIds);
        List<HospitalDepartmentVo> departmentHospitalList =  iHospitalDepartmentService.queryListByIds(departmentIds);
        for (DepartmentOrderCountVo departmentOrderCount : departmentOrderCountList) {
            HospitalVo hospitalVo = findFirst(hospitalList, h -> h.getId().equals(departmentOrderCount.getHospitalId()));
            if (hospitalVo != null) {
                departmentOrderCount.setHospitalName(hospitalVo.getName());
            }
            HospitalDepartmentVo departmentHospitalVo = findFirst(departmentHospitalList, h -> h.getId().equals(departmentOrderCount.getDepartmentId()));
            if (departmentHospitalVo != null) {
                departmentOrderCount.setDepartmentName(departmentHospitalVo.getName());
            }
        }

        // 汇总
        DepartmentOrderStatisticsVo departmentOrderStatisticsVo = new DepartmentOrderStatisticsVo();
        departmentOrderStatisticsVo.setDepartmentOrderCountList(departmentOrderCountList);
        departmentOrderStatisticsVo.setOrderCount(CollectionUtils.getSumValue(departmentOrderCountList, DepartmentOrderCountVo::getOrderCount, Integer::sum, 0));
        departmentOrderStatisticsVo.setInProgressCount(CollectionUtils.getSumValue(departmentOrderCountList, DepartmentOrderCountVo::getInProgressCount, Integer::sum, 0));
        departmentOrderStatisticsVo.setFinishCount(CollectionUtils.getSumValue(departmentOrderCountList, DepartmentOrderCountVo::getFinishCount, Integer::sum, 0));

        return R.ok(departmentOrderStatisticsVo);
    }

}
