package com.jeeplus.test.roster.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.aop.demo.annotation.DemoMode;
import com.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.common.beanvalidator.BeanValidators;
import com.jeeplus.core.excel.ExcelOptions;
import com.jeeplus.core.excel.ExportMode;
import com.jeeplus.core.excel.utils.EasyPoiUtil;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.security.util.SecurityUtils;
import com.jeeplus.sys.constant.enums.LogTypeEnum;
import com.jeeplus.sys.domain.Office;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.service.OfficeService;
import com.jeeplus.sys.service.UserService;
import com.jeeplus.sys.service.dto.OfficeDTO;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.service.mapstruct.UserWrapper;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.oss.service.OssService;
import com.jeeplus.test.rank.domain.Rank;
import com.jeeplus.test.rank.domain.RankRRs;
import com.jeeplus.test.rank.domain.RankSequence;
import com.jeeplus.test.rank.service.RankRRSService;
import com.jeeplus.test.rank.service.RankSequenceService;
import com.jeeplus.test.rank.service.RankService;
import com.jeeplus.test.rank.service.dto.RankDTO;
import com.jeeplus.test.rank.service.dto.RankSequenceDTO;
import com.jeeplus.test.rank.service.mapstruct.RankSequenceWrapper;
import com.jeeplus.test.rank.service.mapstruct.RankWrapper;
import com.jeeplus.test.reimbursement.reimbursementInfo.service.dto.QueryListDto;
import com.jeeplus.test.reimbursement.reimbursementInfo.service.dto.RetureListDto;
import com.jeeplus.test.roster.domain.RosterBase;
import com.jeeplus.test.roster.service.RosterBaseService;
import com.jeeplus.test.roster.service.dto.RosterBaseDTO;
import com.jeeplus.test.roster.service.dto.RosterBaseExportDTO;
import com.jeeplus.test.roster.service.mapstruct.RosterBaseWrapper;
import com.jeeplus.test.user.service.dto.FileUrlDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Api("花名册")
@RestController
@RequestMapping(value = "/roster/base")
public class RosterBaseController {

    @Autowired
    private RosterBaseService rosterBaseService;

    @Autowired
    private UserService userService;

    @Autowired
    private OssService ossService;

    @Autowired
    private OfficeService officeService;

    /**
     * 查询花名册列表
     * @param rosterBaseDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询花名册列表")
    @PreAuthorize("hasAuthority('roster:base:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<RosterBaseDTO>> data(RosterBaseDTO rosterBaseDTO, Page<RosterBaseDTO> page) throws Exception {
        IPage<RosterBaseDTO> result = rosterBaseService.findList (page,rosterBaseDTO);
        return ResponseEntity.ok (result);
    }

    /**
     * 查询花名册数据
     * @param id
     * @return
     */
    @ApiLog("查询花名册详情")
    @PreAuthorize ("hasAnyAuthority('roster:base:view','roster:base:add','roster:base:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        RosterBaseDTO rosterBaseDTO = rosterBaseService.queryById ( id );
        return ResponseEntity.ok (rosterBaseDTO);
    }

    /**
     * 添加花名册
     * @param rosterBaseDTO
     * @return
     */
    @ApiLog(value = "修改/新增花名册", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('roster:base:save','roster:base:edit')")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody RosterBaseDTO rosterBaseDTO, HttpServletRequest request) throws Exception {
        return rosterBaseService.saveRoster(rosterBaseDTO);
    }

    /**
     * 删除花名册
     * @param ids
     * @return
     */
    @ApiLog(value = "删除花名册", type = LogTypeEnum.SAVE)
    @PreAuthorize ("hasAuthority('roster:base:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids,HttpServletRequest request) {
        String idArray[] =ids.split(",");
        return rosterBaseService.removeByRosterIds (idArray);
    }

    /**
     * 上传文件
     * @return
     * @throws IOException
     */
    @ApiOperation("上传文件")
    @RequestMapping("webUpload/upload")
    public ResponseEntity<FileUrlDto> webUpload(HttpServletRequest request, MultipartFile file) throws IOException {
        String dir = "roster";
        FileUrlDto dto = ossService.webUpload(file,dir);
        return ResponseEntity.ok(dto);
    }

    /**
     * 查询所有用户
     * @return
     */
    @ApiLog("查询所有用户")
    @GetMapping("queryAllSupervisor")
    public ResponseEntity queryAllSupervisor() {
        List<UserDTO> userDTOList = new ArrayList<>();
        List<User> list = userService.list();
        list.stream().forEach(item->{
            UserDTO userDTO = UserWrapper.INSTANCE.toDTO (item);
            userDTOList.add(userDTO);
        });
        return ResponseEntity.ok (userDTOList);
    }

    /**
     * 下载导入花名册数据模板
     *
     * @param response
     * @return
     */
    @PreAuthorize ("hasAnyAuthority('roster:base:import')")
    @GetMapping("import/template")
    @ApiOperation(value = "下载模板")
    public void importFileTemplate(HttpServletResponse response) {
        String fileName = "花名册数据导入模板.xlsx";
        List<RosterBaseExportDTO> list = Lists.newArrayList();
        EasyPoiUtil.exportExcel ( list, "花名册数据",  "花名册数据", RosterBaseExportDTO.class, fileName, response );
    }

    /**
     * 导入花名册数据
     *
     * @return
     */
    @DemoMode
    @PreAuthorize("hasAnyAuthority('roster:base:import')")
    @PostMapping("import")
    @ApiOperation(value = "导入花名册excel")
    public ResponseEntity importFile(MultipartFile file) {
        return rosterBaseService.importFile(file);
    }

    /**
     * 花名册数据导出
     * @param rosterBaseDTO
     * @param page
     * @param options
     * @param response
     * @throws Exception
     */
    @ApiLog(value = "花名册导出", type = LogTypeEnum.EXPORT)
    @GetMapping("exportFile")
    @ApiOperation(value = "花名册导出")
    public void exportFile(RosterBaseDTO rosterBaseDTO, Page <RosterBaseDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<RosterBaseDTO> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = rosterBaseService.findList (page,rosterBaseDTO).getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = rosterBaseService.findList (page,rosterBaseDTO).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = rosterBaseService.findList (page,rosterBaseDTO).getRecords();
        }
        EasyPoiUtil.exportExcel ( result, sheetName,  sheetName, RosterBaseDTO.class, fileName, response );

    }

}
