package com.vetti.hotake.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.vetti.common.core.domain.entity.SysUser;
import com.vetti.common.core.service.BaseServiceImpl;
import com.vetti.common.enums.FillTypeEnum;
import com.vetti.common.enums.RoleOperStepsEnum;
import com.vetti.common.enums.RoleStatusEnum;
import com.vetti.common.exception.ServiceException;
import com.vetti.common.utils.DateUtils;
import com.vetti.common.utils.MessageUtils;
import com.vetti.common.utils.SecurityUtils;
import com.vetti.common.utils.uuid.IdUtils;
import com.vetti.hotake.domain.HotakeAiInterviewQuestionsInfo;
import com.vetti.hotake.domain.HotakeInitialScreeningQuestionsInfo;
import com.vetti.hotake.domain.HotakeRolesApplyInfo;
import com.vetti.hotake.domain.HotakeRolesInfo;
import com.vetti.hotake.domain.dto.AiQuestionDto;
import com.vetti.hotake.domain.dto.HotakeRolesInfoDto;
import com.vetti.hotake.domain.dto.roleDto.*;
import com.vetti.hotake.mapper.HotakeRolesApplyInfoMapper;
import com.vetti.hotake.mapper.HotakeRolesInfoMapper;
import com.vetti.hotake.service.IHotakeAiInterviewQuestionsInfoService;
import com.vetti.hotake.service.IHotakeInitialScreeningQuestionsInfoService;
import com.vetti.hotake.service.IHotakeRolesInfoService;
import com.vetti.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 岗位信息Service业务层处理
 * 
 * @author wangxiangshun
 * @date 2025-12-11
 */
@SuppressWarnings("all")
@Service
public class HotakeRolesInfoServiceImpl extends BaseServiceImpl implements IHotakeRolesInfoService
{
    @Autowired
    private HotakeRolesInfoMapper hotakeRolesInfoMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private HotakeRolesApplyInfoMapper hotakeRolesApplyInfoMapper;

    @Autowired
    private IHotakeInitialScreeningQuestionsInfoService hotakeInitialScreeningQuestionsInfoService;

    @Autowired
    private IHotakeAiInterviewQuestionsInfoService hotakeAiInterviewQuestionsInfoService;

    /**
     * 查询岗位信息
     * 
     * @param id 岗位信息主键
     * @return 岗位信息
     */
    @Transactional(readOnly = true)
    @Override
    public HotakeRolesInfo selectHotakeRolesInfoById(Long id)
    {
        return hotakeRolesInfoMapper.selectHotakeRolesInfoById(id);
    }

