package jnpf.qualifications.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jnpf.base.ActionResult;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.entity.qualifications.Qualifications;
import jnpf.exception.HandleException;
import jnpf.model.qualifications.dto.PaginationQualificationsDTO;
import jnpf.model.qualifications.dto.SaveQualificationsDTO;
import jnpf.model.qualifications.vo.*;
import jnpf.permission.PositionApi;
import jnpf.permission.dto.v2.position.QueryPagePositionDTO;
import jnpf.permission.vo.v2.grades.GradeVO;
import jnpf.permission.vo.v2.position.PositionAndGradesVO;
import jnpf.permission.vo.v2.position.PositionVO;
import jnpf.qualifications.service.QualificationsService;
import jnpf.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
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.Map;
import java.util.stream.Collectors;

/**
 * 岗位任职资格标准管理
 *
 * @author Flynn Chan
 * @create 2024-03-04
 */
@Tag(name = "岗位任职资格标准管理")
@RestController
@RequestMapping("/qualifications")
public class QualificationsController {

    @Resource
    private QualificationsService qualificationsService;

    @Autowired
    private UserApiV2Util userApiV2Util;

    @Operation(summary = "岗位任职资格标准管理（分页or全列表）")
    @GetMapping("/page")
    public ActionResult<PageListVO<QualificationsListVO>> page(@SpringQueryMap @Valid PaginationQualificationsDTO dto) {
        List<Qualifications> data = qualificationsService.pageList(dto);
        List<QualificationsListVO> voList = new ArrayList<>();
        if (CollUtil.isNotEmpty(data)) {
            voList = JsonUtil.getJsonToList(data, QualificationsListVO.class);
        }

        //all position glades
        if (CollUtil.isNotEmpty(voList)) {
//            List<PositionEntity> positionEntityList = positionApi.getPositionName(data.stream().map(Qualifications::getPositionId).collect(Collectors.toList()));
            List<PositionVO> positionEntityList = userApiV2Util.listPositionDetailInfoByIds(data.stream().map(Qualifications::getPositionId).collect(Collectors.toList()), null);
//            List<BasePositionGradesEntity> positionGradesEntityList = positionApi.getGradesEntityList(data.stream().map(Qualifications::getPositionGradesId).collect(Collectors.toList()));
            List<GradeVO> positionGradesEntityList = userApiV2Util.listGradeByIds(data.stream().map(Qualifications::getPositionGradesId).collect(Collectors.toList()), null);
            voList.forEach(vo -> {
                positionEntityList.stream().filter(position -> position.getId().equals(vo.getPositionId())).findFirst().ifPresent(
                        positionEntity -> {
                            vo.setPositionEncode(positionEntity.getEnCode());
                            vo.setPositionName(positionEntity.getFullName());
                        }
                );
                if (CollUtil.isNotEmpty(positionGradesEntityList)) {
                    positionGradesEntityList.stream().filter(positionGrades -> positionGrades.getId().equals(vo.getPositionGradesId())).findFirst().ifPresent(positionGradesEntity -> {
                        vo.setPositionGradesName(positionGradesEntity.getFullName());
                    });
                }
            });
        }

        PaginationVO paginationVO = JsonUtil.getJsonToBean(dto, PaginationVO.class);

        return ActionResult.page(voList, paginationVO);
    }

    @Operation(summary = "根据一个岗位id获取职级列表,返回该职级是否配置")
    @GetMapping("/rank-list/{id}")
    public ActionResult<List<GradeVOExp>> rankList(@PathVariable("id") String id) throws Exception {

        return ActionResult.success(qualificationsService.rankList(id));
    }

    @Operation(summary = "分页查询岗位列表带职级")
    @PostMapping("/page-rank-list")
    public ActionResult<PageListVO<PositionAndGradesVOExp>> rankList(@RequestBody QueryPagePositionDTO dto) throws Exception {
        ActionResult<PageListVO<PositionAndGradesVO>> pageListVOActionResult = userApiV2Util.pageIncludingRankPositions(dto, null);
        PageListVO<PositionAndGradesVOExp> page = new PageListVO<>();
        if (pageListVOActionResult != null && pageListVOActionResult.getData() != null && CollUtil.isNotEmpty(pageListVOActionResult.getData().getList())) {
            BeanUtil.copyProperties(pageListVOActionResult.getData(),page);
            Map<String, Qualifications> map = qualificationsService.rankAllSetList();
            List<PositionAndGradesVOExp> positionAndGradesVOExps = BeanUtil.copyToList(page.getList(), PositionAndGradesVOExp.class);
            page.setList(positionAndGradesVOExps);
            List<PositionAndGradesVOExp> list = page.getList();
            if (CollUtil.isNotEmpty(list)) {
                for (PositionAndGradesVOExp positionAndGradesVOExp : list) {
                    if (CollUtil.isNotEmpty(positionAndGradesVOExp.getList())) {
                        for (GradeVOExp gradeVOExp : positionAndGradesVOExp.getList()) {
                            Qualifications qualifications = map.get(positionAndGradesVOExp.getId()+"-"+gradeVOExp.getId());
                            if (qualifications == null) {
                                gradeVOExp.setIsHave(false);
                            } else {
                                gradeVOExp.setIsHave(true);
                                gradeVOExp.setQualificationsId(qualifications.getId());
                            }
                        }
                    }
                }
            }
        }
        return ActionResult.success(page);
    }

    @Operation(summary = "一个岗位任职资格标准详情信息")
    @GetMapping("/{id}")
    public ActionResult<QualificationsInfoVO> infoQualifications(@PathVariable("id") String id) throws Exception {

        return ActionResult.success(qualificationsService.info(id));
    }

    @Operation(summary = "添加一个岗位任职资格标准")
    @PostMapping("")
    public ActionResult<String> addQualifications(@RequestBody @Valid SaveQualificationsDTO qualificationsDTO) throws HandleException {

        return ActionResult.success("添加成功", qualificationsService.insert(qualificationsDTO));
    }

    @Operation(summary = "更新一个岗位任职资格标准")
    @PutMapping("/{id}")
    public ActionResult<Boolean> updateQualifications(@PathVariable("id") String id, @RequestBody @Valid SaveQualificationsDTO qualificationsDTO) throws HandleException {
        qualificationsDTO.setId(id);

        return ActionResult.success(qualificationsService.update(qualificationsDTO));
    }

    @Operation(summary = "更新一个岗位任职资格标准")
    @DeleteMapping("/{id}")
    public ActionResult<Boolean> deleteQualifications(@PathVariable("id") String id) throws HandleException {

        return ActionResult.success(qualificationsService.delete(id));
    }

    @Operation(summary = "统计任职资格标准的数量")
    @GetMapping("/statistics/organize")
    public ActionResult<QualificationsStatisticsVO> qualificationsStatistics(@RequestParam(value = "organizeId") String organizeId) {

        return ActionResult.success(qualificationsService.statistics(organizeId));
    }

    @Operation(summary = "检查统计任职资格标准是否存在")
    @GetMapping("/check/exist")
    public ActionResult<Boolean> checkQualificationsByField(@RequestParam(value = "fieldId") String fieldId, @RequestParam(value = "itemId") String itemId) {
        if (StrUtil.isNotBlank(itemId) && StrUtil.isNotBlank(fieldId)) {
            return ActionResult.success(qualificationsService.checkExistByItem(fieldId, itemId));
        } else if (StrUtil.isNotBlank(fieldId)) {
            return ActionResult.success(qualificationsService.checkExistByField(fieldId));
        } else {
            return ActionResult.fail("请求参数有误");
        }
    }
}
