package com.ruoyi.web.controller.dz;

import java.util.Arrays;
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.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.ExamType;
import com.ruoyi.common.enums.UserRegStatus;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.dz.domain.DzAgent;
import com.ruoyi.dz.dto.CardStudentDTO;
import com.ruoyi.dz.service.IDzAgentService;
import com.ruoyi.enums.CardAction;
import com.ruoyi.enums.CardType;
import com.ruoyi.enums.UserTypeEnum;
import com.ruoyi.learn.domain.LearnTestStudent;
import com.ruoyi.learn.service.ILearnTestStudentService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.domain.CardUserBody;
import com.ruoyi.web.domain.DzCardExport;
import com.ruoyi.web.service.SysLoginService;
import com.ruoyi.web.service.SysRegisterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
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.DzCards;
import com.ruoyi.dz.service.IDzCardsService;
import com.ruoyi.dz.service.IDzSubjectService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 学习卡Controller
 *
 * @author ruoyi
 * @date 2025-09-12
 */
@RestController
@RequestMapping("/dz/cards")
@Api(tags = "后台-学习卡管理")
public class DzCardsController extends BaseController
{
    @Autowired
    private IDzCardsService dzCardsService;
    @Autowired
    private IDzAgentService agentService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private SysRegisterService sysRegisterService;
    @Autowired
    private IDzSubjectService dzSubjectService;
    @Autowired
    private ILearnTestStudentService learnTestStudentService;

    /**
     * 查询学习卡列表
     */
    @PreAuthorize("@ss.hasPermi('dz:cards:list')")
    @GetMapping("/list")
    @ApiOperation("列表")
    public TableDataInfo list(DzCards dzCards)
    {
        prepare(dzCards);
        startPage();
        List<DzCards> list = dzCardsService.selectDzCardsList2(dzCards);
        return getDataTable(list);
    }

    /**
     * 查询学习卡学生列表（简化版），发送试卷使用
     */
    @PreAuthorize("@ss.hasPermi('dz:cards:list')")
    @GetMapping("/list2")
    @ApiOperation("学生列表")
    public TableDataInfo list2(DzCards dzCards,Long paperId)
    {
        prepare(dzCards);
        startPage();
        List<CardStudentDTO> list = dzCardsService.selectDzCardsList3(dzCards);

        // 查询已发布的学生ID列表（根据paperId）
        Set<Long> publishedStudentIds = new java.util.HashSet<>();
        if (paperId != null) {
            LearnTestStudent queryCondition = new LearnTestStudent();
            queryCondition.setPaperId(paperId);
            List<LearnTestStudent> publishedStudents = learnTestStudentService.selectLearnTestStudentList(queryCondition);
            publishedStudentIds = publishedStudents.stream()
                    .map(LearnTestStudent::getStudentId)
                    .collect(Collectors.toSet());
        }

        // 设置 isSend 字段
        for (CardStudentDTO dto : list) {
            if (dto.getUserId() != null && publishedStudentIds.contains(dto.getUserId())) {
                dto.setIsSend(true);
            } else {
                dto.setIsSend(false);
            }
        }

        return getDataTable(list);
    }