    /**
     * 查询岗位详细信息
     * @param id 岗位信息主键
     * @return
     */
    @Override
    public HotakeRolesInfoDto selectHotakeRolesInfoDtoById(Long id) {
        HotakeRolesInfoDto dto = new HotakeRolesInfoDto();
        HotakeRolesInfo hotakeRolesInfo = hotakeRolesInfoMapper.selectHotakeRolesInfoById(id);
        if(hotakeRolesInfo == null){
            throw new ServiceException(MessageUtils.messageCustomize("HotakeRolesInfoServiceImpl10001"));
        }
        BeanUtil.copyProperties(hotakeRolesInfo, dto);

        if(hotakeRolesInfo != null) {
            String requiredSkillsJson = hotakeRolesInfo.getRequiredSkillsJson();
            if(StrUtil.isNotEmpty(requiredSkillsJson)){
                List<RequiredSkillsDto> requiredSkillsList = JSONUtil.toList(requiredSkillsJson, RequiredSkillsDto.class);
                dto.setRequiredSkillsList(requiredSkillsList);
            }

            String niceToHaveSkillsJson = hotakeRolesInfo.getNiceToHaveSkillsJson();
            if(StrUtil.isNotEmpty(niceToHaveSkillsJson)){
                List<NiceToHaveSkillsDto> niceToHaveSkillsList = JSONUtil.toList(niceToHaveSkillsJson, NiceToHaveSkillsDto.class);
                dto.setNiceToHaveSkillsList(niceToHaveSkillsList);
            }

            String educationRequirementsJson = hotakeRolesInfo.getEducationRequirementsJson();
            if(StrUtil.isNotEmpty(educationRequirementsJson)){
                EducationRequirementsDto educationRequirements = JSONUtil.toBean(educationRequirementsJson, EducationRequirementsDto.class);
                dto.setEducationRequirements(educationRequirements);
            }

            String certificationsLicensesJson = hotakeRolesInfo.getCertificationsLicensesJson();
            if(StrUtil.isNotEmpty(certificationsLicensesJson)){
                List<CertificationsLicensesDto> certificationsLicensesList = JSONUtil.toList(certificationsLicensesJson, CertificationsLicensesDto.class);
                dto.setCertificationsLicensesList(certificationsLicensesList);
            }

            String roleBenefitsJson = hotakeRolesInfo.getRoleBenefitsJson();
            if(StrUtil.isNotEmpty(roleBenefitsJson)){
                List<RoleBenefitsDto> roleBenefitsList = JSONUtil.toList(roleBenefitsJson, RoleBenefitsDto.class);
                dto.setRoleBenefitsList(roleBenefitsList);
            }

            String publishingChannelsJson = hotakeRolesInfo.getPublishingChannelsJson();
            if(StrUtil.isNotEmpty(publishingChannelsJson)){
                List<PublishingChannelsDto> publishingChannelsList = JSONUtil.toList(publishingChannelsJson, PublishingChannelsDto.class);
                dto.setPublishingChannelsList(publishingChannelsList);
            }
            HotakeInitialScreeningQuestionsInfo queryQuestion = new HotakeInitialScreeningQuestionsInfo();
            queryQuestion.setRoleId(id);
            List<HotakeInitialScreeningQuestionsInfo> questionsInfoList = hotakeInitialScreeningQuestionsInfoService.selectHotakeInitialScreeningQuestionsInfoList(queryQuestion);
            dto.setInitialScreeningQuestionsInfoList(questionsInfoList);

            HotakeAiInterviewQuestionsInfo queryAiQuestion = new HotakeAiInterviewQuestionsInfo();
            queryAiQuestion.setRoleId(id);
            List<HotakeAiInterviewQuestionsInfo> aiInterviewQuestionsInfoList = hotakeAiInterviewQuestionsInfoService.selectHotakeAiInterviewQuestionsInfoList(queryAiQuestion);
            dto.setAiInterviewQuestionsInfoList(aiInterviewQuestionsInfoList);

            SysUser user = sysUserMapper.selectUserById(hotakeRolesInfo.getRecruiterId());
            dto.setRecruiterUser(user);
            
            // 判断当前用户是否已申请该岗位
            Long currentUserId = SecurityUtils.getUserId();
            HotakeRolesApplyInfo existApply = hotakeRolesApplyInfoMapper.selectByCandidateIdAndRoleId(currentUserId, id);
            dto.setHasApplied(existApply != null);
        }

        return dto;
    }

    /**
     * 查询岗位信息列表
     * 
     * @param hotakeRolesInfo 岗位信息
     * @return 岗位信息
     */
    @Transactional(readOnly = true)
    @Override
    public List<HotakeRolesInfo> selectHotakeRolesInfoList(HotakeRolesInfo hotakeRolesInfo)
    {
        List<HotakeRolesInfo> rolesInfoList = hotakeRolesInfoMapper.selectHotakeRolesInfoList(hotakeRolesInfo);
        //计算一个发布日期
        if(CollectionUtil.isNotEmpty(rolesInfoList)){
            List<HotakeRolesApplyInfo> applyInfoList = hotakeRolesApplyInfoMapper.selectHotakeRolesApplyInfoList(new HotakeRolesApplyInfo());

            List<SysUser> sysUserList = sysUserMapper.selectUserList(new SysUser());
            for (HotakeRolesInfo rolesInfo : rolesInfoList) {
                String posted = DateUtils.getTimeAgo(rolesInfo.getCreateTime());
                rolesInfo.setPosted(posted);

                if(CollectionUtil.isNotEmpty(applyInfoList)){
                    List<HotakeRolesApplyInfo> applyInfos = applyInfoList.stream().filter(e->e.getRoleId().longValue() == rolesInfo.getId().longValue()).toList();
                    if(CollectionUtil.isNotEmpty(applyInfos)){
                        for (HotakeRolesApplyInfo applyInfo : applyInfos) {
                            if(applyInfo.getCandidateId() != null){
                                List<SysUser> userList = sysUserList.stream().filter(e->e.getUserId().longValue() == applyInfo.getCandidateId().longValue()).toList();
                                if(CollectionUtil.isNotEmpty(userList)) {
                                    applyInfo.setCandidateUSer(userList.get(0));
                                }
                            }
                        }
                        rolesInfo.setRolesApplyInfoList(applyInfos);
                    }
                }
            }
        }
        return rolesInfoList;
    }

