package com.ruoyi.web.controller.info;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

import javax.validation.constraints.NotEmpty;
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.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.date.LocalDateTimeUtils;
import com.ruoyi.info.hospital.domain.bo.HospitalDepartmentBo;
import com.ruoyi.info.hospital.domain.bo.HospitalDepartmentRackUpdateBo;
import com.ruoyi.info.hospital.domain.bo.HospitalRackUpdateBo;
import com.ruoyi.info.hospital.domain.vo.HospitalDepartmentVo;
import com.ruoyi.info.hospital.enums.RackStatusEnum;
import com.ruoyi.info.hospital.service.IHospitalDepartmentService;
import com.ruoyi.info.management.domain.TeacherDepartmentRel;
import com.ruoyi.info.management.service.IManagementTeacherService;
import com.ruoyi.info.management.service.ITeacherDepartmentRelService;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
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.*;

/**
 * 医院科室信息Controller
 *
 * @author baifc
 * @date 2025-09-20
 */
@Validated
@Api(value = "医院科室信息控制器", tags = {"医院科室信息管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/info/hospitalDepartment")
public class HospitalDepartmentController extends BaseController {

    private final IHospitalDepartmentService iHospitalDepartmentService;

    private final ITeacherDepartmentRelService iTeacherDepartmentRelService;

    /**
     * 分页查询医院科室信息列表
     */
    @ApiOperation("查询医院科室信息列表")
    @SaCheckPermission("info:hospitalDepartment:list")
    @GetMapping("/page")
    public TableDataInfo<HospitalDepartmentVo> page(@Validated(QueryGroup.class) HospitalDepartmentBo bo, PageQuery pageQuery) {
        if (bo.getCreateTimeEnd() != null) {
            bo.setCreateTimeEnd(LocalDateTimeUtils.getEndOfDate(bo.getCreateTimeEnd()));
        }
        return iHospitalDepartmentService.queryPageList(bo, pageQuery);
    }

    /**
     * 获取医院科室信息详细信息
     */
    @ApiOperation("获取医院科室信息详细信息")
    @SaCheckPermission("info:hospitalDepartment:query")
    @GetMapping("/info/{id}")
    public R<HospitalDepartmentVo> getInfo(@ApiParam("主键")
                                                  @NotNull(message = "主键不能为空")
                                                  @PathVariable("id") Long id) {
        return R.ok(iHospitalDepartmentService.queryById(id));
    }

    /**
     * 新增医院科室信息
     */
    @ApiOperation("新增医院科室信息")
    @SaCheckPermission("info:hospitalDepartment:add")
    @Log(title = "医院科室信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/add")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody HospitalDepartmentBo bo) {
        return toAjax(iHospitalDepartmentService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改医院科室信息
     */
    @ApiOperation("修改医院科室信息")
    @SaCheckPermission("info:hospitalDepartment:edit")
    @Log(title = "医院科室信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/edit")
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody HospitalDepartmentBo bo) {
        return toAjax(iHospitalDepartmentService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 删除医院科室信息
     */
    @ApiOperation("删除医院科室信息")
    @SaCheckPermission("info:hospitalDepartment:remove")
    @Log(title = "医院科室信息", businessType = BusinessType.DELETE)
    @PostMapping("/del/{ids}")
    public R<Void> remove(@ApiParam("主键串")
                                       @NotEmpty(message = "主键不能为空")
                                       @PathVariable Long[] ids) {
        return toAjax(iHospitalDepartmentService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }


    /**
     * 修改医院科室上下架状态
     */
    @ApiOperation("修改医院科室上下架状态")
    @SaCheckPermission("info:hospitalDepartment:edit")
    @Log(title = "修改医院科室上下架状态", businessType = BusinessType.UPDATE)
    @PostMapping("/updateRackStatus")
    public R<Void> updateRackStatus(@Validated @RequestBody HospitalDepartmentRackUpdateBo bo) {
        //  修改医院科室上下架
        iHospitalDepartmentService.updateRackStatus(bo);

        // TODO 如果是禁用状态 则需要强制踢出小程序端的登录用户
        return R.ok();
    }

    /**
     * 获取可关联的科室列表
     */
    @ApiOperation("获取可关联的科室列表")
    @GetMapping("/relList")
    public R<List<HospitalDepartmentVo>> relList(@Validated(QueryGroup.class) HospitalDepartmentBo bo) {
        bo.setRackStatus(RackStatusEnum.UP.getKey());
        List<HospitalDepartmentVo> list = iHospitalDepartmentService.queryByHospitalId(bo);
        Set<Long> ids = convertSet(list, HospitalDepartmentVo::getId);

        List<TeacherDepartmentRel> relList = iTeacherDepartmentRelService.queryByDepartmentIds(ids);
        if (CollUtil.isEmpty(relList)) {
            return R.ok(list);
        }
        // 这里需要判断科室的被关联情况
        for (HospitalDepartmentVo hospitalDepartmentVo : list) {
            TeacherDepartmentRel rel = findFirst(relList,
                r -> r.getDepartmentId().equals(hospitalDepartmentVo.getId()));
            if (rel != null && !rel.getTeacherId().equals(bo.getTeacherId())) {
                // 如果科室已被关联，且当前老师不是关联的，则不可被关联
                hospitalDepartmentVo.setRelFlag(true);
            }
        }
        return R.ok();
    }

}
