package com.ruoyi.web.controller.info;

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

import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
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.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.poi.ExcelUtil;
import com.ruoyi.info.hospital.domain.vo.HospitalVo;
import com.ruoyi.info.hospital.service.IHospitalService;
import com.ruoyi.info.nursing.domain.bo.EnableStatusBo;
import com.ruoyi.info.nursing.domain.vo.NursingWorkerVo;
import com.ruoyi.info.nursing.domain.bo.NursingWorkerBo;
import com.ruoyi.info.nursing.service.INursingWorkerService;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.info.order.domain.vo.OrderWorkerSumVo;
import com.ruoyi.info.order.service.IOrderService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiOperation;

import static com.ruoyi.common.utils.CollectionUtils.*;

/**
 * 护工信息Controller
 *
 * @author baifc
 * @date 2025-09-29
 */
@Validated
@Api(value = "护工信息控制器", tags = {"护工信息管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/info/nursingWorker")
public class NursingWorkerController extends BaseController {

    private final INursingWorkerService iNursingWorkerService;

    private final IHospitalService iHospitalService;

    private final IOrderService iOrderService;

    /**
     * 分页查询护工信息列表
     */
    @ApiOperation("查询护工信息列表")
    @SaCheckPermission("info:nursingWorker:list")
    @GetMapping("/page")
    public TableDataInfo<NursingWorkerVo> page(@Validated(QueryGroup.class) NursingWorkerBo bo, PageQuery pageQuery) {
        TableDataInfo<NursingWorkerVo> pageResult = iNursingWorkerService.queryPageList(bo, pageQuery);
        if (CollUtil.isEmpty(pageResult.getRows())) {
            return pageResult;
        }

        // 构建页面显示信息
        buildNursingWorkerPageResult(pageResult);
        // 赋值
        return pageResult;
    }


    /**
     * 获取护工信息详细信息
     */
    @ApiOperation("获取护工信息详细信息")
    @SaCheckPermission("info:nursingWorker:query")
    @GetMapping("/info/{id}")
    public R<NursingWorkerVo> getInfo(@ApiParam("主键")
                                                  @NotNull(message = "主键不能为空")
                                                  @PathVariable("id") Long id) {
        return R.ok(iNursingWorkerService.queryById(id));
    }

    /**
     * 新增护工信息
     */
    @ApiOperation("新增护工信息")
    @SaCheckPermission("info:nursingWorker:add")
    @Log(title = "护工信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/add")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody NursingWorkerBo bo) {
        return toAjax(iNursingWorkerService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改护工信息
     */
    @ApiOperation("修改护工信息")
    @SaCheckPermission("info:nursingWorker:edit")
    @Log(title = "护工信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/edit")
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody NursingWorkerBo bo) {
        return toAjax(iNursingWorkerService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 禁用/启用护工
     */
    @ApiOperation("禁用启用护工")
    @SaCheckPermission("info:nursingWorker:edit")
    @Log(title = "护工信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/update-status")
    public R<Void> updateStatus(@Validated @RequestBody EnableStatusBo bo) {
        iNursingWorkerService.updateStatus(bo);

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

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

    /**
     * 导出护工信息列表
     */
    @ApiOperation("导出护工信息列表")
    @SaCheckPermission("info:nursingWorker:export")
    @Log(title = "护工信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@Validated NursingWorkerBo bo, HttpServletResponse response) {
        // TODO 列表信息导出
        List<NursingWorkerVo> list = iNursingWorkerService.queryList(bo);
        ExcelUtil.exportExcel(list, "护工信息", NursingWorkerVo.class, response);
    }

    private void buildNursingWorkerPageResult(TableDataInfo<NursingWorkerVo> pageResult) {
        // 获取医院名称
        Set<Long> hospitalIds = convertSet(pageResult.getRows(), NursingWorkerVo::getHospitalId);
        List<HospitalVo> hospitalVos = iHospitalService.queryListByIds(hospitalIds);

        for (NursingWorkerVo nursingWorkerVo : pageResult.getRows()) {
            // 获取医院名称
            HospitalVo hospitalVo = findFirst(hospitalVos, h -> h.getId().equals(nursingWorkerVo.getHospitalId()));
            if (hospitalVo != null) {
                nursingWorkerVo.setHospitalName(hospitalVo.getName());
            }

            //  获取护工的订单信息
            List<OrderWorkerSumVo> orderWorkerSumVoList = iOrderService.getOrderWorkerSum();
            OrderWorkerSumVo orderWorkerSumVo = findFirst(orderWorkerSumVoList, o -> o.getWorkerId().equals(nursingWorkerVo.getId()));
            if (orderWorkerSumVo != null) {
                nursingWorkerVo.setOrderCount(orderWorkerSumVo.getCount());
            }
        }
    }

}
