package com.xjrsoft.module.activity.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.module.activity.dto.ActivityEnrollExportDto;
import com.xjrsoft.module.activity.dto.ActivityEnrollPageDto;
import com.xjrsoft.module.activity.dto.AddActivityEnrollDto;
import com.xjrsoft.module.activity.dto.ChangeStatusDto;
import com.xjrsoft.module.activity.dto.UpdateActivityInfoDto;
import com.xjrsoft.module.activity.dto.UserEnrollDto;
import com.xjrsoft.module.activity.entity.ActivityEnroll;
import com.xjrsoft.module.activity.service.IActivityEnrollService;
import com.xjrsoft.module.activity.vo.ActivityEnrollExcelVo;
import com.xjrsoft.module.activity.vo.ActivityEnrollPageVo;
import com.xjrsoft.module.concat.service.IXjrUserService;
import com.xjrsoft.module.teacher.entity.XjrUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @title: 活动信息
* @Author dzx
* @Date: 2024-07-19
* @Version 1.0
*/
@RestController
@RequestMapping("/activity" + "/activityEnroll")
@Api(value = "/activity"  + "/activityEnroll",tags = "活动登记代码")
@AllArgsConstructor
public class ActivityEnrollController {

    private final IXjrUserService xjrUserService;
    private final IActivityEnrollService activityEnrollService;


    @GetMapping(value = "/page")
    @ApiOperation(value="活动信息列表(分页)")
    @SaCheckPermission("activityinfo:detail")
    public RT<PageOutput<ActivityEnrollPageVo>> page(@Valid ActivityEnrollPageDto dto){

        Page<ActivityEnrollPageVo> page = activityEnrollService.getPage(new Page<>(dto.getLimit(), dto.getSize()), dto);
        PageOutput<ActivityEnrollPageVo> pageOutput = ConventPage.getPageOutput(page, ActivityEnrollPageVo.class);
        for (ActivityEnrollPageVo item : pageOutput.getList()) {
            if(item.getStudentId() != null){
                item.setRoleId(3L);
            }else if(item.getTeacherId() != null){
                item.setRoleId(2L);
            }
        }
        return RT.ok(pageOutput);
    }

    @PostMapping(value = "/change-status")
    @ApiOperation(value="修改状态")
    @SaCheckPermission("officebuild:detail")
    public RT<Boolean> changeStatus(@Valid @RequestBody List<ChangeStatusDto> dtoList) throws Exception {
        List<ActivityEnroll> enrollList = new ArrayList<>();
        for (ChangeStatusDto dto : dtoList) {
            ActivityEnroll enroll = activityEnrollService.getById(dto.getId());
            enroll.setStatus(dto.getStatus());
            enrollList.add(enroll);
        }

        activityEnrollService.updateBatchById(enrollList);
        return RT.ok(true);
    }


    @PostMapping
    @ApiOperation(value = "新增活动信息")
    @SaCheckPermission("activityinfo:add")
    public RT<Boolean> add(@Valid @RequestBody AddActivityEnrollDto dto){

        boolean isSuccess = activityEnrollService.save(dto);
        return RT.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改活动信息")
    @SaCheckPermission("activityinfo:edit")
    public RT<Boolean> update(@Valid @RequestBody UpdateActivityInfoDto dto){

        ActivityEnroll activityInfo = BeanUtil.toBean(dto, ActivityEnroll.class);
        return RT.ok(activityEnrollService.update(activityInfo));

    }

    @DeleteMapping
    @ApiOperation(value = "删除活动信息")
    @SaCheckPermission("activityinfo:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids){
        return RT.ok(activityEnrollService.delete(ids));
    }


    @PostMapping("/export-query")
    @ApiOperation(value = "导出列表")
    public ResponseEntity<byte[]> exportData(@Valid @RequestBody ActivityEnrollExportDto dto) {
        List<ActivityEnrollPageVo> listVos = activityEnrollService.getList(dto);
        List<ActivityEnrollExcelVo> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        for (ActivityEnrollPageVo listVo : listVos) {
            list.add(new ActivityEnrollExcelVo(){{
                setName(listVo.getName());
                setMobile(listVo.getMobile());
                if(listVo.getTeacherId() != null){
                    setRoleType("教师");
                }
                if(listVo.getStudentId() != null){
                    setRoleType("学生");
                }
                if(listVo.getStatus() == 0){
                    setStatus("待确认");
                }else if(listVo.getStatus() == 1){
                    setStatus("未参与");
                }else if(listVo.getStatus() == 2){
                    setStatus("已参与");
                }
                setUserName(listVo.getUserName());
                setCreateDate(sdf.format(listVo.getCreateDate()));
            }});
        }

        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, ActivityEnrollExcelVo.class).automaticMergeHead(false).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(list);

        return RT.fileStream(bot.toByteArray(), "enroll" + ExcelTypeEnum.XLSX.getValue());
    }

    @PostMapping(value = "/enroll")
    @ApiOperation(value="报名")
    @SaCheckPermission("activityinfo:detail")
    public RT<Boolean> enroll(@Valid @RequestBody UserEnrollDto dto){
        List<ActivityEnroll> enrollList = activityEnrollService.list(
                new QueryWrapper<ActivityEnroll>().lambda()
                        .eq(ActivityEnroll::getUserId, StpUtil.getLoginIdAsLong())
                        .eq(ActivityEnroll::getActivityInfoId, dto.getActivityInfoId())
        );
        if(!enrollList.isEmpty()){
            return RT.error("已报名，无需重复报名");
        }
        ActivityEnroll activityEnroll = new ActivityEnroll() {{
            setUserId(StpUtil.getLoginIdAsLong());
            setCreateDate(new Date());
            setActivityInfoId(Long.parseLong(dto.getActivityInfoId()));
        }};
        boolean save = activityEnrollService.save(activityEnroll);

        XjrUser xjrUser = xjrUserService.getById(StpUtil.getLoginIdAsLong());
        if(StrUtil.isNotEmpty(dto.getMobile()) && !dto.getMobile().equals(xjrUser.getMobile())){
            xjrUser.setMobile(dto.getMobile());
            xjrUserService.updateById(xjrUser);
        }

        return RT.ok(save);
    }

}