    private DzCards prepare(DzCards dzCards) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        String userType = sysUser.getUserType();
        if (UserTypeEnum.isInstitution(userType)) {
            dzCards.setDeptId(SecurityUtils.getDeptId());
        } else if (UserTypeEnum.isSchool(userType)) {
            dzCards.setCampusId(sysUser.getUserTypeId());
        } else if (UserTypeEnum.isTeacher(userType)) {
            dzCards.setTeacherId(sysUser.getUserTypeId());
        }
        if ((UserTypeEnum.isAgent(userType)) && null == dzCards.getAgentId()) {
            //代理商及老师只能查看分配给自己的卡
            DzAgent agent = agentService.selectDzAgentByUserId(SecurityUtils.getUserId());
            if (null != agent) {
                if (NumberUtils.isPositive(agent.getParentId())) {
                    dzCards.setLeafAgentId(agent.getAgentId());
                } else {
                    dzCards.setAgentId(agent.getAgentId());
                }
            }
        }
        boolean beginBlank = StringUtils.isBlank(dzCards.getBegin());
        boolean endBlank = StringUtils.isBlank(dzCards.getEnd());
        if (beginBlank && !endBlank) {
            dzCards.setBegin(dzCards.getEnd());
        } else if (!beginBlank && endBlank) {
            dzCards.setEnd(dzCards.getBegin());
        }
        return dzCards;
    }

    /**
     * 导出学习卡列表
     */
    @PreAuthorize("@ss.hasPermi('dz:cards:export')")
    @Log(title = "学习卡", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DzCards dzCards)
    {
        List<DzCards> list = dzCardsService.selectDzCardsList(prepare(dzCards));
        ExcelUtil<DzCardExport> util = new ExcelUtil<DzCardExport>(DzCardExport.class);
        util.exportExcel(response, list.stream().map(t -> {
            DzCardExport exp = new DzCardExport();
            BeanUtils.copyProperties(t, exp);
            return exp;
        }).collect(Collectors.toList()), "学习卡数据");
    }

    /**
     * 获取学习卡详细信息
     */
    @PreAuthorize("@ss.hasPermi('dz:cards:query')")
    @GetMapping(value = "/{cardId}")
    @ApiOperation("详情")
    public AjaxResult getInfo(@PathVariable("cardId") Long cardId)
    {
        return success(dzCardsService.selectDzCardsByCardId(cardId));
    }

    /**
     * 新增学习卡
     */
    @PreAuthorize("@ss.hasPermi('dz:cards:add')")
    @Log(title = "学习卡", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DzCards dzCards)
    {
        return toAjax(dzCardsService.insertDzCards(dzCards));
    }

    /**
     * 修改学习卡
     */
    @PreAuthorize("@ss.hasPermi('dz:cards:edit')")
    @Log(title = "学习卡", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DzCards dzCards)
    {
        return toAjax(dzCardsService.updateDzCards(dzCards));
    }

    /**
     * 删除学习卡
     */
    @PreAuthorize("@ss.hasPermi('dz:cards:remove')")
    @Log(title = "学习卡", businessType = BusinessType.DELETE)
    @DeleteMapping("/{cardIds}")
    public AjaxResult remove(@PathVariable Long[] cardIds)
    {
        return toAjax(dzCardsService.deleteDzCardsByCardIds(cardIds));
    }

    @Log(title = "制卡", businessType = BusinessType.INSERT)
    @PostMapping("/issueCard")
    @ApiOperation("制卡")
    @PreAuthorize("@ss.hasPermi('dz:cards:issue')")
    public AjaxResult issueCard(@ApiParam("机构") Long institutionId, @ApiParam("卡类型") String type, @ApiParam("数量") Integer count) {
        dzCardsService.issueCard(institutionId, getCardType(institutionId, type), count);
        return AjaxResult.success();
    }

    @Log(title = "分配开卡", businessType = BusinessType.INSERT)
    @PostMapping("/assignCard")
    @ApiOperation("分配即开卡")
    @PreAuthorize("@ss.hasPermi('dz:cards:assign')")
    public AjaxResult assignCard(@ApiParam("代理商") @RequestParam Long agentId, @ApiParam("卡类型") String type, @ApiParam(value = "卡类型") Integer cardType,
                                 @ApiParam("开始号") @RequestParam String begin, @ApiParam("结束号") @RequestParam String end,
                                 @ApiParam("省份") @RequestParam(required = false) String location,
                                 @ApiParam("考生类型") @RequestParam(required = false) ExamType examType,
                                 @ApiParam("学校") @RequestParam(required = false) Long schoolId,
                                 @ApiParam("有效天数") @RequestParam(required = false) Integer days)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        DzAgent agent = agentService.selectDzAgentByAgentId(agentId);
        CardType ct = getCardType(agent.getDeptId(), null != cardType ? cardType.toString() : type);
        if(!CardType.Experience.getVal().equals(ct.getVal())) {
            days = null;
        }
        if(UserTypeEnum.Agent.getVal().equals(sysUser.getUserType())) { // 代理商分配
            if (!sysUser.getUserTypeId().equals(agent.getParentId())) {
                throw new ValidationException("只能分配给下级代理");
            }
            dzCardsService.assignCard(agent.getDeptId(), sysUser.getUserTypeId(), agentId, ct, begin, end, location, examType, schoolId, days);
        } else if(UserTypeEnum.Institution.getVal().equals(sysUser.getUserType())) { // 机构分配卡给自己的下级
            if (!sysUser.getDeptId().equals(agent.getDeptId())) {
                throw new ValidationException("只能分配给下级代理");
            }
            dzCardsService.assignCard(agent.getDeptId(), NumberUtils.isPositive(agent.getParentId()) ? agent.getParentId() : agentId, agentId, ct, begin, end, location, examType, schoolId, days);
        } else { // 平台指定, TODO 暂只支持二级代理
            dzCardsService.assignCard(agent.getDeptId(), NumberUtils.isPositive(agent.getParentId()) ? agent.getParentId() : agentId, agentId, ct, begin, end, location, examType, schoolId, days);
        }
        return AjaxResult.success();
    }

    @Log(title = "直接开卡", businessType = BusinessType.INSERT)
    @PostMapping("/openCard")
    @ApiOperation("直接开卡")
    public AjaxResult openCard(@ApiParam("代理商") Long agentId, @ApiParam("省份") String location, @ApiParam("学校") Long schoolId, @ApiParam("开始号") String begin, @ApiParam("结束号") String end,
                               @ApiParam("有效天数") @RequestParam(required = false) Integer days)
    {
        return AjaxResult.error("暂不支持，现在分配即开卡"); // success(dzCardsService.openCard(agentId, location, schoolId, begin, end, days));
    }

    @Log(title = "分配校区", businessType = BusinessType.INSERT)
    @PostMapping("/changeCampus")
    @ApiOperation("分配校区")
    @PreAuthorize("@ss.hasPermi('dz:cards:associateCampus')")
    public AjaxResult changeCampus(@ApiParam("校区") Long campusId,
                                   @ApiParam("校区班级") @RequestParam(required = false) Long campusClassId,
                                   @ApiParam("开始号") @RequestParam(required = false) String begin,
                                   @ApiParam("结束号") @RequestParam(required = false) String end,
                                   @ApiParam("卡片ID列表") @RequestParam(required = false) String cardIds) {
        // 如果cardIds不为空，使用cardIds方式；否则使用begin和end方式
        if (StringUtils.isNotBlank(cardIds)) {
            // 将cardIds字符串转换为Long数组
            String[] cardIdArray = cardIds.split(",");
            if (cardIdArray.length == 0) {
                throw new ValidationException("卡片ID列表不能为空");
            }
            Long[] cardIdLongArray = new Long[cardIdArray.length];
            for (int i = 0; i < cardIdArray.length; i++) {
                String cardIdStr = cardIdArray[i].trim();
                if (StringUtils.isBlank(cardIdStr)) {
                    throw new ValidationException("卡片ID不能为空");
                }
                try {
                    cardIdLongArray[i] = Long.parseLong(cardIdStr);
                } catch (NumberFormatException e) {
                    throw new ValidationException("卡片ID格式错误: " + cardIdStr);
                }
            }
            if (cardIdLongArray.length == 0) {
                throw new ValidationException("卡片ID列表不能为空");
            }
            return AjaxResult.success(dzCardsService.changeCampusByCardIds(campusId, campusClassId, cardIdLongArray));
        } else {
            // 使用begin和end方式，验证不能为空
            if (StringUtils.isBlank(begin)) {
                throw new ValidationException("开始卡号不能为空");
            }
            if (StringUtils.isBlank(end)) {
                throw new ValidationException("结束卡号不能为空");
            }
            return AjaxResult.success(dzCardsService.changeCampus(campusId, campusClassId, begin, end));
        }
    }

    @Log(title = "支付", businessType = BusinessType.UPDATE)
    @PostMapping("/change/pay")
    @ApiOperation("支付")
    public AjaxResult changePay(@ApiParam("卡ID") @RequestParam Long[] cardIds) {
        return changeCard(CardAction.Pay, cardIds, null);
    }
    @Log(title = "续费", businessType = BusinessType.UPDATE)
    @PostMapping("/change/renew")
    @ApiOperation("续费")
    public AjaxResult changeRenew(@ApiParam("卡ID") @RequestParam Long[] cardIds, @ApiParam("续费天数") @RequestParam(required = false) Integer days) {
        return changeCard(CardAction.Renew, cardIds, days);
    }
    @Log(title = "结算", businessType = BusinessType.UPDATE)
    @PostMapping("/change/settlement")
    @ApiOperation("结算")
    public AjaxResult changeSettlement(@ApiParam("卡ID") @RequestParam Long[] cardIds) {
        return changeCard(CardAction.Settlement, cardIds, null);
    }
    @Log(title = "重卡", businessType = BusinessType.UPDATE)
    @PostMapping("/change/reopen")
    @ApiOperation("重卡")
    public AjaxResult changeReopen(@ApiParam("卡ID") @RequestParam Long[] cardIds) {
        return changeCard(CardAction.ReOpen, cardIds, null);
    }
    @Log(title = "退费", businessType = BusinessType.UPDATE)
    @PostMapping("/change/refund")
    @ApiOperation("退费")
    public AjaxResult changeRefund(@ApiParam("卡ID") @RequestParam Long[] cardIds) {
        return changeCard(CardAction.Refund, cardIds, null);
    }
    @Log(title = "关卡", businessType = BusinessType.UPDATE)
    @PostMapping("/change/close")
    @ApiOperation("关卡")
    public AjaxResult changeClose(@ApiParam("卡ID") @RequestParam Long[] cardIds) {
        return changeCard(CardAction.Close, cardIds, null);
    }

    @Log(title = "修改卡", businessType = BusinessType.UPDATE)
    @PostMapping("/changeCard")
    @ApiOperation("修改卡 重卡/关卡/支付/续费/结算")
    public AjaxResult changeCard(@ApiParam("操作") @RequestParam CardAction action, @ApiParam("卡ID") @RequestParam Long[] cardIds, Integer days)
    {
        dzCardsService.changeCard(action, cardIds,days);
        if ((CardAction.Close.equals(action) || CardAction.Refund.equals(action)) && ArrayUtils.isNotEmpty(cardIds)) {
            sysLoginService.resetTokens(sysUserService.selectUserByCardIds(Arrays.asList(cardIds)));
        } else if ((CardAction.ReOpen.equals(action) || CardAction.Renew.equals(action)) && ArrayUtils.isNotEmpty(cardIds)) {
            List<SysUser> sysUsers = sysUserService.selectUserByCardIds(Arrays.asList(cardIds));
            for (SysUser user : sysUsers) {
                if(UserRegStatus.User.equals(user.getRegStatus())) {
                    SysUser upUser = new SysUser();
                    upUser.setUserId(user.getUserId());
                    upUser.setRegStatus(UserRegStatus.Student);
                    sysUserService.updateUserProfile(upUser);
                }
            }
            sysLoginService.resetTokens(sysUsers);
        }
        return AjaxResult.success();
    }

    @Log(title = "修改卡用户信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updateCardUser")
    @ApiOperation("修改卡用户信息")
    @PreAuthorize("@ss.hasPermi('dz:cards:updateuser')")
    public AjaxResult updateCardUser(@RequestBody CardUserBody cardUserBody) {
        sysRegisterService.improve(cardUserBody);
        return AjaxResult.success();
    }

    @GetMapping(value = "/cardUser/{cardId}")
    @ApiOperation("卡用户详情")
    @PreAuthorize("@ss.hasPermi('dz:cards:updateuser')")
    public AjaxResult getCardUser(@PathVariable("cardId") Long cardId)
    {
        CardUserBody cardUserBody = new CardUserBody();
        DzCards dzCards = dzCardsService.selectDzCardsByCardId(cardId);
        if(null == dzCards) {
            throw new ValidationException("卡号无效");
        }
        List<SysUser> sysUserList = sysUserService.selectUserByCardIds(Lists.newArrayList(cardId));
        if(CollectionUtils.isEmpty(sysUserList)) {
            throw new ValidationException("卡用户无效");
        }
        SysUser sysUser = sysUserList.get(0);
        BeanUtils.copyProperties(sysUser, cardUserBody, "password", "schoolId", "classId");
        cardUserBody.setMobile(sysUser.getPhonenumber());
        if (null != sysUser.getDirectedStudy()) {
            cardUserBody.setDirectionStudy(JSONArray.parse(sysUser.getDirectedStudy()));
        }
        BeanUtils.copyProperties(dzCards, cardUserBody, "password", "nickName", "location", "examType", "endYear", "examMajor", "examMajorName");
        cardUserBody.setCampusSchoolId(dzCards.getCampusId());
        return success(cardUserBody);
    }

    /**
     * 获取用户模拟考试列表
     */
    @GetMapping("/getUserSimulateList")
    @ApiOperation("获取用户模拟考试列表")
    @PreAuthorize("@ss.hasPermi('dz:cards:list')")
    public AjaxResult getUserSimulateList(@RequestParam("cardId") Long cardId)
    {
        // 根据cardId查询userId
        List<SysUser> sysUserList = sysUserService.selectUserByCardIds(Lists.newArrayList(cardId));
        if(CollectionUtils.isEmpty(sysUserList)) {
            return AjaxResult.success(new java.util.ArrayList<>());
        }
        SysUser sysUser = sysUserList.get(0);

        // 获取eval_counts字段
        String evalCounts = sysUser.getEvalCounts();
        if(StringUtils.isBlank(evalCounts)) {
            return AjaxResult.success(new java.util.ArrayList<>());
        }

        // 解析JSON
        JSONObject evalCountsJson = JSONObject.parseObject(evalCounts);
        if(evalCountsJson == null || evalCountsJson.isEmpty()) {
            return AjaxResult.success(new java.util.ArrayList<>());
        }

        // 获取所有subjectId
        java.util.Set<String> subjectIdSet = evalCountsJson.keySet();
        if(subjectIdSet.isEmpty()) {
            return AjaxResult.success(new java.util.ArrayList<>());
        }

        // 转换为Long数组
        Long[] subjectIds = subjectIdSet.stream()
                .filter(StringUtils::isNotBlank)
                .map(Long::parseLong)
                .toArray(Long[]::new);

        // 查询科目信息
        List<com.ruoyi.dz.domain.DzSubject> subjectList = dzSubjectService.selectDzSubjectBySubjectIds(subjectIds);
        java.util.Map<Long, String> subjectNameMap = subjectList.stream()
                .collect(java.util.stream.Collectors.toMap(
                    com.ruoyi.dz.domain.DzSubject::getSubjectId,
                    com.ruoyi.dz.domain.DzSubject::getSubjectName,
                    (v1, v2) -> v1
                ));

        // 构建返回结果
        List<java.util.Map<String, Object>> resultList = new java.util.ArrayList<>();
        for(String subjectIdStr : subjectIdSet) {
            try {
                Long subjectId = Long.parseLong(subjectIdStr);
                Integer count = evalCountsJson.getInteger(subjectIdStr);
                if(count == null) {
                    count = 0;
                }

                java.util.Map<String, Object> item = new java.util.HashMap<>();
                item.put("subjectId", subjectId);
                item.put("subjectName", subjectNameMap.getOrDefault(subjectId, "未知科目"));
                item.put("count", count);
                item.put("userId", sysUser.getUserId());
                resultList.add(item);
            } catch(NumberFormatException e) {
                // 忽略无效的subjectId
                continue;
            }
        }

        // 按subjectId排序
        resultList.sort((a, b) -> {
            Long idA = (Long) a.get("subjectId");
            Long idB = (Long) b.get("subjectId");
            return idA.compareTo(idB);
        });

        return AjaxResult.success(resultList);
    }

    /**
     * 更新用户模拟考试次数
     */
    @PostMapping("/updateUserEvalCounts")
    @ApiOperation("更新用户模拟考试次数")
    @PreAuthorize("@ss.hasPermi('dz:cards:list')")
    public AjaxResult updateUserEvalCounts(@RequestBody Map<String, Object> params)
    {
        // 参数验证
        if (params == null || !params.containsKey("userId") || params.get("userId") == null) {
            throw new ValidationException("用户ID不能为空");
        }
        if (!params.containsKey("subjectId") || params.get("subjectId") == null) {
            throw new ValidationException("科目ID不能为空");
        }
        if (!params.containsKey("count") || params.get("count") == null) {
            throw new ValidationException("次数不能为空");
        }

        // 获取参数
        Long userId = Long.valueOf(params.get("userId").toString());
        Long subjectId = Long.valueOf(params.get("subjectId").toString());
        Integer count = Integer.valueOf(params.get("count").toString());

        // 根据userId查询用户
        SysUser sysUser = sysUserService.selectUserById(userId);
        if(sysUser == null) {
            throw new ValidationException("用户不存在");
        }

        // 获取eval_counts字段
        String evalCounts = sysUser.getEvalCounts();
        JSONObject evalCountsJson;

        if(StringUtils.isBlank(evalCounts)) {
            // 如果为空，创建新的JSON对象
            evalCountsJson = new JSONObject();
        } else {
            // 解析JSON
            evalCountsJson = JSONObject.parseObject(evalCounts);
            if(evalCountsJson == null) {
                evalCountsJson = new JSONObject();
            }
        }

        // 更新对应subjectId的值
        evalCountsJson.put(String.valueOf(subjectId), count);

        // 更新到数据库（使用updateUserInfo只更新基本信息，不影响角色和岗位）
        sysUser.setEvalCounts(evalCountsJson.toJSONString());
        sysUserService.updateUserInfo(sysUser);

        return AjaxResult.success();
    }

    /**
     * 统计学习卡数据
     */
    @PreAuthorize("@ss.hasPermi('dz:cards:list')")
    @GetMapping("/statistics")
    @ApiOperation("统计学习卡数据")
    public AjaxResult statistics(@RequestParam(required = false) Long deptId,
                                  @RequestParam(required = false) Long agentId,
                                  @RequestParam(required = false) String openTimeBegin,
                                  @RequestParam(required = false) String openTimeEnd)
    {
        java.util.Map<String, Object> params = new java.util.HashMap<>();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Long campusId = null;
        Long teacherId = null;
        if (UserTypeEnum.isAgent(sysUser.getUserType())) {
            agentId = sysUser.getUserTypeId();
        } else if (UserTypeEnum.isSchool(sysUser.getUserType())) {
            campusId = sysUser.getUserTypeId();
        } else if (UserTypeEnum.isTeacher(sysUser.getUserType())) {
            teacherId = sysUser.getUserTypeId();
        } else if(!UserTypeEnum.isSys(sysUser.getUserType())) {
            deptId = sysUser.getDeptId();
        }
        if (deptId != null) {
            params.put("deptId", deptId);
        }
        if (agentId != null) {
            params.put("agentId", agentId);
        }
        if (campusId != null) {
            params.put("campusId", campusId);
        }
        if (teacherId != null) {
            params.put("teacherId", teacherId);
        }
        if (openTimeBegin != null && !openTimeBegin.isEmpty()) {
            params.put("openTimeBegin", openTimeBegin);
        }
        if (openTimeEnd != null && !openTimeEnd.isEmpty()) {
            params.put("openTimeEnd", openTimeEnd);
        }
        List<com.ruoyi.dz.dto.CardStatisticsDTO> list = dzCardsService.statisticCards(params);
        return success(list);
    }

    private CardType getCardType(Long institutionId, String type) {
        if(!NumberUtils.isNumeric(type)) {
            return CardType.valueOf(type);
        }
        Integer cardType = Integer.parseInt(type);
        if(cardType == 9) {
            return CardType.Experience;
        } else if(cardType == 7) {
            return CardType.ECard;
        }
        return (null == institutionId || institutionId.equals(101L)) ? CardType.Platform : CardType.Dept;
    }

    /**
     * 统计详情 - 根据统计类型查询学习卡列表
     */
    @PreAuthorize("@ss.hasPermi('dz:cards:list')")
    @GetMapping("/statisticsDetail")
    @ApiOperation("统计详情 - 查询学习卡列表")
    public TableDataInfo statisticsDetail(@RequestParam String statisticsType,
                                          @RequestParam Long agentId)
    {
        DzCards dzCards = new DzCards();
        dzCards.setStatisticsType(statisticsType);
        dzCards.setAgentId(agentId);
        startPage();
        List<DzCards> list = dzCardsService.selectDzCardsList(prepare(dzCards));
        return getDataTable(list);
    }

}
