package com.ruoyi.web.controller.dz;

import java.util.Arrays;
import java.util.List;
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.service.IDzAgentService;
import com.ruoyi.enums.CardAction;
import com.ruoyi.enums.CardType;
import com.ruoyi.enums.UserTypeEnum;
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.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;

    /**
     * 查询学习卡列表
     */
    @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);
    }

    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("校区班级") Long campusClassId, @ApiParam("开始号") String begin, @ApiParam("结束号") String end) {
        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);
    }
    @Log(title = "续费", businessType = BusinessType.UPDATE)
    @PostMapping("/change/renew")
    @ApiOperation("续费")
    public AjaxResult changeRenew(@ApiParam("卡ID") @RequestParam Long[] cardIds) {
        return changeCard(CardAction.Renew, cardIds);
    }
    @Log(title = "结算", businessType = BusinessType.UPDATE)
    @PostMapping("/change/settlement")
    @ApiOperation("结算")
    public AjaxResult changeSettlement(@ApiParam("卡ID") @RequestParam Long[] cardIds) {
        return changeCard(CardAction.Settlement, cardIds);
    }
    @Log(title = "重卡", businessType = BusinessType.UPDATE)
    @PostMapping("/change/reopen")
    @ApiOperation("重卡")
    public AjaxResult changeReopen(@ApiParam("卡ID") @RequestParam Long[] cardIds) {
        return changeCard(CardAction.ReOpen, cardIds);
    }
    @Log(title = "退费", businessType = BusinessType.UPDATE)
    @PostMapping("/change/refund")
    @ApiOperation("退费")
    public AjaxResult changeRefund(@ApiParam("卡ID") @RequestParam Long[] cardIds) {
        return changeCard(CardAction.Refund, cardIds);
    }
    @Log(title = "关卡", businessType = BusinessType.UPDATE)
    @PostMapping("/change/close")
    @ApiOperation("关卡")
    public AjaxResult changeClose(@ApiParam("卡ID") @RequestParam Long[] cardIds) {
        return changeCard(CardAction.Close, cardIds);
    }

    @Log(title = "修改卡", businessType = BusinessType.UPDATE)
    @PostMapping("/changeCard")
    @ApiOperation("修改卡 重卡/关卡/支付/续费/结算")
    public AjaxResult changeCard(@ApiParam("操作") @RequestParam CardAction action, @ApiParam("卡ID") @RequestParam Long[] cardIds)
    {
        dzCardsService.changeCard(action, cardIds);
        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) && 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");
        cardUserBody.setCampusSchoolId(dzCards.getCampusId());
        return success(cardUserBody);
    }

    /**
     * 统计学习卡数据
     */
    @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);
        }
        if(Integer.parseInt(type) == 9) {
            return CardType.Experience;
        }
        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);
    }

}
