package com.xjrsoft.module.classtime.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.classtime.dto.AddClassTimeStatisticsDto;
import com.xjrsoft.module.classtime.dto.ClassTimeStatisticsPageDto;
import com.xjrsoft.module.classtime.dto.RefreshStatisticsDto;
import com.xjrsoft.module.classtime.dto.UpdateClassTimeStatisticsDto;
import com.xjrsoft.module.classtime.entity.ClassTimeStatistics;
import com.xjrsoft.module.classtime.entity.ClassTimeStatisticsRecord;
import com.xjrsoft.module.classtime.entity.ClassTimeStatisticsSet;
import com.xjrsoft.module.classtime.service.IClassTimeStatisticsRecordService;
import com.xjrsoft.module.classtime.service.IClassTimeStatisticsService;
import com.xjrsoft.module.classtime.service.IClassTimeStatisticsSetService;
import com.xjrsoft.module.classtime.vo.ClassTimeStatisticsPageVo;
import com.xjrsoft.module.classtime.vo.ClassTimeStatisticsRecordVo;
import com.xjrsoft.module.classtime.vo.ClassTimeStatisticsVo;
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.IOException;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
* @title: 课时统计
* @Author dzx
* @Date: 2024-09-26
* @Version 1.0
*/
@RestController
@RequestMapping("/classtime" + "/classTimeStatistics")
@Api(value = "/classtime"  + "/classTimeStatistics",tags = "课时统计代码")
@AllArgsConstructor
public class ClassTimeStatisticsController {

    private final IClassTimeStatisticsSetService statisticsSetService;
    private final IClassTimeStatisticsService classTimeStatisticsService;
    private final IClassTimeStatisticsRecordService recordService;

