package com.jeeplus.assess.program.configuration.typeDict.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
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.jeeplus.assess.program.configuration.typeDict.domain.ProgramTypeDict;
import com.jeeplus.assess.program.configuration.typeDict.service.ProgramTypeDictService;
import com.jeeplus.assess.program.configuration.typeDict.service.dto.ProgramTypeDictDTO;
import com.jeeplus.logging.annotation.ApiLog;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
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.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

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

    @Resource
    private ProgramTypeDictService programTypeDictService;

    /**
     * 查询项目类型管理列表
     * @param programTypeDictDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询项目类型管理列表")
    @PreAuthorize("hasAuthority('program:configuration:type:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<ProgramTypeDictDTO>> data(ProgramTypeDictDTO programTypeDictDTO, Page<ProgramTypeDictDTO> page) throws Exception {
        page.setSize(-1);
        IPage<ProgramTypeDictDTO> result = new Page<ProgramTypeDictDTO>();
        if(ObjectUtil.isNotEmpty(programTypeDictDTO)){
            if(StringUtils.isNotBlank(programTypeDictDTO.getType())){
                //根据type模糊查询
                List<ProgramTypeDict> programTypeDictList = programTypeDictService.list(new QueryWrapper<ProgramTypeDict>().lambda()
                        .like(StringUtils.isNotBlank(programTypeDictDTO.getType()), ProgramTypeDict::getType, programTypeDictDTO.getType())
                );
                //获取到其中不是一级项目类型的数据
                List<ProgramTypeDict> childList = programTypeDictList.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(ProgramTypeDict::getId).collect(Collectors.toList());
                //childList的父级id全部获取
                List<String> cupIdList = childList.stream().distinct().map(ProgramTypeDict::getParentId).collect(Collectors.toList());
                //获取到其中一级项目类型的数据的id
                List<String> pIdList = programTypeDictList.stream().distinct().filter(item -> {
                    if ("0".equals(item.getParentId())) {
                        return true;
                    }
                    return false;
                }).map(ProgramTypeDict::getId).collect(Collectors.toList());
                //获取pIdList下的所有子项目类型的id
                if(CollectionUtil.isNotEmpty(pIdList)){
                    pIdList.addAll(programTypeDictService.list(new QueryWrapper<ProgramTypeDict>().lambda()
                            .in(ProgramTypeDict::getParentId,pIdList)).stream().map(ProgramTypeDict::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<ProgramTypeDict> wrapper = new QueryWrapper<ProgramTypeDict>()
                            .in("ptd.id",idList);
                    result = programTypeDictService.findList (page,wrapper);
                }
            }else{
                result = programTypeDictService.findList (page,new QueryWrapper<ProgramTypeDict>());
            }
        }
        return ResponseEntity.ok (result);
    }

    /**
     * 查询项目类型管理数据
     * @param id
     * @return
     */
    @ApiLog("查询项目类型管理详情")
    @PreAuthorize ("hasAnyAuthority('program:configuration:type:view','program:configuration:type:add','program:configuration:type:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        ProgramTypeDictDTO programTypeDictDTO = programTypeDictService.queryById ( id );
        return ResponseEntity.ok (programTypeDictDTO);
    }

    /**
     * 查询全部一级项目类型
     * @return
     */
    @ApiLog("查询全部一级项目类型")
    @GetMapping("getList")
    public ResponseEntity<List<ProgramTypeDictDTO>> getList() {
        List<ProgramTypeDictDTO> list = programTypeDictService.getList();
        return ResponseEntity.ok (list);
    }

    /**
     * 保存项目类型
     * @param programTypeDictDTO
     * @return
     */
    @ApiLog(value = "修改/新增项目类型")
    @PreAuthorize("hasAnyAuthority('program:configuration:type:save','program:configuration:type:edit')")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody ProgramTypeDictDTO programTypeDictDTO) {
        programTypeDictService.saveType(programTypeDictDTO);
        return ResponseEntity.ok ("操作成功");
    }

    /**
     * 删除项目类型
     * @param ids
     * @return
     */
    @ApiLog(value = "删除项目类型")
    @PreAuthorize ("hasAuthority('program:configuration:type:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids) {
        return programTypeDictService.deleteByIds(ids);
    }

}
