package com.xiaoniu.subsystem.business.controller;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xiaoniu.common.core.result.R;
import com.xiaoniu.common.core.utils.BeanUtil;
import com.xiaoniu.common.core.utils.poi.ExcelUtil;
import com.xiaoniu.common.log.annotation.Log;
import com.xiaoniu.common.log.enums.BusinessType;
import com.xiaoniu.subsystem.business.domain.Sign;
import com.xiaoniu.subsystem.business.domain.StudentInfo;
import com.xiaoniu.subsystem.business.domain.dto.StudentInfoDTO;
import com.xiaoniu.subsystem.business.domain.dto.StudentInfoPageDTO;
import com.xiaoniu.subsystem.business.domain.vo.StudentInfoPageVO;
import com.xiaoniu.subsystem.business.service.IStudentInfoService;
import com.xiaoniu.subsystem.system.domain.SysDictData;
import com.xiaoniu.subsystem.system.domain.Unit;
import com.xiaoniu.subsystem.system.service.ISysDictDataService;
import com.xiaoniu.subsystem.system.service.IUnitService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

import static com.xiaoniu.common.security.utils.SecurityUtils.getUnitId;
import static com.xiaoniu.common.security.utils.SecurityUtils.getUserId;

/**
 * <p>
 * 学员信息表 前端控制器
 * </p>
 *
 * @author haoxuyang
 * @since 2024-12-23 05:36:11
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/student")
@Tag(name = "学员信息表", description = "学员信息")
public class StudentInfoController {
    private final IUnitService unitService;
    private final IStudentInfoService studentInfoService;
    private ISysDictDataService dictDataService;

    /**
     * 分页
     */
    @GetMapping("/page")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "分页", description = "传入StudentInfoPageDTO")
    public R<IPage<StudentInfoPageVO>> page(@Validated StudentInfoPageDTO dto) {
        IPage<StudentInfo> pages = studentInfoService.page(new Page<>(dto.getPageNum(), dto.getPageSize()),
                new LambdaQueryWrapper<StudentInfo>()
                        .orderByDesc(StudentInfo::getCreateTime)
                        .eq(dto.getFlightId() != null,StudentInfo::getFlightId,dto.getFlightId())
                        .like(StringUtils.isNotBlank(dto.getMainUnitName()),StudentInfo::getMainUnitName,dto.getMainUnitName())
                        .like(StringUtils.isNotBlank(dto.getUserName()), StudentInfo::getUserName, dto.getUserName())
                        .like(StringUtils.isNotBlank(dto.getFlightName()), StudentInfo::getFlightName, dto.getFlightName())
                        .eq(StringUtils.isNotBlank(dto.getTraineeType()),StudentInfo::getTraineeType,dto.getTraineeType())
                        .eq(StringUtils.isNotBlank(dto.getYear()),StudentInfo::getYear,dto.getYear())
                        .like(StringUtils.isNotBlank(dto.getTrainingUnitName()),StudentInfo::getTrainingUnitName,dto.getTrainingUnitName())
                        .like(StringUtils.isNotBlank(dto.getJob()),StudentInfo::getJob,dto.getJob())
                        .like(StringUtils.isNotBlank(dto.getPresentPostName()),StudentInfo::getPresentPostName,dto.getPresentPostName()));

        IPage<StudentInfoPageVO> copy = BeanUtil.copy(pages, StudentInfoPageVO.class);
        return R.data(copy);
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "新增", description = "传入StudentInfoDTO")
    public R save(@Valid @RequestBody StudentInfoDTO dto) {
        Unit unit = unitService.getById(getUnitId());
        StudentInfo copy = BeanUtil.copy(dto, StudentInfo.class)
                .setCreateDept(unit.getUnitId())
                .setCreateUser(getUserId())
                .setCreateTime(new Date());
        List<StudentInfo> one = studentInfoService.list(new LambdaQueryWrapper<StudentInfo>()
                        .eq(StudentInfo::getFlightId,dto.getFlightId())
                        .eq(StudentInfo::getIdCard,copy.getIdCard())
        );
        if (CollectionUtils.isNotEmpty(one)) {
            return R.fail("学员已存在");
        }
        return R.status(studentInfoService.save(copy));
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @Operation(summary = "修改", description = "传入StudentInfoDTO")
    public R update(@Valid @RequestBody StudentInfoDTO dto) {
        StudentInfo copy = BeanUtil.copy(dto, StudentInfo.class)
                .setUpdateUser(getUserId())
                .setUpdateTime(new Date());
        return R.status(studentInfoService.updateById(copy));
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @Operation(summary = "删除", description = "传入ids")
    public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
        List<StudentInfo> list = studentInfoService.listByIds(Arrays.stream(ids.split(",")).toList());
        return R.status(studentInfoService.removeByIds(Arrays.stream(ids.split(",")).toList()));
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    @ApiOperationSupport(order = 3)
    @Log(title = "导出", businessType = BusinessType.EXPORT)
    @Operation(summary = "导出", description = "传入StudentInfoPageDTO")
    public void export(HttpServletResponse response, @Validated StudentInfoPageDTO dto) {
        List<StudentInfo> list = new ArrayList<>();
        if (StringUtils.isNotBlank(dto.getIds())) {
            list.addAll(studentInfoService.list(new LambdaQueryWrapper<StudentInfo>()
                    .orderByDesc(StudentInfo::getCreateTime)
                    .in(StringUtils.isNotBlank(dto.getIds()), StudentInfo::getStudentId,
                            Arrays.stream(dto.getIds().split(",")).toList())));
        } else {
            list.addAll(studentInfoService.list(new LambdaQueryWrapper<StudentInfo>()
                    .orderByDesc(StudentInfo::getCreateTime)
                    .eq(dto.getFlightId() != null,StudentInfo::getFlightId,dto.getFlightId())
                    .like(StringUtils.isNotBlank(dto.getMainUnitName()),StudentInfo::getMainUnitName,dto.getMainUnitName())
                    .like(StringUtils.isNotBlank(dto.getUserName()), StudentInfo::getUserName, dto.getUserName())
                    .like(StringUtils.isNotBlank(dto.getFlightName()), StudentInfo::getFlightName, dto.getFlightName())
                    .eq(StringUtils.isNotBlank(dto.getTraineeType()),StudentInfo::getTraineeType,dto.getTraineeType())
                    .eq(StringUtils.isNotBlank(dto.getYear()),StudentInfo::getYear,dto.getYear())
                    .like(StringUtils.isNotBlank(dto.getTrainingUnitName()),StudentInfo::getTrainingUnitName,dto.getTrainingUnitName())
                    .like(StringUtils.isNotBlank(dto.getJob()),StudentInfo::getJob,dto.getJob())
                    .like(StringUtils.isNotBlank(dto.getPresentPostName()),StudentInfo::getPresentPostName,dto.getPresentPostName())));
        }
        List<SysDictData> data = dictDataService.list(
                new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictType, "1"));
        Map<String, String> map = data.stream()
                .collect(Collectors.toMap(SysDictData::getDictLabel, SysDictData::getDictValue));
        for (StudentInfo studentInfo : list) {
            studentInfo.setMajorType(map.get(studentInfo.getMajorType()));
        }
        ExcelUtil<StudentInfo> excelUtil = new ExcelUtil<>(StudentInfo.class);
        excelUtil.exportExcel(response, list, "学员信息数据");
    }

    /**
     * 导入
     */
    @PostMapping("/import")
    @ApiOperationSupport(order = 9)
    @Log(title = "学员信息导入", businessType = BusinessType.IMPORT)
    @Operation(summary = "导入")
    public R importData(MultipartFile file,
                        @Parameter(description = "是否支持更新", required = true)
                        @RequestParam boolean updateSupport) throws Exception {
        ExcelUtil<StudentInfo> util = new ExcelUtil<>(StudentInfo.class);
        List<StudentInfo> list = util.importExcel(file.getInputStream());
        List<SysDictData> data = dictDataService.list(
                new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictType, "1"));
        Map<String, String> map = data.stream()
                .collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (StudentInfo studentInfo : list) {
            studentInfo.setMajorType(map.get(studentInfo.getMajorType()));
        }
        return R.success(studentInfoService.importData(list, updateSupport));
    }

    /**
     * 模版导入
     */
    @GetMapping("/importTemplate")
    @ApiOperationSupport(order = 10)
    @Operation(summary = "导入模版下载")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<StudentInfo> util = new ExcelUtil<>(StudentInfo.class);
        util.importTemplateExcel(response, "学员信息导入模版");
    }

}
