package com.jeeplus.test.program.configuration.fileDict.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
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.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.sys.constant.enums.LogTypeEnum;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.test.program.configuration.fileDict.domain.ProgramFileDict;
import com.jeeplus.test.program.configuration.fileDict.service.ProgramFileDictService;
import com.jeeplus.test.program.configuration.fileDict.service.dto.ProgramFileDictDTO;
import com.jeeplus.test.program.configuration.typeDict.domain.ProgramTypeDict;
import com.jeeplus.test.program.configuration.typeDict.service.ProgramTypeDictService;
import com.jeeplus.test.program.configuration.typeDict.service.dto.ProgramTypeDictDTO;
import io.swagger.annotations.Api;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@Api("项目配置管理-附件类型管理")
@RestController
@RequestMapping(value = "/program/configuration/file")
public class ProgramFileDictController {

    @Resource
    private ProgramFileDictService programFileDictService;

    /**
     * 查询附件类型管理列表
     * @param programFileDictDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询附件类型管理列表")
    @PreAuthorize("hasAuthority('program:configuration:file:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<ProgramFileDictDTO>> data(ProgramFileDictDTO programFileDictDTO, Page<ProgramFileDictDTO> page) throws Exception {
        page.setSize(-1);
        IPage<ProgramFileDictDTO> result = new Page<ProgramFileDictDTO>();
        if(ObjectUtil.isNotEmpty(programFileDictDTO)){
            if(StringUtils.isNotBlank(programFileDictDTO.getName())){
                //根据name模糊查询
                List<ProgramFileDict> programFileDictList = programFileDictService.list(new QueryWrapper<ProgramFileDict>().lambda()
                        .like(StringUtils.isNotBlank(programFileDictDTO.getName()), ProgramFileDict::getName, programFileDictDTO.getName())
                );
                //获取到其中不是一级附件类型的数据
                List<ProgramFileDict> childList = programFileDictList.stream().distinct().filter(item -> {
                    if (!"0".equals(item.getParentId())) {
                        return true;
                    }
                    return false;
                }).collect(Collectors.toList());
                //childList的id全部获取
                List<String> cIdList = childList.stream().distinct().map(ProgramFileDict::getId).collect(Collectors.toList());
                //childList的父级id全部获取
                List<String> cupIdList = childList.stream().distinct().map(ProgramFileDict::getParentId).collect(Collectors.toList());
                //获取到其中一级附件类型的数据的id
                List<String> pIdList = programFileDictList.stream().distinct().filter(item -> {
                    if ("0".equals(item.getParentId())) {
                        return true;
                    }
                    return false;
                }).map(ProgramFileDict::getId).collect(Collectors.toList());
                //获取pIdList下的所有子附件类型的id
                if(CollectionUtil.isNotEmpty(pIdList)){
                    pIdList.addAll(programFileDictService.list(new QueryWrapper<ProgramFileDict>().lambda()
                            .in(ProgramFileDict::getParentId,pIdList)).stream().map(ProgramFileDict::getId).collect(Collectors.toList()));
                }
                //将获取到的这几个id集合融合到一起并去重，然后根据id查询，即可得到结果
                cIdList.addAll(cupIdList);
                cIdList.addAll(pIdList);
                List<String> idList = cIdList.stream().distinct().collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(idList)){
                    QueryWrapper<ProgramFileDict> wrapper = new QueryWrapper<ProgramFileDict>()
                            .in("pfd.id",idList);
                    result = programFileDictService.findList (page,wrapper);
                }
            }else{
                result = programFileDictService.findList (page,new QueryWrapper<ProgramFileDict>());
            }
        }
        return ResponseEntity.ok (result);
    }

    /**
     * 查询附件类型管理数据
     * @param id
     * @return
     */
    @ApiLog("查询附件类型管理数据")
    @PreAuthorize ("hasAnyAuthority('program:configuration:file:view','program:configuration:file:add','program:configuration:file:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        ProgramFileDictDTO programFileDictDTO = programFileDictService.queryById ( id );
        return ResponseEntity.ok (programFileDictDTO);
    }

    /**
     * 保存附件类型
     * @param programFileDictDTO
     * @return
     */
    @ApiLog(value = "修改/新增附件类型", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('program:configuration:type:save','program:configuration:type:edit')")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody ProgramFileDictDTO programFileDictDTO) {
        programFileDictService.saveType(programFileDictDTO);
        return ResponseEntity.ok ("操作成功");
    }

    /**
     * 删除附件类型
     * @param ids
     * @return
     */
    @ApiLog(value = "删除附件类型", type = LogTypeEnum.SAVE)
    @PreAuthorize ("hasAuthority('program:configuration:type:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids) {
        return programFileDictService.deleteByIds(ids);
    }

    /**
     * 查询附件类型
     * @return
     */
    @ApiLog("查询附件类型")
    @GetMapping("getAllFileType")
    public ResponseEntity getAllFileType() {
        List<ProgramFileDict> list = programFileDictService.list ( new QueryWrapper<ProgramFileDict>().lambda().eq(ProgramFileDict::getParentId,"0") );
        return ResponseEntity.ok (list);
    }
}
