package com.ruoyi.api.controller.info;

import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.validation.constraints.NotNull;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.api.controller.common.AbstractApiController;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.FilePathSplicingType;
import com.ruoyi.common.filepathsplicing.FilePathSplicing;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.date.LocalDateTimeUtils;
import com.ruoyi.info.management.domain.TeacherDepartmentRel;
import com.ruoyi.info.management.domain.vo.WorkerOrderCountVo;
import com.ruoyi.info.management.service.ITeacherDepartmentRelService;
import com.ruoyi.info.nursing.domain.bo.NursingWorkerApiReqBo;
import com.ruoyi.info.nursing.domain.bo.NursingWorkerBo;
import com.ruoyi.info.nursing.domain.vo.NursingWorkerBenchVo;
import com.ruoyi.info.nursing.domain.vo.NursingWorkerVo;
import com.ruoyi.info.nursing.service.INursingWorkerService;
import com.ruoyi.info.order.domain.bo.OrderCountBo;
import com.ruoyi.info.order.enums.OrderStatus;
import com.ruoyi.info.order.service.IOrderService;

import cn.dev33.satoken.annotation.SaCheckPermission;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;

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

/**
 * @author fucheng.bai
 * @date 2025/10/9
 */
@Validated
@Api(value = "API 护工管理控制器", tags = {"护工管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/info/nursingWorker")
public class ApiNursingWorkerController extends AbstractApiController {

    private final INursingWorkerService nursingWorkerService;

    private final IOrderService orderService;

    private final ITeacherDepartmentRelService teacherDepartmentRelService;

    @FilePathSplicing(type = FilePathSplicingType.RESPONSE)
    @ApiOperation("护工工作台信息")
    @GetMapping("/workbench")
    public R<NursingWorkerBenchVo> workbench() {
        Long workerId = getWorkerId();

        NursingWorkerBenchVo nursingWorkerBenchVo = new NursingWorkerBenchVo();

        //  获取护工的基本信息
        NursingWorkerVo nursingWorkerVo = nursingWorkerService.queryById(workerId);
        BeanCopyUtils.copy(nursingWorkerVo, nursingWorkerBenchVo);

        //  获取护工的订单信息
        // 护工订单总数
        Integer orderCount = orderService.queryOrderCount(new OrderCountBo(workerId));
        // 护工今日订单数量
        Date todayBegin = DateUtils.toDate(LocalDateTimeUtils.getToday());
        Date todayEnd = LocalDateTimeUtils.getEndOfDate(todayBegin);
        Integer todayCount = orderService.queryOrderCount(new OrderCountBo(workerId, todayBegin, todayEnd));
        // 护工待服务数量
        Integer waitServiceCount = orderService.queryOrderCount(new OrderCountBo(workerId, OrderStatus.wait_service.getCode()));
        // 护工服务中数量
        Integer inServiceCount = orderService.queryOrderCount(new OrderCountBo(workerId, OrderStatus.in_progress.getCode()));
        nursingWorkerBenchVo.setOrderCount(orderCount);
        nursingWorkerBenchVo.setTodayCount(todayCount);
        nursingWorkerBenchVo.setWaitServiceCount(waitServiceCount);
        nursingWorkerBenchVo.setInServiceCount(inServiceCount);

        return R.ok(nursingWorkerBenchVo);
    }

    // 护工列表查询
    @FilePathSplicing(type = FilePathSplicingType.RESPONSE)
    @ApiOperation("护工列表查询")
    @GetMapping("/list")
    public R<List<NursingWorkerVo>> list(NursingWorkerApiReqBo bo) {
        Long teacherId = getTeacherId();

        Set<Long> hospitalIds = new HashSet<>();
        // 查询管理老师可查看的医院
        if (bo.getHospitalId() == null) {
            List<TeacherDepartmentRel> teacherDepartmentRelList = teacherDepartmentRelService.queryByTeacherId(teacherId);
            hospitalIds = convertSet(teacherDepartmentRelList, TeacherDepartmentRel::getHospitalId);
        } else {
            hospitalIds.add(bo.getHospitalId());
        }
        bo.setHospitalIds(hospitalIds);

        // 查询护工列表
        List<NursingWorkerVo> nursingWorkerList = nursingWorkerService.queryListForTeacher(bo);

        // 查询护工的订单数量
        Set<Long> workerIds = convertSet(nursingWorkerList, NursingWorkerVo::getId);
        List<WorkerOrderCountVo> workerOrderCountList = orderService.queryWorkerOrderCount(workerIds);
        for (NursingWorkerVo nursingWorker : nursingWorkerList) {
            WorkerOrderCountVo workerOrderCountVo = findFirst(workerOrderCountList, o -> o.getWorkerId().equals(nursingWorker.getId()));
            if (workerOrderCountVo != null) {
                nursingWorker.setInProgressCount(workerOrderCountVo.getInProgressCount());
                nursingWorker.setFinishCount(workerOrderCountVo.getFinishCount());
            }
        }

        return R.ok(nursingWorkerList);
    }

    /**
     * 获取护工信息详细信息
     */
    @FilePathSplicing(type = FilePathSplicingType.RESPONSE)
    @ApiOperation("获取护工信息详细信息")
    @GetMapping("/info/{id}")
    public R<NursingWorkerVo> getInfo(@ApiParam("主键")
                                      @NotNull(message = "主键不能为空")
                                      @PathVariable("id") Long id) {
        NursingWorkerVo nursingWorker = nursingWorkerService.queryById(id);

        // 查询订单数量
        List<Long> ids = Collections.singletonList(nursingWorker.getId());
        List<WorkerOrderCountVo> workerOrderCountList = orderService.queryWorkerOrderCount(ids);

        WorkerOrderCountVo workerOrderCountVo = findFirst(workerOrderCountList, o -> o.getWorkerId().equals(nursingWorker.getId()));
        if (workerOrderCountVo != null) {
            nursingWorker.setInProgressCount(workerOrderCountVo.getInProgressCount());
            nursingWorker.setFinishCount(workerOrderCountVo.getFinishCount());
        }
        return R.ok(nursingWorker);
    }


    /**
     * 新增护工信息
     */
    @FilePathSplicing(type = FilePathSplicingType.REQUEST)
    @ApiOperation("新增护工信息")
    @RepeatSubmit()
    @PostMapping("/add")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody NursingWorkerBo bo) {
        nursingWorkerService.insertByBo(bo);
        return R.ok();
    }


    @FilePathSplicing(type = FilePathSplicingType.REQUEST)
    @ApiOperation("修改护工信息")
    @RepeatSubmit()
    @PostMapping("/edit")
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody NursingWorkerBo bo) {
        nursingWorkerService.updateByBo(bo);
        return R.ok();
    }

}
