package com.testor.module.train.project.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.testor.biz.file.model.dto.FileDTO;
import com.testor.common.core.utils.StringUtils;
import com.testor.module.aptitude.model.domain.TPersonAptitude;
import com.testor.module.aptitude.model.domain.TPersonAptitudeDto;
import com.testor.module.aptitude.service.TPersonAptitudeService;
import com.testor.module.notice.model.domain.TSysFile;
import com.testor.module.notice.service.TSysFileService;
import com.testor.module.train.project.model.domain.ProfessionalIndicatorScore;
import com.testor.module.train.project.model.enums.ProfessionalIndicatorScoreEnum;
import com.testor.module.train.project.model.stat.ProfessionalIndicatorScoreDetail;
import com.testor.module.train.project.service.ProfessionalIndicatorScoreService;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.common.models.supers.SuperModel;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户专业评分表 前端控制器
 * </p>
 *
 * @author caoqiang
 * @since 2024-09-07
 */
@RestController
@RequestMapping("/professionalIndicatorScore")
@Api(value = "ProfessionalIndicatorScoreController", tags = "专业化指数评分")
@Slf4j
public class ProfessionalIndicatorScoreController extends SuperController {

    @Autowired
    private ProfessionalIndicatorScoreService professionalIndicatorScoreService;
    @Autowired
    private TPersonAptitudeService tPersonAptitudeService;
    @Autowired
    private TSysFileService tSysFileService;


    @ApiOperation(value = "专业化指数评分新增 ", notes = "专业化指数评分新增接口")
    @PostMapping(value = "/add")
    public BaseResponse<Boolean> add(@RequestBody ProfessionalIndicatorScoreDetail para) {
        ProfessionalIndicatorScore indicatorScore = new ProfessionalIndicatorScore();
        BeanUtils.copyProperties(para, indicatorScore);

        UserInfo loginUser = ContextUtils.getLoginUser();
        indicatorScore.setUserId(indicatorScore.getUserId());
        indicatorScore.setCreateBy(loginUser.getUserId());
        indicatorScore.setUpdateBy(loginUser.getUserId());
        indicatorScore.setStatus("0");
        indicatorScore.setCreateDate(new Date());
        indicatorScore.setUpdateDate(new Date());
        indicatorScore.setWorkProduct(JSON.toJSONString(para.getWorkProduct()));
        indicatorScore.setHonors(JSON.toJSONString(para.getHonors()));
        String id = indicatorScore.getId();
        if (StringUtils.isBlank(id)) {
            indicatorScore.setId(IdHelper.getId32bit());
        }
        String totalScore = indicatorScore.getTotalScore();
        if (StringUtils.isNotBlank(totalScore)) {
            if (Double.parseDouble(totalScore) < 6.00) {
                indicatorScore.setTotalScoreDes("不达标");
            }
            if (Double.parseDouble(totalScore) >= 6.00 && Double.parseDouble(totalScore) <= 8.00) {
                indicatorScore.setTotalScoreDes("达标");
            }
            if (Double.parseDouble(totalScore) > 8.00) {
                indicatorScore.setTotalScoreDes("优秀");
            }
        }
        boolean save = professionalIndicatorScoreService.saveOrUpdate(indicatorScore);
        BaseResponse<Boolean> response = new BaseResponse<>();
        response.setData(save);
        return response;
    }

    @ApiOperation(value = "专业化指数评分详情 ", notes = "专业化指数评分详情接口")
    @GetMapping(value = "/detail")
    public BaseResponse<ProfessionalIndicatorScoreDetail> detail(String userId) {
        BaseResponse<ProfessionalIndicatorScoreDetail> response = new BaseResponse<>();
        ProfessionalIndicatorScoreDetail detail = new ProfessionalIndicatorScoreDetail();
        ProfessionalIndicatorScore indicatorScore = professionalIndicatorScoreService.lambdaQuery()
                .eq(ProfessionalIndicatorScore::getUserId, userId).one();
        if (indicatorScore == null) {
            return response;
        }
        BeanUtils.copyProperties(indicatorScore, detail);
        String personAptitudeIds = indicatorScore.getPersonAptitudeIds();
        if (StringUtils.isNotBlank(personAptitudeIds)) {
            String[] split = StringUtils.split(personAptitudeIds, ",");
            List<TPersonAptitude> list = tPersonAptitudeService.lambdaQuery().in(TPersonAptitude::getId, split).list();
            if (CollectionUtils.isNotEmpty(list)) {
                detail.setPersonAptitude(list);
            }
        }
        detail.setEducationSpecialityFileDTOS(findFileDtos(indicatorScore.getEducationSpecialityFileIds()));
        detail.setWorkProductFileDTOS(findFileDtos(indicatorScore.getWorkProductFileIds()));
        detail.setWorkExperienceFileDTOS(findFileDtos(indicatorScore.getWorkExperienceFileIds()));
        detail.setHonorsFileDTOS(findFileDtos(indicatorScore.getHonorsFileIds()));
        detail.setHonors(JSON.parseArray(indicatorScore.getHonors(), String.class));
        detail.setWorkProduct(JSON.parseArray(indicatorScore.getWorkProduct(), String.class));
        response.setData(detail);
        return response;
    }

    @ApiOperation(value = "当前登陆人的专业资格 ", notes = "当前登陆人的专业资格")
    @GetMapping(value = "/personAptitudeDetail")
    public BaseResponse<JSONObject> personAptitudeDetail(String userId) {
        if (StringUtils.isBlank(userId)) {
            UserInfo loginUser = ContextUtils.getLoginUser();
            userId = loginUser.getUserId();
        }
        BaseResponse<JSONObject> response = new BaseResponse<>();
        List<TPersonAptitude> personAptitudeList = tPersonAptitudeService.lambdaQuery().eq(TPersonAptitude::getPersonId, userId)
                .eq(TPersonAptitude::getAptitudeStatus, "1").eq(SuperModel::getStatus, "0").list();
        if (CollectionUtils.isEmpty(personAptitudeList)) {
            return response;
        }
        List<Float> scoreList = new ArrayList<>();
        List<TPersonAptitudeDto> dtoList = new ArrayList<>();
        personAptitudeList.forEach(data -> {
            TPersonAptitudeDto dto = BeanHelper.beanToBean(data, TPersonAptitudeDto.class);
            String aptitudeName = dto.getAptitudeName();
            scoreList.add(Float.parseFloat(ProfessionalIndicatorScoreEnum.getScoreByCode(aptitudeName)));
            dtoList.add(dto);
        });
        Float max = Collections.max(scoreList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("aptitudeScore", String.valueOf(max));
        jsonObject.put("aptitudeList", dtoList);
        response.setData(jsonObject);
        return response;
    }


    /**
     * 获取文件列表
     *
     * @param fileIds
     * @return
     */
    private List<FileDTO> findFileDtos(String fileIds) {
        List<FileDTO> list = new ArrayList<>();
        if (StringUtils.isNotBlank(fileIds)) {
            String[] split = StringUtils.split(fileIds, ",");
            for (String s : split) {
                FileDTO fileDTO = new FileDTO();
                TSysFile tSysFile = tSysFileService.getById(s);
                if (tSysFile != null && !(tSysFile.getStatus().equals("1"))) {
                    fileDTO.setFilePath(tSysFile.getFilePath());
                    fileDTO.setFileName(tSysFile.getFileName());
                    fileDTO.setFileDowName(tSysFile.getFileDowName());
                    fileDTO.setFileId(s);
                    list.add(fileDTO);
                }
            }
        }
        return list;
    }

}
