package com.ruoyi.cms.service.impl;

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

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)
    {
        List<AppUser> list=appUserMapper.selectAppUserList(appUser);
        if(list!=null){
            //身份证脱敏处理
            list.forEach(x->{
                x.setIdCard(StringUtil.desensitizeIdCard(x.getIdCard()));
            });
        }
        return list;
    }

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

    /**
     * 修改APP用户
     *
     * @param appUser APP用户
     * @return 结果
     */
    @Override
    public int updateAppUser(AppUser appUser)
    {
        if(appUser.getExperiencesList()!=null&&appUser.getExperiencesList().size()>0){
            userWorkExperiencesMapper.batchInsert(appUser.getExperiencesList());
        }
        if(appUser.getAppSkillsList()!=null&&appUser.getAppSkillsList().size()>0){
            appSkillMapper.batchInsert(appUser.getAppSkillsList());
        }
        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).orderByDesc(AppUser::getUpdateTime).last("LIMIT 1"));
    }

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

    @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 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 sysUser=new SysUser();
        sysUser.setUserName(appUser.getPhone());
        sysUser.setNickName(StringUtils.isEmpty(appUser.getName())?appUser.getPhone():appUser.getName());
        sysUser.setPassword(SecurityUtils.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());
        appUserMapper.insertSysUser(sysUser);
        //保存sys_user_role
        mapUserRole.put("userId",sysUser.getUserId());
        appUserMapper.insertSysUserRole(mapUserRole);
        //一体机密码
        if(StringUtils.isNotEmpty(appUser.getYtjPassword())){
            appUser.setYtjPassword(SiteSecurityUtils.encryptPassword(appUser.getYtjPassword()));
        }
        appUserMapper.updateById(appUser);
        return appUser;
    }

    @Override
    public AppUser selectAppuserByIdcard(String idCard) {
        return appUserMapper.selectOne(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getIdCard, idCard).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();
        SysUser sysUser=loginUser.getUser();
        AppUser appUser=selectAppuserByIdcard(sysUser.getIdCard());
        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);
    }
}
