package com.ruoyi.cms.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.domain.entity.MyChart;
import com.ruoyi.common.core.domain.entity.File;
import com.ruoyi.cms.domain.vo.AppSkillVo;
import com.ruoyi.cms.mapper.*;
import com.ruoyi.cms.util.StringUtil;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.cms.domain.vo.AppUserLky;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SiteSecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.ruoyi.cms.service.IAppUserService;
import org.springframework.transaction.annotation.Transactional;

/**
 * APP用户Service业务层处理
 *
 * @author lishundong
 * @date 2024-09-03
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper,AppUser> implements IAppUserService
{
    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private JobTitleMapper jobTitleMapper;
    @Autowired
    private CompanyContactMapper companyContactMapper;
    @Autowired
    private UserWorkExperiencesMapper userWorkExperiencesMapper;
    @Autowired
    private AppSkillMapper appSkillMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private FileMapper fileMapper;

    /**
     * 查询APP用户
     *
     * @param userId APP用户主键
     * @return APP用户
     */
    @Override
    public AppUser selectAppUserByUserId(Long userId)
    {
        AppUser appUser = appUserMapper.selectById(userId);
        if(StringUtils.isNotEmpty(appUser.getJobTitleId())){
            List<String> list = Arrays.asList(appUser.getJobTitleId().split(","));
            List<Long> collect = list.stream().map(Long::valueOf).collect(Collectors.toList());
            List<JobTitle> jobs = jobTitleMapper.selectBatchIds(collect);
            appUser.setJobTitle(jobs.stream().map(JobTitle::getJobName).collect(Collectors.toList()));
        }
        //查询企业信息
        if("0".equals(appUser.getIsCompanyUser())){
            Company company=companyMapper.selectOne(Wrappers.<Company>lambdaQuery().eq(Company::getCode, appUser.getIdCard()).orderByDesc(Company::getUpdateTime).last("LIMIT 1"));
            appUser.setCompany(company);
            if(company!=null){
                CompanyContact contact=new CompanyContact();
                contact.setCompanyId(company.getCompanyId());
                List<CompanyContact> companyContactList=companyContactMapper.getSelectList(contact);
                company.setCompanyContactList(companyContactList);
            }
        }else if("1".equals(appUser.getIsCompanyUser())){
            UserWorkExperiences workExperiences=new UserWorkExperiences();
            workExperiences.setUserId(appUser.getUserId());
            List<UserWorkExperiences> experiences =userWorkExperiencesMapper.getWorkExperiencesList(workExperiences);
            appUser.setExperiencesList(experiences);

            AppSkill skill=new AppSkill();
            skill.setUserId(appUser.getUserId());
            List<AppSkill> skillList=appSkillMapper.getList(skill);
            appUser.setAppSkillsList(skillList);
        }
        return appUser;
    }

    /**
     * 查询APP用户列表
     *
     * @param appUser APP用户
     * @return APP用户
     */
    @Override
    public List<AppUser> selectAppUserList(AppUser appUser)
    {
        return appUserMapper.selectAppUserList(appUser);
    }

    /**
     * 新增APP用户
     *
     * @param appUser APP用户
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertAppUser(AppUser appUser)
    {
        return appUserMapper.insert(appUser);
    }

    /**
     * 修改APP用户
     *
     * @param appUser APP用户
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateAppUser(AppUser appUser)
    {
        //工作经历
        if(appUser.getExperiencesList()!=null&&appUser.getExperiencesList().size()>0){
            List<UserWorkExperiences> add=new ArrayList<>();
            List<UserWorkExperiences> upp=new ArrayList<>();
            appUser.getExperiencesList().forEach(it->{
                if(it.getId()!=null){upp.add(it);}else{it.setUserId(appUser.getUserId());add.add(it);}
            });
            if(add.size()>0){
                userWorkExperiencesMapper.batchInsert(appUser.getExperiencesList());
            }
            if(upp.size()>0){
                upp.forEach(it->{
                    it.setCreateTime(null);
                    it.setUserId(it.getUserId()==null?appUser.getUserId():it.getUserId());
                    userWorkExperiencesMapper.updateById(it);
                });
            }
        }
        //技能
        if(appUser.getAppSkillsList()!=null&&appUser.getAppSkillsList().size()>0){
            List<AppSkill> add=new ArrayList<>();
            List<AppSkill> upp=new ArrayList<>();
            appUser.getAppSkillsList().forEach(it->{
                if(it.getId()!=null){upp.add(it);}else{it.setUserId(appUser.getUserId());add.add(it);}
            });
            if(add.size()>0){
                appSkillMapper.batchInsert(appUser.getAppSkillsList());
            }
            if(upp.size()>0){
                upp.forEach(it->{
                    it.setCreateTime(null);
                    it.setUserId(it.getUserId()==null?appUser.getUserId():it.getUserId());
                    appSkillMapper.updateById(it);
                });
            }
        }
        //添加一体机密码
        if(StringUtils.isNotEmpty(appUser.getYtjPassword())){
            appUser.setYtjPassword(SiteSecurityUtils.encryptPassword(appUser.getYtjPassword()));
        }
        return appUserMapper.updateById(appUser);
    }

    /**
     * 批量删除APP用户
     *
     * @param userIds 需要删除的APP用户主键
     * @return 结果
     */
    @Override
    public int deleteAppUserByUserIds(Long[] userIds)
    {
        return appUserMapper.deleteBatchIds(Arrays.asList(userIds));
    }

    @Override
    public AppUser getPhone(String phone) {
        return appUserMapper.selectOne(new LambdaQueryWrapper<AppUser>()
                .eq(AppUser::getPhone, phone).eq(AppUser::getDelFlag,"0").orderByDesc(AppUser::getUpdateTime).last("LIMIT 1"));
    }

    @Override
    public AppUser getPhoneAndNoRole(String phone) {
        return appUserMapper.selectOne(new LambdaQueryWrapper<AppUser>()
                .eq(AppUser::getPhone, phone).eq(AppUser::getDelFlag,"0").isNull(AppUser::getIsCompanyUser).orderByDesc(AppUser::getUpdateTime).last("LIMIT 1"));
    }

    @Override
    public AppUser getPhoneAndUserType(String phone,String userType) {
        return appUserMapper.selectOne(new LambdaQueryWrapper<AppUser>()
                .eq(AppUser::getPhone, phone).eq(AppUser::getIsCompanyUser,userType).eq(AppUser::getDelFlag,"0").orderByDesc(AppUser::getUpdateTime).last("LIMIT 1"));
    }

    @Override
    public AppUser selectByOpenid(String openid,String userType) {
        return appUserMapper.selectByOpenid(openid,userType);
    }

    @Override
    public AppUser registerAppUser(RegisterBody registerBody) {
        AppUser appUser=registerBody.getAppUser();
        System.out.println("userId================"+SiteSecurityUtils.getUserId());
        if(SiteSecurityUtils.isLogin()){
            AppUser appUserResult=appUserMapper.selectById(SiteSecurityUtils.getUserId());
            if(appUser==null){
                appUser=appUserResult;
            }else{
                appUser.setPhone(appUserResult.getPhone());
                appUser.setUserId(appUserResult.getUserId());
            }
        }
        //角色集合
        Map<String,Object> mapUserRole=new HashMap<>();
        switch (appUser.getIsCompanyUser()){
            case StringUtil.IS_COMPANY_USER://企业
                if(registerBody.getCompany()!=null){
                    Company company=registerBody.getCompany();
                    Long companyId=company.getCompanyId();
                    if(companyId==null){
                        companyMapper.insert(registerBody.getCompany());
                        registerBody.getCompany().getCompanyContactList().forEach(it->{
                            it.setCompanyId(registerBody.getCompany().getCompanyId());
                        });
                    }
                    if(registerBody.getCompany().getCompanyContactList()!=null&&registerBody.getCompany().getCompanyContactList().size()>0){
                        companyContactMapper.batchInsert(registerBody.getCompany().getCompanyContactList());
                    }
                    //保存app_user信息
                    appUser.setIdCard(company.getCode());
                    appUser.setName(company.getName());
                }
                mapUserRole.put("roleId",StringUtil.SYS_QY);
                break;
            default://求职者
                if(registerBody.getExperiencesList()!=null&&registerBody.getExperiencesList().size()>0){
                    registerBody.getExperiencesList().forEach(it->{
                        it.setUserId(SiteSecurityUtils.getUserId());
                    });
                    userWorkExperiencesMapper.batchInsert(registerBody.getExperiencesList());
                }
                if(registerBody.getAppSkillsList()!=null&&registerBody.getAppSkillsList().size()>0){
                    registerBody.getAppSkillsList().forEach(it->{
                        it.setUserId(SiteSecurityUtils.getUserId());
                    });
                    appSkillMapper.batchInsert(registerBody.getAppSkillsList());
                }
                mapUserRole.put("roleId",StringUtil.SYS_QZZ);
        }
        //保存sys_user
        SysUser  parmUser=appUserMapper.selectSysUserIdcard(appUser.getIdCard());
        if(parmUser==null){
            registerInsertSysUser(appUser,mapUserRole);
        }
        //一体机密码
        if(StringUtils.isNotEmpty(appUser.getYtjPassword())){
            appUser.setYtjPassword(SiteSecurityUtils.encryptPassword(appUser.getYtjPassword()));
        }
        appUserMapper.updateById(appUser);
        return appUser;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppUser registerAppUserNew(RegisterBody registerBody) {
        // 1. 参数校验
        validateRegisterParam(registerBody);

        // 2. 获取基础数据
        AppUser appUser = registerBody.getAppUser();
        Long loginUserId = SiteSecurityUtils.getUserId();

        // 3. 登录态处理：关联已有用户信息
        AppUser existingUser = handleLoginUserAssociation(appUser, loginUserId);

        // 4. 差异化业务处理（企业用户/求职者）
        handleUserTypeSpecificLogic(existingUser, registerBody);

        // 5. 系统用户同步（不存在则创建）
        syncSysUserIfNecessary(existingUser);

        // 6. 一体机密码加密处理
        encryptYtjPassword(existingUser);

        // 7. 更新App用户信息
        appUserMapper.updateById(existingUser);

        return existingUser;
    }

    /**
     * 注册参数校验
     * @param registerBody 注册请求体
     */
    private void validateRegisterParam(RegisterBody registerBody) {
        if (registerBody == null) {
            throw new IllegalArgumentException("注册请求参数不能为空");
        }
    }

    /**
     * 处理登录用户关联逻辑
     * @param appUser 注册传入的用户信息
     * @param loginUserId 登录用户ID
     * @return 关联后的用户信息
     */
    private AppUser handleLoginUserAssociation(AppUser appUser, Long loginUserId) {
        if (SiteSecurityUtils.isLogin() && loginUserId != null) {
            AppUser dbUser = appUserMapper.selectById(loginUserId);
            if (dbUser != null) {
                if (appUser == null) {
                    return dbUser;
                } else {
                    appUser.setPhone(dbUser.getPhone());
                    appUser.setUserId(dbUser.getUserId());
                    return appUser;
                }
            }
        }
        return appUser;
    }

    /**
     * 处理不同用户类型的差异化业务逻辑
     * @param appUser 用户信息
     * @param registerBody 注册请求体
     */
    private void handleUserTypeSpecificLogic(AppUser appUser, RegisterBody registerBody) {
        String userType = appUser.getIsCompanyUser();
        switch (userType) {
            case StringUtil.IS_COMPANY_USER:
                handleCompanyUserLogic(appUser, registerBody.getCompany());
                break;
            default:
                handleJobSeekerUserLogic(appUser, registerBody);
                break;
        }
    }

    /**
     * 处理企业用户注册逻辑
     * @param appUser 企业用户信息
     * @param company 企业信息
     */
    private void handleCompanyUserLogic(AppUser appUser, Company company) {
        if (company != null) {
            // 保存企业信息（新增场景）
            if (company.getCompanyId() == null) {
                companyMapper.insert(company);
                // 批量保存企业联系人
                saveCompanyContacts(company.getCompanyId(), company.getCompanyContactList());
            }
            // 关联企业信息到用户
            appUser.setIdCard(company.getCode());
            appUser.setName(company.getName());
        }
    }

    /**
     * 批量保存企业联系人
     * @param companyId 企业ID
     * @param contactList 联系人列表
     */
    private void saveCompanyContacts(Long companyId, List<CompanyContact> contactList) {
        if (contactList != null && !contactList.isEmpty()) {
            contactList.forEach(contact -> contact.setCompanyId(companyId));
            companyContactMapper.batchInsert(contactList);
        }
    }

    /**
     * 处理求职者用户注册逻辑
     * @param appUser 求职者用户信息
     * @param registerBody 注册请求体
     */
    private void handleJobSeekerUserLogic(AppUser appUser, RegisterBody registerBody) {
        Long userId = appUser.getUserId();
        // 保存工作经历
        saveUserWorkExperiences(userId, registerBody.getExperiencesList());
        // 保存技能信息
        saveUserAppSkills(userId, registerBody.getAppSkillsList());
    }

    /**
     * 批量保存用户工作经历
     * @param userId 用户ID
     * @param experiencesList 工作经历列表
     */
    private void saveUserWorkExperiences(Long userId, List<UserWorkExperiences> experiencesList) {
        if (experiencesList != null && !experiencesList.isEmpty()) {
            experiencesList.forEach(experience -> experience.setUserId(userId));
            userWorkExperiencesMapper.batchInsert(experiencesList);
        }
    }

    /**
     * 批量保存用户技能信息
     * @param userId 用户ID
     * @param skillsList 技能列表
     */
    private void saveUserAppSkills(Long userId, List<AppSkill> skillsList) {
        if (skillsList != null && !skillsList.isEmpty()) {
            skillsList.forEach(skill -> skill.setUserId(userId));
            appSkillMapper.batchInsert(skillsList);
        }
    }

    /**
     * 同步系统用户（不存在则创建）
     * @param appUser App用户信息
     */
    private void syncSysUserIfNecessary(AppUser appUser) {
        SysUser sysUser = appUserMapper.selectSysUserIdcard(appUser.getIdCard());
        if (sysUser == null) {
            // 构建角色映射
            Map<String, Object> roleMap = buildUserRoleMap(appUser.getIsCompanyUser());
            // 创建系统用户及角色关联
            registerInsertSysUser(appUser, roleMap);
        }
    }

    /**
     * 构建用户角色映射
     * @param userType 用户类型
     * @return 角色ID映射
     */
    private Map<String, Object> buildUserRoleMap(String userType) {
        Map<String, Object> roleMap = new HashMap<>();
        if (StringUtil.IS_COMPANY_USER.equals(userType)) {
            roleMap.put("roleId", StringUtil.SYS_QY);
        } else {
            roleMap.put("roleId", StringUtil.SYS_QZZ);
        }
        return roleMap;
    }

    /**
     * 加密一体机密码
     * @param appUser 用户信息
     */
    private void encryptYtjPassword(AppUser appUser) {
        if (StringUtils.hasText(appUser.getYtjPassword())) {
            appUser.setYtjPassword(SiteSecurityUtils.encryptPassword(appUser.getYtjPassword()));
        }
    }

    /**
     * 保存系统用户及角色关联
     * @param appUser App用户信息
     * @param roleMap 角色映射（包含roleId）
     */
    private void registerInsertSysUser(AppUser appUser, Map<String, Object> roleMap) {
        // 构建系统用户
        SysUser sysUser = buildSysUser(appUser);
        // 插入系统用户
        appUserMapper.insertSysUser(sysUser);
        // 关联用户角色
        roleMap.put("userId", sysUser.getUserId());
        appUserMapper.insertSysUserRole(roleMap);
    }

    /**
     * 构建系统用户对象
     * @param appUser App用户信息
     * @return 系统用户对象
     */
    private SysUser buildSysUser(AppUser appUser) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(StringUtil.USER_KEY + appUser.getIdCard());
        sysUser.setNickName(StringUtils.isEmpty(appUser.getName()) ? appUser.getPhone() : appUser.getName());
        sysUser.setPassword(SiteSecurityUtils.encryptPassword("123456"));
        sysUser.setPhonenumber(appUser.getPhone());
        sysUser.setSex(appUser.getSex());
        sysUser.setStatus("0");
        sysUser.setLoginIp(appUser.getLoginIp());
        sysUser.setLoginDate(appUser.getLoginDate());
        sysUser.setIdCard(appUser.getIdCard());
        return sysUser;
    }


    @Override
    public AppUser selectAppuserByIdcard(String idCard) {
        return appUserMapper.selectOne(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getIdCard, idCard).eq(AppUser::getDelFlag,"0").orderByDesc(AppUser::getUpdateTime).last("LIMIT 1"));
    }

    @Override
    public AppUserLky selectAppUserInfo(AppUser appUser) {
        AppUserLky lky=new AppUserLky();
        appUser=appUserMapper.selectById(appUser.getUserId());
        if(StringUtils.isNotEmpty(appUser.getJobTitleId())){
            List<String> list = Arrays.asList(appUser.getJobTitleId().split(","));
            List<Long> collect = list.stream().map(Long::valueOf).collect(Collectors.toList());
            List<JobTitle> jobs = jobTitleMapper.selectBatchIds(collect);
            lky.setJobTitles(jobs.stream().map(JobTitle::getJobName).collect(Collectors.toList()));
        }
        //查询用户技能
        AppSkill parmsk=new AppSkill();
        parmsk.setUserId(appUser.getUserId());
        List<AppSkillVo> skillList=appSkillMapper.getUserSkillList(parmsk);
        //回填
        lky.setAppSkillsList(skillList);
        return lky;
    }

    @Override
    public AppUser getUserInfo() {
        //查询用户信息
        LoginUser loginUser=SecurityUtils.getLoginUser();
        System.out.println("loginUser========================"+JSON.toJSONString(loginUser));
        SysUser sysUser=loginUser.getUser();
        System.out.println("sysUser========================"+JSON.toJSONString(sysUser));
        AppUser appUser=selectAppuserByIdcard(sysUser.getIdCard());
        System.out.println("appUser========================"+JSON.toJSONString(appUser));
        if(appUser!=null&&appUser.getUserId()!=null){
            //查询工作经历信息
            UserWorkExperiences parm=new UserWorkExperiences();
            parm.setUserId(appUser.getUserId());
            List<UserWorkExperiences> experiencesList=userWorkExperiencesMapper.getWorkExperiencesList(parm);
            appUser.setExperiencesList(experiencesList);
            //查询用户技能
            AppSkill parmsk=new AppSkill();
            parmsk.setUserId(appUser.getUserId());
            List<AppSkill> skillList=appSkillMapper.getList(parmsk);
            appUser.setAppSkillsList(skillList);

            //查询附件
            File fileParm=new File();
            fileParm.setBussinessid(appUser.getUserId());
            List<File> files=fileMapper.selectFileList(fileParm);
            appUser.setFileList(files);

            //查询足迹
            MyChart myChart=appUserMapper.getMyTj(appUser.getUserId());
            appUser.setMyChart(myChart);
        }
        return appUser;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editRegisterUser(RegisterBody registerBody) {
        Long userId=registerBody.getAppUser().getUserId();
        if(userId!=null){
            //保存或修改工作经历
            List<UserWorkExperiences> userWorkExperiencesList=registerBody.getExperiencesList();
            editUserWorkExperiences(userWorkExperiencesList,userId);
            //修改技能
            List<AppSkill> skillList=registerBody.getAppSkillsList();
            editSkill(skillList,userId);
            //修改用户信息
            AppUser appUser=registerBody.getAppUser();
            if(appUser!=null&&appUser.getUserId()!=null){
                appUserMapper.updateById(appUser);
            }
        }
        return 1;
    }

    /**
     * 修改技能
     * @param list
     */
    public void editSkill(List<AppSkill> list,Long userId){
        if(list!=null&&list.size()>0){
            List<AppSkill> add=new ArrayList<>();
            list.forEach(it->{
                it.setUserId(userId);
                if(it.getId()!=null){appSkillMapper.updateById(it);}else{add.add(it);}
            });
            if(add.size()>0){
                appSkillMapper.batchInsert(add);
            }
        }
    }

    /**
     * 修改工作经历
     * @param list
     */
    public void editUserWorkExperiences(List<UserWorkExperiences> list,Long userId){
        if(list!=null&&list.size()>0){
            List<UserWorkExperiences> add=new ArrayList<>();
            list.forEach(it->{
                it.setUserId(userId);
                if(it.getId()!=null){userWorkExperiencesMapper.updateById(it);}else{add.add(it);}
            });
            if(add.size()>0){
                userWorkExperiencesMapper.batchInsert(add);
            }
        }
    }

    @Override
    public List<AppUser> selectNoTmAppUserList(AppUser appUser)
    {
        return appUserMapper.selectAppUserList(appUser);
    }

    @Override
    public MyChart getMyTj(Long userId) {
        return appUserMapper.getMyTj(userId);
    }

    @Override
    public List<AppUserShow> selectUserApplyList(AppUser appUser) {
        List<AppUserShow> list=appUserMapper.selectUserApplyList(appUser);
        if(list!=null){
            //身份证脱敏处理
            list.forEach(x->{
                x.setIdCard(StringUtil.desensitizeIdCard(x.getIdCard()));
            });
        }
        return list;
    }
}
