package com.ruoyi.web.controller.dz;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dz.domain.DzSchool;
import com.ruoyi.dz.service.IDzSchoolService;
import com.ruoyi.enums.UserTypeEnum;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.dz.domain.DzAgent;
import com.ruoyi.dz.service.IDzAgentService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 机构代理Controller
 *
 * @author ruoyi
 * @date 2025-09-12
 */
@RestController
@RequestMapping("/dz/agent")
public class DzAgentController extends BaseController
{
    @Autowired
    private IDzAgentService dzAgentService;
    @Autowired
    private IDzSchoolService schoolService;
    @Autowired
    private ISysUserService userService;


    private List<DzAgent> getAgent(DzAgent dzAgent){
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        List<DzAgent> allList = Lists.newArrayList();
        if(UserTypeEnum.isAgent(sysUser.getUserType())) {
            dzAgent.setParentId(sysUser.getUserTypeId());
            allList.add(dzAgentService.selectDzAgentByAgentId(sysUser.getUserTypeId()));
        } else if(UserTypeEnum.isTeacher(sysUser.getUserType())) {
            dzAgent.setTeacherId(sysUser.getUserTypeId());
        } else if(!UserTypeEnum.isSys(sysUser.getUserType())) {
            dzAgent.setDeptId(sysUser.getDeptId());
        }

        allList.addAll(dzAgentService.selectDzAgentList(dzAgent));
        return allList;
    }
    /**
     * 查询机构代理列表
     */
    // @PreAuthorize("@ss.hasAnyPermi('dz:agent:list,dz:teacher:list')")
    @GetMapping("/list")
    public AjaxResult list(DzAgent dzAgent)
    {
        List<DzAgent> allList = getAgent(dzAgent);
        //处理关联学校的显示
        List<Long> distinctSchoolIds = allList.stream()
                .map(DzAgent::getSchoolIds)
                .filter(Objects::nonNull)        // 过滤null数组
                .filter(array -> array.length > 0) // 过滤空数组
                .flatMap(Arrays::stream).filter(Objects::nonNull)        // 过滤数组中的null元素
                .distinct()
                .collect(Collectors.toList());
        //查询学校名称
        if (CollectionUtil.isNotEmpty(distinctSchoolIds)){
            Map<Long, DzSchool> schoolMap = schoolService.selectDzSchoolListByIds(distinctSchoolIds).stream().collect(Collectors.toMap(DzSchool::getId, school -> school));
            for (DzAgent agent : allList) {
                if (agent.getSchoolIds() != null&&agent.getSchoolIds().length>0) {
                    String schoolName = Arrays.stream(agent.getSchoolIds())
                            .filter(Objects::nonNull)  // 过滤null值
                            .map(schoolId -> schoolMap.get(schoolId))  // 根据ID获取学校对象
                            .filter(Objects::nonNull)  // 过滤map中不存在的学校
                            .map(DzSchool::getName)    // 获取学校名称
                            .filter(name -> name != null && !name.trim().isEmpty())  // 过滤空名称
                            .collect(Collectors.joining(", "));  // 用逗号连接

                    agent.setSchoolName(schoolName);
                }
            }
        }

        allList = processAgentList(allList);

        return success(allList);
    }

    /**
     * 导出机构代理列表
     */
    @PreAuthorize("@ss.hasPermi('dz:agent:export')")
    @Log(title = "机构代理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DzAgent dzAgent)
    {
        List<DzAgent> list = getAgent(dzAgent);
        // 设置机构名称
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(agent -> {
                if (agent.getDept() != null && agent.getDept().getDeptName() != null) {
                    agent.setDeptName(agent.getDept().getDeptName());
                }
            });
        }
        //处理密码
        list = processAgentList(list);

        ExcelUtil<DzAgent> util = new ExcelUtil<DzAgent>(DzAgent.class);
        util.exportExcel(response, list, "机构代理数据");
    }

    /**
     * 获取机构代理详细信息
     */
    @PreAuthorize("@ss.hasPermi('dz:agent:query')")
    @GetMapping(value = "/{agentId}")
    public AjaxResult getInfo(@PathVariable("agentId") Long agentId)
    {
        return success(dzAgentService.selectDzAgentByAgentId(agentId));
    }

    /**
     * 新增机构代理
     */
    @PreAuthorize("@ss.hasPermi('dz:agent:add')")
    @Log(title = "机构代理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DzAgent dzAgent)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if(UserTypeEnum.isAgent(sysUser.getUserType()) && null != sysUser.getUserTypeId()) {
            dzAgent.setParentId(sysUser.getUserTypeId());
        }
        if(null == dzAgent.getDeptId()) {
            dzAgent.setDeptId(sysUser.getDeptId());
        }
        setSchools(dzAgent);
        return toAjax(dzAgentService.insertDzAgent(dzAgent));
    }

    /**
     * 修改机构代理
     */
    @PreAuthorize("@ss.hasPermi('dz:agent:edit')")
    @Log(title = "机构代理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DzAgent dzAgent)
    {
        setSchools(dzAgent);
        dzAgentService.updateDzAgent(dzAgent);
        //同时修改sys_user表的nickName
        SysUser user = userService.selectUserByUserName(String.valueOf(dzAgent.getAgentId()));
        if (null!=user){
            if (!user.getNickName().equalsIgnoreCase(dzAgent.getName())){
                user.setNickName(dzAgent.getName());
                userService.updateUserInfo(user);
            }
        }
        return AjaxResult.success();
    }

    private void setSchools(DzAgent dzAgent){
        String schools = dzAgent.getSchools();
        Long[] schoolIds = dzAgent.getSchoolIds();
        if (null!=schoolIds&&schoolIds.length>0){
            schools = Arrays.stream(schoolIds).filter(Objects::nonNull).map(String::valueOf) .collect(Collectors.joining(","));
            dzAgent.setSchools(schools);
        }
    }

    /**
     * 删除机构代理
     */
    @PreAuthorize("@ss.hasPermi('dz:agent:remove')")
    @Log(title = "机构代理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{agentIds}")
    public AjaxResult remove(@PathVariable Long[] agentIds)
    {
        return toAjax(dzAgentService.deleteDzAgentByAgentIds(agentIds));
    }

    private List<DzAgent> processAgentList(List<DzAgent> allList) {
        if (CollectionUtils.isNotEmpty(allList)) {
            List<Long> userIds = allList.stream()
                    .map(DzAgent::getUserId).filter(userId -> userId != null)
                    .distinct().collect(Collectors.toList());
            if (!userIds.isEmpty()) {
                List<SysUser> users = userService.selectUserByUserIds(userIds);
                // 创建userId到SysUser的映射
                Map<Long, SysUser> userMap = users.stream()
                        .filter(user -> user.getUserId() != null)
                        .collect(Collectors.toMap(
                                SysUser::getUserId,
                                user -> user,
                                (existing, replacement) -> existing
                        ));
                // 设置每个agent的password2
                allList.forEach(agent -> {
                    if (agent.getUserId() != null && userMap.containsKey(agent.getUserId())) {
                        agent.setPassword2(userMap.get(agent.getUserId()).getPassword2());
                        agent.setStatus(userMap.get(agent.getUserId()).getStatus());
                    }
                });
            }
        }
        return allList;
    }
}
