package com.xjrsoft.module.courseTable.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
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.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.activity.dto.ChangeStatusDto;
import com.xjrsoft.module.courseTable.dto.UserEnrollDto;
import com.xjrsoft.module.base.entity.BaseClass;
import com.xjrsoft.module.base.service.IBaseClassService;
import com.xjrsoft.module.concat.service.IXjrUserService;
import com.xjrsoft.module.courseTable.dto.AddSecondCourseDto;
import com.xjrsoft.module.courseTable.dto.SecondCourseEnrollPageDto;
import com.xjrsoft.module.courseTable.dto.SecondCoursePageDto;
import com.xjrsoft.module.courseTable.dto.UpdateSecondCourseDto;
import com.xjrsoft.module.courseTable.entity.SecondCourse;
import com.xjrsoft.module.courseTable.service.ISecondCourseService;
import com.xjrsoft.module.courseTable.vo.SecondCourseEnrollExcelVo;
import com.xjrsoft.module.courseTable.vo.SecondCourseEnrollRangeVo;
import com.xjrsoft.module.courseTable.vo.SecondCourseEnrollVo;
import com.xjrsoft.module.courseTable.vo.SecondCoursePageVo;
import com.xjrsoft.module.courseTable.vo.SecondCourseVo;
import com.xjrsoft.module.organization.entity.Department;
import com.xjrsoft.module.organization.service.IDepartmentService;
import com.xjrsoft.module.system.entity.File;
import com.xjrsoft.module.system.service.IFileService;
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.RequestParam;
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.List;

/**
* @title: 第二课堂
* @Author dzx
* @Date: 2024-07-29
* @Version 1.0
*/
@RestController
@RequestMapping("/courseTable" + "/secondCourse")
@Api(value = "/courseTable"  + "/secondCourse",tags = "第二课堂代码")
@AllArgsConstructor
public class SecondCourseController {


    private final ISecondCourseService secondCourseService;
    private final IBaseClassService classService;
    private final IDepartmentService departmentService;
    private final IXjrUserService xjrUserService;
    private final IFileService fileService;

