package com.ruoyi.web.controller.system;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.domain.dto.emergencyUser.EmergencyUserAddRequest;
import com.ruoyi.web.domain.entity.EmergencyUser;
import com.ruoyi.web.domain.entity.PersonInfo;
import com.ruoyi.web.domain.vo.EmergencyUserVO;
import com.ruoyi.web.service.EmergencyUserService;
import com.ruoyi.web.service.PersonInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

@Api(tags = "应急指令下达负责人管理")
@RestController
@RequestMapping("/system/emergency/user")
public class EmergencyUserController {

    @Autowired
    private EmergencyUserService emergencyUserService;


    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 添加指令下达负责人
     *
     * @param emergencyUserAddRequest
     * @return
     */
    @ApiOperation("添加指令下达负责人")
    @PostMapping("/add")
    public AjaxResult addEmergencyUser(@RequestBody EmergencyUserAddRequest emergencyUserAddRequest) {
        if (emergencyUserAddRequest == null) {
            return error("请求参数为空");
        }
        Integer personId = emergencyUserAddRequest.getPersonId();
        QueryWrapper<PersonInfo> wrapper = new QueryWrapper<>();
        wrapper.select("user_id")
                .eq("id", personId);
        PersonInfo personInfo = personInfoService.getOne(wrapper);
        if (personInfo == null) {
            throw new ServiceException("未找到负责人");
        }
        EmergencyUser emergencyUser = new EmergencyUser();
        Integer userId = personInfo.getUserId();

        QueryWrapper<EmergencyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        long count = emergencyUserService.count(queryWrapper);
        if (count == 0) {
            // 不存在才添加
            emergencyUser.setUserId(userId);
            boolean save = emergencyUserService.save(emergencyUser);
            if (save) {
                return success("添加成功");
            } else {
                return error("添加失败");
            }
        } else {
            return error("添加失败,该用户已成为指令下达负责人");
        }
    }

    /**
     * 删除指令下达负责人
     *
     * @param paramsMap
     * @return
     */
    @ApiOperation("删除指令下达负责人")
    @PostMapping("/delete")
    public AjaxResult deleteEmergencyUser(@RequestBody Map<String, String> paramsMap) {
        String ids = paramsMap.get("ids");
        if (StrUtil.isBlank(ids)) {
            return error("请求参数为空");
        }

        // 2. 分割ID字符串为List<Integer>
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .map(Long::parseLong)
                .collect(Collectors.toList());

        if (idList.isEmpty()) {
            throw new ServiceException("ID格式异常");
        }

        // 3. 构建删除条件
        QueryWrapper<EmergencyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);

        // 4. 执行删除（返回是否删除成功）
        boolean b = emergencyUserService.remove(queryWrapper);
        if (b) {
            return success("删除成功");
        }
        return error("删除失败");
    }


    /**
     * 获取指令下达负责人列表
     *
     * @return
     */
    @ApiOperation("获取指令下达负责人列表")
    @PostMapping("/list")
    public AjaxResult listEmergencyUserByPage() {
        List<EmergencyUser> list = emergencyUserService.list();

        // 收集所有用户ID
        List<Long> userIds = list.stream()
                .map(emergencyUser -> Long.valueOf(emergencyUser.getUserId()))
                .collect(Collectors.toList());
        // 批量查询用户信息
        List<SysUser> sysUsers = sysUserMapper.selectUsersByIds(userIds);
        // 创建用户ID->昵称的映射
        Map<Long, String> userNickNameMap = sysUsers.stream()
                .collect(Collectors.toMap(SysUser::getUserId, SysUser::getNickName));

        List<EmergencyUserVO> emergencyUserVOList = list.stream().map(emergencyUser -> {
            Integer userId = emergencyUser.getUserId();
            EmergencyUserVO emergencyUserVO = new EmergencyUserVO();
            // 从映射中获取昵称
            String nickName = userNickNameMap.getOrDefault(Long.valueOf(userId), "");
            emergencyUserVO.setNickName(nickName);
            emergencyUserVO.setId(emergencyUser.getId());
            return emergencyUserVO;
        }).collect(Collectors.toList());
//        sysUserMapper.selectUserList();
//        return success(emergencyUserVOList);
        return success( sysUserService.selectUserList(new SysUser()));


//        List<EmergencyUserVO> emergencyUserVOList = list.stream().map(emergencyUser -> {
//            Integer userId = emergencyUser.getUserId();
//            EmergencyUserVO emergencyUserVO = new EmergencyUserVO();
//            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
//            wrapper.select("nick_name")
//                    .eq("user_id", userId);
//            SysUser sysUser = sysUserMapper.selectUserById(Long.valueOf(userId));
//            String nickName = sysUser.getNickName();
//            emergencyUserVO.setNickName(nickName);
//            emergencyUserVO.setId(emergencyUser.getId());
//            return emergencyUserVO;
//        }).collect(Collectors.toList());
//        return success(emergencyUserVOList);

    }
}