    /**
     * 新增岗位信息
     * 
     * @param hotakeRolesInfo 岗位信息
     * @return 结果
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    public int insertHotakeRolesInfo(HotakeRolesInfo hotakeRolesInfo)
    {
        hotakeRolesInfo.setCreateTime(DateUtils.getNowDate());
        return hotakeRolesInfoMapper.insertHotakeRolesInfo(hotakeRolesInfo);
    }

    /**
     * 修改岗位信息
     * 
     * @param hotakeRolesInfo 岗位信息
     * @return 结果
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    public int updateHotakeRolesInfo(HotakeRolesInfo hotakeRolesInfo)
    {
        hotakeRolesInfo.setUpdateTime(DateUtils.getNowDate());
        return hotakeRolesInfoMapper.updateHotakeRolesInfo(hotakeRolesInfo);
    }

    /**
     * 批量删除岗位信息
     * 
     * @param ids 需要删除的岗位信息主键
     * @return 结果
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    public int deleteHotakeRolesInfoByIds(Long[] ids)
    {
        return hotakeRolesInfoMapper.deleteHotakeRolesInfoByIds(ids);
    }

    /**
     * 删除岗位信息信息
     * 
     * @param id 岗位信息主键
     * @return 结果
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    public int deleteHotakeRolesInfoById(Long id)
    {
        return hotakeRolesInfoMapper.deleteHotakeRolesInfoById(id);
    }
    /**
     * 批量新增岗位信息
     *
     * @param hotakeRolesInfoList 岗位信息列表
     * @return 结果
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    public int batchInsertHotakeRolesInfo(List<HotakeRolesInfo> hotakeRolesInfoList){
        return hotakeRolesInfoMapper.batchInsertHotakeRolesInfo(hotakeRolesInfoList);
    }

    /**
     * 保存岗位信息
     * @param hotakeRolesInfo 岗位信息
     * @return
     */
    @Override
    public HotakeRolesInfoDto saveHotakeRolesInfo(HotakeRolesInfoDto hotakeRolesInfo) {
        //先看岗位信息ID是否存在
        HotakeRolesInfo rolesInfo = null;
        Long rolesInfoId = 0L;
        if(hotakeRolesInfo.getId() == null){
            //先保存一个空数据
            HotakeRolesInfo info = new HotakeRolesInfo();
            fill(FillTypeEnum.INSERT.getCode(), info);
            info.setUuid(IdUtils.simpleUUID());
            insertHotakeRolesInfo(info);
            rolesInfoId = info.getId();
        }else{
            rolesInfoId = hotakeRolesInfo.getId();
        }
        rolesInfo = selectHotakeRolesInfoById(rolesInfoId);
        if(rolesInfo == null){
            throw new ServiceException(MessageUtils.messageCustomize("HotakeRolesInfoServiceImpl10001"));
        }
        //按照步骤来进行保存对应的数据
        if(RoleOperStepsEnum.STEPS_1.getCode().equals(hotakeRolesInfo.getOperStep())){
            rolesInfo.setRoleName(hotakeRolesInfo.getRoleName());
            rolesInfo.setCompanyName(hotakeRolesInfo.getCompanyName());
            rolesInfo.setRoleType(hotakeRolesInfo.getRoleType());
            rolesInfo.setJobLevel(hotakeRolesInfo.getJobLevel());
            rolesInfo.setJobExperience(hotakeRolesInfo.getJobExperience());
            rolesInfo.setLocationType(hotakeRolesInfo.getLocationType());
            rolesInfo.setJobType(hotakeRolesInfo.getJobType());
            rolesInfo.setSalaryStart(hotakeRolesInfo.getSalaryStart());
            rolesInfo.setSalaryEnd(hotakeRolesInfo.getSalaryEnd());
        }
        if(RoleOperStepsEnum.STEPS_2.getCode().equals(hotakeRolesInfo.getOperStep())){

            if(CollectionUtil.isNotEmpty(hotakeRolesInfo.getRequiredSkillsList())){
                String requiredSkillsJson = JSONUtil.toJsonStr(hotakeRolesInfo.getRequiredSkillsList());
                rolesInfo.setRequiredSkillsJson(requiredSkillsJson);
            }else{
                rolesInfo.setRequiredSkillsJson("");
            }

            if(CollectionUtil.isNotEmpty(hotakeRolesInfo.getNiceToHaveSkillsList())){
                String niceToHaveSkillsJson = JSONUtil.toJsonStr(hotakeRolesInfo.getNiceToHaveSkillsList());
                rolesInfo.setNiceToHaveSkillsJson(niceToHaveSkillsJson);
            }else{
                rolesInfo.setNiceToHaveSkillsJson("");
            }

            if(hotakeRolesInfo.getEducationRequirements() != null){
                rolesInfo.setEducationRequirementsJson(JSONUtil.toJsonStr(hotakeRolesInfo.getEducationRequirements()));
            }else {
                rolesInfo.setEducationRequirementsJson("");
            }

            if (CollectionUtil.isNotEmpty(hotakeRolesInfo.getCertificationsLicensesList())){
                String certificationsLicensesJson = JSONUtil.toJsonStr(hotakeRolesInfo.getCertificationsLicensesList());
                rolesInfo.setCertificationsLicensesJson(certificationsLicensesJson);
            }else{
                rolesInfo.setCertificationsLicensesJson("");
            }
            rolesInfo.setAcceptEquivalentWorkFlag(hotakeRolesInfo.getAcceptEquivalentWorkFlag());
        }
        if(RoleOperStepsEnum.STEPS_3.getCode().equals(hotakeRolesInfo.getOperStep())){
            rolesInfo.setDescriptionTone(hotakeRolesInfo.getDescriptionTone());
            rolesInfo.setAboutRole(hotakeRolesInfo.getAboutRole());
            rolesInfo.setResponsibilities(hotakeRolesInfo.getResponsibilities());
            if (CollectionUtil.isNotEmpty(hotakeRolesInfo.getRoleBenefitsList())){
                String roleBenefitsJson = JSONUtil.toJsonStr(hotakeRolesInfo.getRoleBenefitsList());
                rolesInfo.setRoleBenefitsJson(roleBenefitsJson);
            }else{
                rolesInfo.setRoleBenefitsJson("");
            }
//            createAiQuestion(rolesInfoId);
        }
        if(RoleOperStepsEnum.STEPS_4.getCode().equals(hotakeRolesInfo.getOperStep())){

        }
        if(RoleOperStepsEnum.STEPS_5.getCode().equals(hotakeRolesInfo.getOperStep())){
            rolesInfo.setAiScreeningVideoFlag(hotakeRolesInfo.getAiScreeningVideoFlag());
            rolesInfo.setVideoId(hotakeRolesInfo.getVideoId());
            rolesInfo.setSpeechSpeed(hotakeRolesInfo.getSpeechSpeed());
        }
        if(RoleOperStepsEnum.STEPS_6.getCode().equals(hotakeRolesInfo.getOperStep())){
            if (CollectionUtil.isNotEmpty(hotakeRolesInfo.getPublishingChannelsList())){
                String publishingChannelsJson = JSONUtil.toJsonStr(hotakeRolesInfo.getPublishingChannelsList());
                rolesInfo.setPublishingChannelsJson(publishingChannelsJson);
            }else{
                rolesInfo.setPublishingChannelsJson("");
            }
            rolesInfo.setPublishingScheduleDate(hotakeRolesInfo.getPublishingScheduleDate());
            rolesInfo.setPublishingScheduleTime(hotakeRolesInfo.getPublishingScheduleTime());
            rolesInfo.setApplicationDeadline(hotakeRolesInfo.getApplicationDeadline());
        }
        //默认是编辑中状态
        if(StrUtil.isEmpty(hotakeRolesInfo.getStatus())){
            rolesInfo.setStatus(RoleStatusEnum.EDITING.getCode());
        }else{
            rolesInfo.setStatus(hotakeRolesInfo.getStatus());
        }
        if(StrUtil.isNotEmpty(hotakeRolesInfo.getDataType())){
            rolesInfo.setDataType(hotakeRolesInfo.getDataType());
        }
        if(StrUtil.isNotEmpty(hotakeRolesInfo.getLanguages())){
            rolesInfo.setLanguages(hotakeRolesInfo.getLanguages());
        }
        if(StrUtil.isNotEmpty(hotakeRolesInfo.getOperStep())){
            rolesInfo.setOperStep(hotakeRolesInfo.getOperStep());
        }
        rolesInfo.setRecruiterId(SecurityUtils.getUserId());
        fill(FillTypeEnum.UPDATE.getCode(), rolesInfo);
        hotakeRolesInfoMapper.updateAllHotakeRolesInfo(rolesInfo);
        //查询返回所有的结果数据
        HotakeRolesInfoDto rolesInfoDto = selectHotakeRolesInfoDtoById(rolesInfo.getId());
        return rolesInfoDto;
    }


    /**
     * 初始化AI面试问题-临时的
     * @param roleId 岗位ID
     */
    private void createAiQuestion(Long roleId){
        HotakeAiInterviewQuestionsInfo questionsInfo = new HotakeAiInterviewQuestionsInfo();
        questionsInfo.setQuestionTitle("General Questions");
        questionsInfo.setFocusType("Personality & Culture");
        questionsInfo.setRoleId(roleId);
        questionsInfo.setRecruiterId(SecurityUtils.getUserId());
        questionsInfo.setOverview("This is General Questions Overview");

        List<AiQuestionDto> questionDtoList = new ArrayList<>();
        AiQuestionDto questionDto = new AiQuestionDto();
        questionDto.setQuestions("Can you provide an example of a situation where you had to work in a physically demanding environment?,How do you plan to handle tasks that require specific construction knowledge or skills that you may not have yet?");
        questionDtoList.add(questionDto);
        questionsInfo.setAiQuestionList(questionDtoList);

        hotakeAiInterviewQuestionsInfoService.insertHotakeAiInterviewQuestionsInfo(questionsInfo);
    }
}