    @GetMapping(value = "/page")
    @ApiOperation(value="第二课堂列表(分页)")
    @SaCheckPermission("secondcourse:detail")
    public RT<PageOutput<SecondCoursePageVo>> page(@Valid SecondCoursePageDto dto){
        if(dto.getUserId() == null){
            dto.setUserId(StpUtil.getLoginIdAsLong());
        }
        Page<SecondCoursePageVo> page = secondCourseService.getPage(new Page<>(dto.getLimit(), dto.getSize()), dto);
        for (SecondCoursePageVo record : page.getRecords()) {
            if(record.getEnrollStatus() > 0){
                record.setEnrollStatus(1);
            }
            if(record.getCoverId() != null){
                File file = fileService.getOne(
                        new QueryWrapper<File>().lambda()
                                .select(File::getId)
                                .select(File.class, x -> VoToColumnUtil.fieldsToColumns(File.class).contains(x.getProperty()))
                                .eq(File::getFolderId, record.getCoverId())
                );
                record.setCoverUrl(file.getFileUrl());
            }
        }
        PageOutput<SecondCoursePageVo> pageOutput = ConventPage.getPageOutput(page, SecondCoursePageVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value="根据id查询第二课堂信息")
    @SaCheckPermission("secondcourse:detail")
    public RT<SecondCourseVo> info(@RequestParam Long id){
        SecondCourse secondCourse = secondCourseService.getByIdDeep(id);
        if (secondCourse == null) {
           return RT.error("找不到此数据！");
        }
        SecondCourseVo courseVo = BeanUtil.toBean(secondCourse, SecondCourseVo.class);
        if(secondCourse.getEnrollRange() != null && !"".equals(secondCourse.getEnrollRange())){
            JsonParser parser = new JsonParser();
            JsonArray asJsonArray = parser.parse(secondCourse.getEnrollRange()).getAsJsonArray();
            List<SecondCourseEnrollRangeVo> list = new ArrayList<>();
            for (JsonElement jsonElement : asJsonArray) {
                SecondCourseEnrollRangeVo relationDto = JSONUtil.toBean(jsonElement.getAsJsonObject().toString(), SecondCourseEnrollRangeVo.class);
                if(relationDto.getUserId() != null){
                    XjrUser xjrUser = xjrUserService.getById(relationDto.getUserId());
                    if(xjrUser != null){
                        relationDto.setName(xjrUser.getName());
                    }
                }else if(relationDto.getDeptId() != null){
                    Department department = departmentService.getById(relationDto.getDeptId());
                    if(department != null){
                        relationDto.setName(department.getName());
                    }

                }else if(relationDto.getClassId() != null){
                    BaseClass aClass = classService.getById(relationDto.getClassId());
                    if(aClass != null){
                        relationDto.setName(aClass.getName());
                    }
                }
                list.add(relationDto);
            }
            courseVo.setSecondCourseEnrollRangeList(list);
        }
        if(secondCourse.getCoverId() != null){
            File file = fileService.getOne(
                    new QueryWrapper<File>().lambda()
                            .select(File::getId)
                            .select(File.class, x -> VoToColumnUtil.fieldsToColumns(File.class).contains(x.getProperty()))
                            .eq(File::getFolderId, secondCourse.getCoverId())
            );
            courseVo.setCoverUrl(file.getFileUrl());
        }

        Integer enrollCount = secondCourseService.getEnrollCount(secondCourse.getId());
        courseVo.setEnrollCount(enrollCount);
        return RT.ok(courseVo);
    }


    @PostMapping
    @ApiOperation(value = "新增第二课堂")
    @SaCheckPermission("secondcourse:add")
    public RT<Boolean> add(@Valid @RequestBody AddSecondCourseDto dto){
        boolean isSuccess = secondCourseService.add(dto);
        return RT.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改第二课堂")
    @SaCheckPermission("secondcourse:edit")
    public RT<Boolean> update(@Valid @RequestBody UpdateSecondCourseDto dto){

        return RT.ok(secondCourseService.update(dto));
    }

    @DeleteMapping
    @ApiOperation(value = "删除第二课堂")
    @SaCheckPermission("secondcourse:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids){
        return RT.ok(secondCourseService.delete(ids));
    }

    @PostMapping(value = "/change-status")
    @ApiOperation(value="修改状态")
    @SaCheckPermission("officebuild:detail")
    public RT<Boolean> changeStatus(@Valid @RequestBody ChangeStatusDto dto) throws Exception {
        SecondCourse secondCourse = secondCourseService.getById(dto.getId());
        if(secondCourse == null){
            throw new MyException("未能找到数据");
        }
        secondCourse.setStatus(dto.getStatus());
        secondCourseService.updateById(secondCourse);
        return RT.ok(true);
    }

    @GetMapping(value = "/enroll-page")
    @ApiOperation(value="报名表")
    @SaCheckPermission("secondcourse:detail")
    public RT<PageOutput<SecondCourseEnrollVo>> enrollPage(@Valid SecondCourseEnrollPageDto dto){
        Page<SecondCourseEnrollVo> enrollPage = secondCourseService.getEnrollPage(new Page<>(dto.getLimit(), dto.getSize()), dto);
        for (SecondCourseEnrollVo record : enrollPage.getRecords()) {
            if(record.getStudentId() != null){
                record.setRoleId(3L);
            }else if(record.getTeacherId() != null){
                record.setRoleId(2L);
            }
        }

        PageOutput<SecondCourseEnrollVo> pageOutput = ConventPage.getPageOutput(enrollPage, SecondCourseEnrollVo.class);
        return RT.ok(pageOutput);
    }

    @PostMapping("/export-query")
    @ApiOperation(value = "导出列表")
    public ResponseEntity<byte[]> exportData(@Valid @RequestBody SecondCourseEnrollPageDto dto) {
        List<SecondCourseEnrollVo> enrollList = secondCourseService.getEnrollList(dto);
        List<SecondCourseEnrollExcelVo> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        for (SecondCourseEnrollVo listVo : enrollList) {
            list.add(new SecondCourseEnrollExcelVo(){{
                setName(listVo.getName());
                setMobile(listVo.getMobile());
                if(listVo.getTeacherId() != null){
                    setRoleType("教师");
                }
                if(listVo.getStudentId() != null){
                    setRoleType("学生");
                }
                setUserName(listVo.getUserName());
                if(listVo.getCreateDate() != null){
                    setCreateDate(sdf.format(listVo.getCreateDate()));
                }
            }});
        }

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

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


    @PostMapping(value = "/enroll")
    @ApiOperation(value="报名")
    @SaCheckPermission("secondcourse:detail")
    public RT<Boolean> enroll(@Valid @RequestBody UserEnrollDto dto){
        Boolean enroll = secondCourseService.enroll(dto);
        return RT.ok(enroll);
    }

    @GetMapping(value = "/my-enroll-page")
    @ApiOperation(value="我的报名记录(分页)")
    @SaCheckPermission("secondcourse:detail")
    public RT<PageOutput<SecondCoursePageVo>> myEnrollList(@Valid SecondCoursePageDto dto){
        if(dto.getUserId() == null){
            dto.setUserId(StpUtil.getLoginIdAsLong());
        }

        Page<SecondCoursePageVo> page = secondCourseService.getMyPage(new Page<>(dto.getLimit(), dto.getSize()), dto);
        PageOutput<SecondCoursePageVo> pageOutput = ConventPage.getPageOutput(page, SecondCoursePageVo.class);
        return RT.ok(pageOutput);
    }

}