package com.xiaoniu.subsystem.business.controller;


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.ProfileManage;
import com.xiaoniu.subsystem.business.domain.dto.ProfileManageDTO;
import com.xiaoniu.subsystem.business.domain.dto.ProfileManagePageDTO;
import com.xiaoniu.subsystem.business.domain.dto.ProfilePageDTO;
import com.xiaoniu.subsystem.business.domain.dto.ProfileSaveDTO;
import com.xiaoniu.subsystem.business.domain.vo.ProfileManageVO;
import com.xiaoniu.subsystem.business.service.IProfileManageService;
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 org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

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

@RestController
@AllArgsConstructor
@RequestMapping("/profileManage")
@Tag(name = "资料管理表2", description = "资料管理表接口2")
public class ProfileManageController {
    private IProfileManageService profileManageService;

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "详情", description = "传入profile")
    public R<ProfileManageVO> detail(@Parameter(description = "主键", required = true) @RequestParam Long profileId) {
        ProfileManage detail = profileManageService.getById(profileId);
        return R.data(BeanUtil.copy(detail, ProfileManageVO.class));
    }

    /**
     * 详情
     */
    @GetMapping("/flight/detail")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "班次详情", description = "传入profile")
    public R<ProfileManageVO> flightDetail(ProfilePageDTO dto) {
        ProfileManage detail = profileManageService.getOne(new LambdaQueryWrapper<ProfileManage>()
                .eq(ProfileManage::getType,dto.getType())
                .eq(ProfileManage::getFlightId,dto.getFlightId())
                .eq(StringUtils.isNotBlank(dto.getProfileName()),ProfileManage::getProfileName,dto.getProfileName())
        );
        return R.data(BeanUtil.copy(detail, ProfileManageVO.class));
    }



    /**
     * 分页 资料管理表
     */
    @GetMapping("/page")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "分页", description = "传入profile")
    public R<IPage<ProfileManageVO>> page(@Validated ProfilePageDTO dto) {
        IPage<ProfileManage> pages = profileManageService.page(new Page<>(dto.getPageNum(), dto.getPageSize()),
                new LambdaQueryWrapper<ProfileManage>()
                        .eq(ProfileManage::getType, dto.getType())
                        .eq(null != dto.getFlightId(), ProfileManage::getFlightId, dto.getFlightId())
                        .like(StringUtils.isNotBlank(dto.getFlightName()), ProfileManage::getFlightName, dto.getFlightName())
                        .like(StringUtils.isNotBlank(dto.getFlightCode()), ProfileManage::getFlightCode, dto.getFlightCode())
                        .like(StringUtils.isNotBlank(dto.getProfileName()), ProfileManage::getProfileName, dto.getProfileName())
                        .like(StringUtils.isNotBlank(dto.getProfileCode()), ProfileManage::getProfileCode, dto.getProfileCode())
                        .eq(StringUtils.isNotBlank(dto.getYear()), ProfileManage::getYear, dto.getYear())
                        .orderByDesc(ProfileManage::getCreateTime));
        return R.data(BeanUtil.copy(pages, ProfileManageVO.class));
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    @ApiOperationSupport(order = 3)
    @Log(title = "资料导出", businessType = BusinessType.EXPORT)
    @Operation(summary = "导出", description = "传入ids")
    public void export(HttpServletResponse response, @Validated ProfileManagePageDTO dto) {
        List<ProfileManage> list = new ArrayList<>();
        if (StringUtils.isNotBlank(dto.getIds())) {
            list.addAll(profileManageService.list(new LambdaQueryWrapper<ProfileManage>()
                    .orderByDesc(ProfileManage::getCreateTime)
                    .in(StringUtils.isNotBlank(dto.getIds()), ProfileManage::getProfileId,
                            Arrays.stream(dto.getIds().split(",")).toList())));
        } else {
            list.addAll(profileManageService.list(new LambdaQueryWrapper<ProfileManage>()
                    .orderByDesc(ProfileManage::getCreateTime)
                    .eq(ProfileManage::getType, dto.getType())
                    .eq(null != dto.getFlightId(), ProfileManage::getFlightId, dto.getFlightId())
                    .like(StringUtils.isNotBlank(dto.getFlightName()), ProfileManage::getFlightName, dto.getFlightName())
                    .like(StringUtils.isNotBlank(dto.getFlightCode()), ProfileManage::getFlightCode, dto.getFlightCode())
                    .like(StringUtils.isNotBlank(dto.getProfileName()), ProfileManage::getProfileName, dto.getProfileName())
                    .eq(StringUtils.isNotBlank(dto.getYear()), ProfileManage::getYear, dto.getYear())));
        }
        ExcelUtil<ProfileManage> excelUtil = new ExcelUtil<>(ProfileManage.class);
        excelUtil.exportExcel(response, list, (StringUtils.equals(dto.getType(), "0") ? "培训资料数据" :
                StringUtils.equals(dto.getType(), "1") ? "结算资料数据" : "评审资料"));

    }

    /**
     * 新增 资料管理表
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "新增", description = "传入profile")
    public R save(@Valid @RequestBody ProfileManageDTO dto) {
        return R.status(profileManageService.save(
                dto.setYear(String.valueOf(LocalDate.now().getYear()))
                        .setCreateDept(getUnitId()).setCreateUser(getUserId()).setCreateTime(new Date())));
    }

    /**
     * 新增 资料管理表
     */
    @PostMapping("/flight/Save")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "班次新增", description = "传入profile")
    public R flightSave(@Valid @RequestBody ProfileManageDTO dto) {
        ProfileManage profileManage= profileManageService.getOne(new LambdaQueryWrapper<ProfileManage>()
                .eq(ProfileManage::getFlightId,dto.getFlightId())
                .eq(ProfileManage::getType,dto.getType())
        );
        if (profileManage != null) {
            return R.status(profileManageService.updateById(profileManage.setUrl(dto.getUrl())));
        }
        return R.status(profileManageService.save(
                dto.setYear(String.valueOf(LocalDate.now().getYear()))
                        .setCreateDept(getUnitId()).setCreateUser(getUserId()).setCreateTime(new Date())));
    }

    /**
     * 修改 资料管理表
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @Operation(summary = "修改", description = "传入profile")
    public R update(@Valid @RequestBody ProfileManageDTO dto) {
        return R.status(profileManageService.updateById(
                dto.setUpdateUser(getUserId()).setUpdateTime(new Date())));
    }

    /**
     * 获取连接集合
     */
    @GetMapping("/getUrls")
    @ApiOperationSupport(order = 6)
    @Operation(summary = "获取连接集合", description = "传入dto")
    public R<List<String>> getUrls(@Validated ProfilePageDTO dto) {
        List<ProfileManage> list = new ArrayList<>();
        if (StringUtils.isNotBlank(dto.getIds())) {
            list.addAll(profileManageService.list(new LambdaQueryWrapper<ProfileManage>()
                    .orderByDesc(ProfileManage::getCreateTime)
                    .in(StringUtils.isNotBlank(dto.getIds()), ProfileManage::getProfileId,
                            Arrays.stream(dto.getIds().split(",")).toList())));
        } else {
            list.addAll(profileManageService.list(new LambdaQueryWrapper<ProfileManage>()
                    .orderByDesc(ProfileManage::getCreateTime)
                    .eq(ProfileManage::getType, dto.getType())
                    .eq(null != dto.getFlightId(), ProfileManage::getFlightId, dto.getFlightId())
                    .like(StringUtils.isNotBlank(dto.getFlightName()), ProfileManage::getFlightName, dto.getFlightName())
                    .like(StringUtils.isNotBlank(dto.getFlightCode()), ProfileManage::getFlightCode, dto.getFlightCode())
                    .like(StringUtils.isNotBlank(dto.getProfileName()), ProfileManage::getProfileName, dto.getProfileName())
                    .eq(StringUtils.isNotBlank(dto.getYear()), ProfileManage::getYear, dto.getYear())));
        }
        List<String> urls = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (ProfileManage profile : list) {
                urls.add(profile.getUrl());
            }
        }
        return R.data(urls);
    }

    /**
     * 删除 资料管理表
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @Operation(summary = "删除", description = "传入ids")
    public R remove(@NotNull @Parameter(description = "主键集合", required = true) @RequestParam String profileIds) {
        return R.status(profileManageService.updateByIds(Arrays.stream(profileIds.split(",")).toList()));
    }

    @Operation(summary = "导入文件（压缩包）")
    @PostMapping(value = "/importProFile")
    @ApiOperationSupport(order = 8)
    public R<String> importProFile(@RequestPart(value = "file") MultipartFile file,
                                   ProfileSaveDTO dto) {
        profileManageService.importProFile(file, dto);
        return R.status(true);
    }
}
