package com.ruoyi.web.controller.dz;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ValidationException;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.dz.domain.DzAgent;
import com.ruoyi.dz.domain.DzSchool;
import com.ruoyi.dz.mapper.DzAgentMapper;
import com.ruoyi.dz.mapper.DzSchoolMapper;
import com.ruoyi.enums.CardType;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.dz.service.IDzCardsService;
import com.ruoyi.enums.CardAudit;
import com.ruoyi.enums.RequestStatus;
import com.ruoyi.enums.UserTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
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.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.DzCardsOpen;
import com.ruoyi.dz.service.IDzCardsOpenService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 开卡申请Controller
 *
 * @author ruoyi
 * @date 2025-09-12
 */
@RestController
@RequestMapping("/dz/open")
@Api(tags = "后台-学习卡管理-开卡申请")
public class DzCardsOpenController extends BaseController
{
    @Autowired
    private IDzCardsOpenService dzCardsOpenService;
    @Autowired
    private IDzCardsService dzCardsService;
    @Autowired
    private DzSchoolMapper dzSchoolMapper;
    @Autowired
    private DzAgentMapper dzAgentMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    /**
     * 查询开卡申请列表
     */
    @PreAuthorize("@ss.hasPermi('dz:open:list')")
    @GetMapping("/list")
    @ApiOperation("开卡申请列表")
    public TableDataInfo list(DzCardsOpen dzCardsOpen)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (UserTypeEnum.isAgent(sysUser.getUserType())) {
            dzCardsOpen.setAgentId(sysUser.getUserTypeId());
        } else if(UserTypeEnum.isSchool(sysUser.getUserType())) {
            dzCardsOpen.setSchoolId(sysUser.getUserTypeId());
        } else if(!UserTypeEnum.isSys(sysUser.getUserType())) {
            dzCardsOpen.setDeptId(sysUser.getDeptId());
        }
        startPage();
        List<DzCardsOpen> list = dzCardsOpenService.selectDzCardsOpenList(dzCardsOpen);
        
        // 提取所有的schoolId、agentId和deptId
        Set<Long> schoolIds = list.stream()
                .map(DzCardsOpen::getSchoolId)
                .filter(id -> id != null)
                .collect(Collectors.toSet());
        
        Set<Long> agentIds = list.stream()
                .map(DzCardsOpen::getAgentId)
                .filter(id -> id != null)
                .collect(Collectors.toSet());
        
        
        
        // 批量查询学校
        Map<Long, String> schoolMap = java.util.Collections.emptyMap();
        if (CollectionUtils.isNotEmpty(schoolIds)) {
            List<DzSchool> schoolList = dzSchoolMapper.selectDzSchoolListByIds(new java.util.ArrayList<>(schoolIds));
            schoolMap = schoolList.stream()
                    .filter(school -> school.getId() != null && school.getName() != null)
                    .collect(Collectors.toMap(DzSchool::getId, DzSchool::getName, (existing, replacement) -> existing));
        }
        
        // 批量查询代理商
        Map<Long, DzAgent> agentMap = java.util.Collections.emptyMap();
        Set<Long> deptIds = new java.util.HashSet<>();
        if (CollectionUtils.isNotEmpty(agentIds)) {
            List<DzAgent> agentList = dzAgentMapper.selectDzAgentByAgentIds(new java.util.ArrayList<>(agentIds));
            agentMap = agentList.stream()
                    .filter(agent -> agent.getAgentId() != null)
                    .collect(Collectors.toMap(DzAgent::getAgentId, agent -> agent, (existing, replacement) -> existing));
            // 批量查询机构
            deptIds.addAll(agentList.stream().map(DzAgent::getDeptId).filter(id -> id != null).collect(Collectors.toSet()));
        }
        
        // 批量查询机构
        Map<Long, String> deptMap = java.util.Collections.emptyMap();
        if (CollectionUtils.isNotEmpty(deptIds)) {
            List<SysDept> deptList = sysDeptMapper.selectDeptByIds(new java.util.ArrayList<>(deptIds));
            deptMap = deptList.stream()
                    .filter(dept -> dept.getDeptId() != null && dept.getDeptName() != null)
                    .collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName, (existing, replacement) -> existing));
        }
        
        // 填充schoolName、agentName和deptName
        for (DzCardsOpen item : list) {
            item.setCardType(CardType.getNewVal(item.getCardType()));
            if (item.getSchoolId() != null && schoolMap.containsKey(item.getSchoolId())) {
                item.setSchoolName(schoolMap.get(item.getSchoolId()));
            }
            if (item.getAgentId() != null && agentMap.containsKey(item.getAgentId())) {
                DzAgent agent = agentMap.get(item.getAgentId());
                if (agent != null && agent.getName() != null) {
                    item.setAgentName(agent.getName());
                }
                if (agent != null && agent.getDeptId() != null && deptMap.containsKey(agent.getDeptId())) {
                    item.setDeptName(deptMap.get(agent.getDeptId()));
                }
            }
        }
        
        return getDataTable(list);
    }

    /**
     * 导出开卡申请列表
     */
    @PreAuthorize("@ss.hasPermi('dz:open:export')")
    @Log(title = "开卡申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DzCardsOpen dzCardsOpen)
    {
        List<DzCardsOpen> list = dzCardsOpenService.selectDzCardsOpenList(dzCardsOpen);
        ExcelUtil<DzCardsOpen> util = new ExcelUtil<DzCardsOpen>(DzCardsOpen.class);
        util.exportExcel(response, list, "开卡申请数据");
    }

    /**
     * 获取开卡申请详细信息
     */
//    @PreAuthorize("@ss.hasPermi('dz:open:query')")
//    @GetMapping(value = "/{id}")
//    public AjaxResult getInfo(@PathVariable("id") Long id)
//    {
//        return success(dzCardsOpenService.selectDzCardsOpenById(id));
//    }

    /**
     * 新增开卡申请
     */
    @PreAuthorize("@ss.hasPermi('dz:open:add')")
    @Log(title = "开卡申请", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("申请开卡")
    public AjaxResult add(@RequestBody DzCardsOpen dzCardsOpen)
    {
        dzCardsOpen.setSender(String.valueOf(SecurityUtils.getUserId()));
        dzCardsOpen.setStatus(CardAudit.NoAudit.getVal());
        return toAjax(dzCardsService.requestOpenCard(dzCardsOpen));
    }

    /**
     * 修改开卡申请
     */
    @PreAuthorize("@ss.hasPermi('dz:open:edit')")
    @Log(title = "开卡申请", businessType = BusinessType.UPDATE)
    @PostMapping("/audit")
    @ApiOperation("审核开卡申请")
    public AjaxResult audit(@RequestBody DzCardsOpen dzCardsOpen)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        return toAjax(dzCardsService.confirmOpenCard(dzCardsOpen, sysUser));
    }

    /**
     * 删除开卡申请
     */
    @PreAuthorize("@ss.hasPermi('dz:open:remove')")
    @Log(title = "开卡申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        DzCardsOpen open = dzCardsOpenService.selectDzCardsOpenById(id);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (UserTypeEnum.Agent.getVal().equals(sysUser.getUserType()) && !open.getAgentId().equals(sysUser.getUserId())) {
            throw new ValidationException("不可修改他人申请");
        }
        if(RequestStatus.Accept.getVal().equals(open.getStatus())) {
            throw new ValidationException("不可删除已经通过的申请");
        }
        return toAjax(dzCardsOpenService.deleteDzCardsOpenByIds(new Long[] {id}));
    }
}
