package com.ruoyi.web.controller.dz;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ValidationException;

import cn.hutool.core.util.NumberUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.ExamType;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.dz.domain.DzAgent;
import com.ruoyi.dz.service.IDzAgentService;
import com.ruoyi.enums.CardAction;
import com.ruoyi.enums.CardType;
import com.ruoyi.enums.UserTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
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.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;

    /**
     * 查询学习卡列表
     */
    @PreAuthorize("@ss.hasPermi('dz:cards:list')")
    @GetMapping("/list")
    @ApiOperation("列表")
    public TableDataInfo list(DzCards dzCards)
    {
        String userType = SecurityUtils.getLoginUser().getUser().getUserType();
        if(UserTypeEnum.isInstitution(userType)&&null==dzCards.getDeptId()){
            dzCards.setDeptId(SecurityUtils.getDeptId());
        }
        if((UserTypeEnum.isAgent(userType)||UserTypeEnum.isTeacher(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());
                }
            }
        }

        startPage();
        List<DzCards> list = dzCardsService.selectDzCardsList(dzCards);
        return getDataTable(list);
    }

    /**
     * 导出学习卡列表
     */
    @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(dzCards);
        ExcelUtil<DzCards> util = new ExcelUtil<DzCards>(DzCards.class);
        util.exportExcel(response, list, "学习卡数据");
    }

    /**
     * 获取学习卡详细信息
     */
    @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("制卡")
    public AjaxResult issueCard(@ApiParam("机构") Long institutionId, @ApiParam("卡类型") CardType type, @ApiParam("数量") Integer count)
    {
        dzCardsService.issueCard(institutionId, type, count);
        return AjaxResult.success();
    }

    @Log(title = "分配卡", businessType = BusinessType.INSERT)
    @PostMapping("/assignCard")
    @ApiOperation("分配卡")
    public AjaxResult assignCard(@ApiParam("代理商") @RequestParam Long agentId, @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)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        DzAgent agent = agentService.selectDzAgentByAgentId(agentId);
        if(UserTypeEnum.Agent.getVal().equals(sysUser.getUserType())) { // 代理商分配
            if (!sysUser.getUserTypeId().equals(agent.getParentId())) {
                throw new ValidationException("只能分配给下级代理");
            }
            dzCardsService.assignCard(sysUser.getUserTypeId(), agentId, begin, end, location, examType, schoolId);
        } else if(UserTypeEnum.Institution.getVal().equals(sysUser.getUserType())) { // 机构分配卡给自己的下级
            if (!sysUser.getDeptId().equals(agent.getDeptId())) {
                throw new ValidationException("只能分配给下级代理");
            }
            dzCardsService.assignCard(NumberUtils.isPositive(agent.getParentId()) ? agent.getParentId() : agentId, agentId, begin, end, location, examType, schoolId);
        } else { // 平台指定, TODO 暂只支持二级代理
            dzCardsService.assignCard(NumberUtils.isPositive(agent.getParentId()) ? agent.getParentId() : agentId, agentId, begin, end, location, examType, schoolId);
        }
        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)
    {
        return AjaxResult.success(dzCardsService.openCard(agentId, location, schoolId, begin, end));
    }

    @Log(title = "分配校区", businessType = BusinessType.INSERT)
    @PostMapping("/changeCampus")
    @ApiOperation("分配校区")
    public AjaxResult changeCampus(@ApiParam("校区") Long campusId, @ApiParam("开始号") String begin, @ApiParam("结束号") String end)
    {
        return AjaxResult.success(dzCardsService.changeCampus(campusId, begin, end));
    }

    @Log(title = "修改卡", businessType = BusinessType.UPDATE)
    @PostMapping("/changeCard")
    @ApiOperation("修改卡 重卡/关卡/支付")
    public AjaxResult changeCard(@ApiParam("操作") @RequestParam CardAction action, @ApiParam("卡ID") @RequestParam Long[] cardIds)
    {
        dzCardsService.changeCard(action, cardIds);
        return AjaxResult.success();
    }
}