    @GetMapping(value = "/page")
    @ApiOperation(value="课时统计列表(分页)")
    @SaCheckPermission("classtimestatistics:detail")
    public RT<PageOutput<ClassTimeStatisticsPageVo>> page(@Valid ClassTimeStatisticsPageDto dto){

        LambdaQueryWrapper<ClassTimeStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .orderByDesc(ClassTimeStatistics::getId)
                .eq(dto.getYear() != null, ClassTimeStatistics::getYear, dto.getYear())
                .eq(dto.getMonth() != null, ClassTimeStatistics::getMonth, dto.getMonth())
                .select(ClassTimeStatistics.class,x -> VoToColumnUtil.fieldsToColumns(ClassTimeStatisticsPageVo.class).contains(x.getProperty()));
        IPage<ClassTimeStatistics> page = classTimeStatisticsService.page(ConventPage.getPage(dto), queryWrapper);
        PageOutput<ClassTimeStatisticsPageVo> pageOutput = ConventPage.getPageOutput(page, ClassTimeStatisticsPageVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value="根据id查询课时统计信息")
    @SaCheckPermission("classtimestatistics:detail")
    public RT<ClassTimeStatisticsVo> info(@RequestParam Long id){
        ClassTimeStatistics classTimeStatistics = classTimeStatisticsService.getByIdDeep(id);
        if (classTimeStatistics == null) {
           return RT.error("找不到此数据！");
        }
        return RT.ok(BeanUtil.toBean(classTimeStatistics, ClassTimeStatisticsVo.class));
    }


    @PostMapping
    @ApiOperation(value = "新增课时统计")
    @SaCheckPermission("classtimestatistics:add")
    public RT<Boolean> add(@Valid @RequestBody AddClassTimeStatisticsDto dto){
        boolean isSuccess = classTimeStatisticsService.add(dto);
        return RT.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改课时统计")
    @SaCheckPermission("classtimestatistics:edit")
    public RT<Boolean> update(@Valid @RequestBody UpdateClassTimeStatisticsDto dto){

        ClassTimeStatistics classTimeStatistics = BeanUtil.toBean(dto, ClassTimeStatistics.class);
        return RT.ok(classTimeStatisticsService.update(classTimeStatistics));
    }

    @DeleteMapping
    @ApiOperation(value = "删除课时统计")
    @SaCheckPermission("classtimestatistics:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids){
        return RT.ok(classTimeStatisticsService.delete(ids));

    }

    @PostMapping(value = "/change-status")
    @ApiOperation(value="修改状态")
    @SaCheckPermission("classtimestatistics:detail")
    public RT<Boolean> changeStatus(@Valid @RequestBody ChangeStatusDto dto) throws Exception {
        ClassTimeStatistics statistics = classTimeStatisticsService.getById(dto.getId());
        if(statistics == null){
            throw new MyException("未能查到数据");
        }
        statistics.setStatus(dto.getStatus());
        classTimeStatisticsService.updateById(statistics);
        if(dto.getStatus() != null && dto.getStatus() == 3){
            classTimeStatisticsService.lockData(dto.getId());
        }
        return RT.ok(true);
    }

    @GetMapping(value = "/last-date")
    @ApiOperation(value="查询最新统计的结束日期")
    @SaCheckPermission("classtimestatisticsset:detail")
    public RT<LocalDate> lastInfo(){
        List<ClassTimeStatistics> list = classTimeStatisticsService.list(
                new QueryWrapper<ClassTimeStatistics>().lambda().orderByDesc(ClassTimeStatistics::getEndDate)
        );
        if (list.isEmpty()) {
            return RT.ok();
        }
        ClassTimeStatistics result = list.get(0);
        return RT.ok(result.getEndDate());
    }

    @PostMapping("/refresh-statistics")
    @ApiOperation(value = "刷新课时统计")
    @SaCheckPermission("classtimestatistics:detail")
    public RT<Boolean> refreshStatistics(@Valid @RequestBody RefreshStatisticsDto dto){

        ClassTimeStatistics classTimeStatistics = classTimeStatisticsService.getById(dto.getId());
        classTimeStatistics.setStatus(0);
        classTimeStatistics.setModifyDate(new Date());

        //查询最新权重并保存到统计中
        Integer category = 1;
        List<ClassTimeStatisticsSet> list = statisticsSetService.list(
                new QueryWrapper<ClassTimeStatisticsSet>().lambda()
                        .eq(ClassTimeStatisticsSet::getCategory, category)
                        .orderByDesc(ClassTimeStatisticsSet::getCreateDate)
        );
        if(list.isEmpty()){
            throw new MyException("请先设置权重并进行保存");
        }
        classTimeStatistics.setWeightSetJson(list.get(0).getJsonContent());

        //查询最新费用并保存到统计中
        category = 2;
        list = statisticsSetService.list(
                new QueryWrapper<ClassTimeStatisticsSet>().lambda()
                        .eq(ClassTimeStatisticsSet::getCategory, category)
                        .orderByDesc(ClassTimeStatisticsSet::getCreateDate)
        );
        if(list.isEmpty()){
            throw new MyException("请先设置费用并进行保存");
        }
        classTimeStatistics.setCostSetJson(list.get(0).getJsonContent());
        Boolean aBoolean = classTimeStatisticsService.updateById(classTimeStatistics);

//        CompletableFuture.runAsync(() -> {
//            classTimeStatisticsService.refreshRecord(classTimeStatistics);
//        });
        classTimeStatisticsService.refreshRecord(classTimeStatistics);

        return RT.ok(aBoolean);
    }


    @GetMapping(value = "/record-list")
    @ApiOperation(value="课时统计详情列表")
    @SaCheckPermission("classtimestatistics:detail")
    public RT<List<ClassTimeStatisticsRecordVo>> recordPage(@Valid RefreshStatisticsDto dto){
        List<ClassTimeStatisticsRecordVo> recordList = classTimeStatisticsService.getRecordList(dto.getId());
        return RT.ok(recordList);
    }

    @GetMapping(value = "/record-detail-info")
    @ApiOperation(value="课时统计详情明细")
    @SaCheckPermission("classtimestatistics:detail")
    public RT<String> recordDetailInfo(@Valid RefreshStatisticsDto dto){
        ClassTimeStatisticsRecord record = recordService.getById(dto.getId());
        return RT.ok(record.getAllClassTimeData());
    }

    @PostMapping(value = "/record-detail-export-query")
    @ApiOperation(value="课时统计详情明细-导出")
    @SaCheckPermission("classtimestatistics:detail")
    public ResponseEntity<byte[]> recordDetailExportQuery(@Valid @RequestBody RefreshStatisticsDto dto) throws IOException {
        String fileName = "recordDetailExportQuery" + ExcelTypeEnum.XLSX.getValue();
        byte[] bytes = recordService.recordDetailExportQuery(dto.getId());
        return RT.fileStream(bytes, fileName);
    }


    @PostMapping(value = "/record-export-query")
    @ApiOperation(value="课时统计详情导出")
    @SaCheckPermission("classtimestatistics:detail")
    public ResponseEntity<byte[]> recordExport(@Valid @RequestBody  RefreshStatisticsDto dto) throws IOException {
        byte[] bytes = classTimeStatisticsService.recordExport(dto.getId());
        String fileName = "recordExport" + ExcelTypeEnum.XLSX.getValue();
        return RT.fileStream(bytes, fileName);
    }

}