package com.jeeplus.human.practice.register.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.common.SecurityUtils;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.common.constant.CacheNames;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.human.enrollment.enrollmentRegistration.service.EnrollmentRegistrationService;
import com.jeeplus.human.enrollment.enrollmentRegistration.utils.SnowFlake;
import com.jeeplus.human.practice.register.domain.Registration;
import com.jeeplus.human.practice.register.domain.RegistrationBank;
import com.jeeplus.human.practice.register.domain.RegistrationExperience;
import com.jeeplus.human.practice.register.domain.RegistrationFamilyMembers;
import com.jeeplus.human.practice.register.mapper.FamilyMembersMapper;
import com.jeeplus.human.practice.register.mapper.InterRegistrationMapper;
import com.jeeplus.human.practice.register.mapper.RegistrationExperienceMapper;
import com.jeeplus.human.practice.register.service.dto.RegistrationDto;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.*;
import com.jeeplus.sys.service.dto.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author 王强
 * @version 1.0
 * @date 2023-09-13 14:11
 */
@Service
@Transactional
public class RegistrationService extends ServiceImpl<InterRegistrationMapper, Registration> {

    @Resource
    private InterRegistrationMapper mapper;

    @Resource
    private FamilyMembersMapper familyMembersMapper;

    @Resource
    private RegistrationBankService bankService;

    @Resource
    private RegistrationExperienceMapper experienceMapper;

    @Resource
    private EnrollmentRegistrationService enrollmentRegistrationService;

    @Autowired
    private RedisUtils redisUtils;

    public Integer findIdCardOnly(String idCard) throws Exception {
        QueryWrapper<Registration> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_card", idCard);
        queryWrapper.eq("del_flag", 0);
        // 删除基础信息表
        Integer integer = mapper.selectCount(queryWrapper);
        return integer;
    }

    public void updateStatusById(RegistrationDto dto) {
        mapper.updateStatusById(dto.getId(), dto.getType());
        //根据id将这一条实习登记信息物理删除
        mapper.deleteByIdOnPhysic(dto.getId());
    }

    public Registration findById(String id) {
        // 查询基础信息表
        Registration info = mapper.getById(id);
        if (null != info){
            List<RegistrationFamilyMembers> familyMembers = familyMembersMapper.getByRegisterId(id);
            info.setFamilyMembers(familyMembers);
            List<RegistrationExperience> experiences = experienceMapper.getByRegisterId(id);
            info.setExperiences(experiences);
            OfficeDTO officeDTO = SpringUtil.getBean(IOfficeApi.class).getParentOfficeById(info.getPracticeOffice());
            info.setParentOfficeName(officeDTO.getName());
        }
        return info;
    }

    public String remove(String id) {
        //根据手机号获取用户
        Registration registration = mapper.getById(id);
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByMobile(registration.getMobilePhone());
        if (userDTO != null){
            SpringUtil.getBean(IUserApi.class).deleteById(userDTO.getId());
        }
        //删除实习经验表的数据
        experienceMapper.deleteByRegisterId(id);
        //删除家庭成员表的数据
        familyMembersMapper.deleteByRegisterId(id);
        // 删除基础信息表
        mapper.removeById(id);

        return "操作成功";
    }

    /**
     * 实习人员登记表信息
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<RegistrationDto> findList(Page<RegistrationDto> page, RegistrationDto projectReportData) throws Exception{
        QueryWrapper<RegistrationDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition (projectReportData,RegistrationDto.class);
        queryWrapper.eq("a.del_flag","0");
        if (StringUtils.isNotBlank(projectReportData.getPracticeOffice())) {
            queryWrapper.eq("a.practice_office",projectReportData.getPracticeOffice());
        }
        if (StringUtils.isNotBlank(projectReportData.getCompanyId())) {
            queryWrapper.eq("so1.id",projectReportData.getCompanyId());
        }

        if (projectReportData.getCreateDates() != null && projectReportData.getCreateDates().length > 1) {
            // 添加条件
            queryWrapper.and(wrapper ->
                    wrapper.between("practice_start_day", projectReportData.getCreateDates()[0], projectReportData.getCreateDates()[1])
                            .or()
                            .between("practice_complete_day", projectReportData.getCreateDates()[0], projectReportData.getCreateDates()[1])
                            .or()
                            .le("practice_start_day", projectReportData.getCreateDates()[0])
                            .ge("practice_complete_day", projectReportData.getCreateDates()[1])
            );

        }

        if (StringUtils.isNotBlank(projectReportData.getMobilePhone())) {
            queryWrapper.like("a.mobile_phone",projectReportData.getMobilePhone());
        }
        if (StringUtils.isNotBlank(projectReportData.getName())) {
            queryWrapper.like("a.name",projectReportData.getName());
        }
        //性别
        if (StringUtils.isNotBlank(projectReportData.getSex())) {
            queryWrapper.eq("a.sex",projectReportData.getSex());
        }
        //身份证号码
        if (StringUtils.isNotBlank(projectReportData.getIdCard())) {
            queryWrapper.like("a.id_card",projectReportData.getIdCard());
        }
        //毕业院校
        if (StringUtils.isNotBlank(projectReportData.getGraduatedFrom())) {
            queryWrapper.like("a.graduated_from",projectReportData.getGraduatedFrom());
        }
        //专业
        if (StringUtils.isNotBlank(projectReportData.getSpeciality())) {
            queryWrapper.like("a.speciality",projectReportData.getSpeciality());
        }
        //qq/微信
        if (StringUtils.isNotBlank(projectReportData.getQqNum())) {
            queryWrapper.like("a.qq_num",projectReportData.getQqNum());
        }
        //实习单位名称
        if (StringUtils.isNotBlank(projectReportData.getPracticeUnitName())) {
            queryWrapper.like("a.practice_unit_name",projectReportData.getPracticeUnitName());
        }
        //项目经理
        if (StringUtils.isNotBlank(projectReportData.getProjectManager())) {
            queryWrapper.eq("a.project_manager",projectReportData.getProjectManager());
        }
        IPage<RegistrationDto> list = mapper.findList(page, queryWrapper);
        return list;

    }

    /**
     * 根据id查实习人员信息
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<RegistrationDto> findList2(Page<RegistrationDto> page, RegistrationDto projectReportData) throws Exception{
        QueryWrapper<RegistrationDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition (projectReportData,RegistrationDto.class);
        queryWrapper.eq("a.del_flag","0");
        queryWrapper.eq("a.id",projectReportData.getId());
        IPage<RegistrationDto> list = mapper.findList2(page, queryWrapper);
        return list;

    }

    public Registration saveRegistration(Registration registration) throws Exception {
        if (StringUtils.isNotEmpty(registration.getId())){

            Registration report = mapper.getById(registration.getId());
            if (report != null){
                return update(registration);
            }
        }
        return add(registration);
    }

    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    public Registration update(Registration reportData) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));

        Registration report = new Registration();
        BeanUtils.copyProperties(reportData, report);
        report.setUpdateById(userDTO.getId());
        report.setUpdateTime(new Date());

        //当审核通过的时候，将该人员加入到实习生角色中，根据联系电话发送短信到该实习生手机中，将实习状态改为“实习中”
        //根据他的姓名生成一个系统账号，就是创建一个用户信息
        if (StringUtils.isNotBlank(report.getType()) && !userDTO.isAdmin()){
            if (report.getType().equals("5")){
                //获取当前的用户，审核的人
                UserDTO dto = new UserDTO();
                //设置信息
                // 生成id
                String amountId = SnowFlake.getId();
                dto.setId(amountId);
                dto.setName(report.getName());
                dto.setPassword(SecurityUtils.encryptPassword("123456"));
                dto.setLoginName(report.getName());
                dto.setLoginFlag("1");
                dto.setMobile(report.getMobilePhone());
                dto.setTenantDTO(userDTO.getTenantDTO());
                dto.setCompanyDTO(userDTO.getCompanyDTO());
                OfficeDTO officeDTO = new OfficeDTO();
                officeDTO.setId(report.getPracticeOffice());
                dto.setOfficeDTO(officeDTO);

                OfficeDTO office = SpringUtil.getBean(IOfficeApi.class).getOfficeById(report.getPracticeOffice());
                // 获取实习生角色id
                Map<String,String> keyMap = new HashMap<>();
                keyMap.put("name", "实习生");
                keyMap.put("tenantId", office.getTenantId());
                List <RoleDTO> roleIdList = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(keyMap);
//                List <RoleDTO> roleIdList = new ArrayList<>();
//                roleIdList.add(roleInfo);
                dto.setRoleDTOList(roleIdList);


                //发送短信通知
                String officeName = "";
                String networkAddress = "";
                if (null != office) {
                    TenantDTO tenantDTO = new TenantDTO();
                    tenantDTO.setId(office.getTenantId());
                    dto.setTenantDTO(tenantDTO);
                    if (office.getTenantId().equals("10003")){
                        officeName = "会计业务管理公司";
                        networkAddress = "cpapmis.xgccpm.com";
                    }else if (office.getTenantId().equals("10004")) {
                        officeName = "中审管理公司";
                        networkAddress = "zs.xgccpm.com";
                    }else if (office.getTenantId().equals("10001")) {
                        officeName = "评估管理公司";
                        networkAddress = "http://amc.xgccpm.com";
                    }
                } else {
                    TenantDTO tenantDTO = new TenantDTO();
                    tenantDTO.setId("10002");
                    dto.setTenantDTO(tenantDTO);
                    officeName = "综合管理公司";
                }



                SpringUtil.getBean ( IUserApi.class ).saveOrUpdate(dto);


//                OfficeDTO office = SpringUtil.getBean(IOfficeApi.class).getOfficeById(report.getPracticeOffice());


                /*String randomCode = report.getName() + "你好!你好!欢迎来" + officeName + "实习，实习期间请及时在公司系统:" + networkAddress
                        + "中填写实习日志，系统初始账号密码为，系统初始账号密码为：" + report.getName() +
                        "/123456，请尽快登陆系统并修改初始密码！";*/
                Map<String, Object> stringObjectMap = SpringUtil.getBean(IUserApi.class).sendInternshipEntryRandomCodes(report.getMobilePhone(), report.getName(), officeName);
                Integer statusCode = (Integer) stringObjectMap.get("statusCode");
                if (200 == statusCode) {
                    System.out.println("短信发送成功!");
                } else if (10001 == statusCode) {
                    String message = (String) stringObjectMap.get("message");
                    System.out.println(message);
                }else if(10002 == statusCode){
                    System.out.println("账户短信量余额不足，请联系管理员进行充值!");
                }else if(10003 == statusCode){
                    System.out.println("手机号获取验证码次数已达每日上限!");
                } else {
                    System.out.println("短信发送失败，错误代码：101，请联系管理员!");
                }

                report.setPracticeStatus("0");
                report.setUserId(dto.getId());

                //发送完善工资卡信息  实习生完善银行卡号
                Map map = SpringUtil.getBean(IFlowableApi.class).getByNameForFen("实习生完善银行卡号");
                String procDefId = map.get("id")+"";

                //当流程结束的时候，发起工资卡信息完善流程
                String uid = SnowFlake.getId();
                RegistrationBank wageCard = new RegistrationBank();
                wageCard.setId(uid);
                wageCard.setCreateById("1");
                wageCard.setUpdateById("1");
                wageCard.setProcessDefinitionId(procDefId);
                wageCard.setRegisterId(report.getId());
                wageCard.setUserId(amountId);
                wageCard.setType("2");
                bankService.save(wageCard);

                String procDefKey = map.get("key")+"";
                String businessTable = "human_resources_practice_registration_bank";
                String businessId = uid;
                String title = "工资卡信息完善";
                String assignee = amountId;
                String recordType = "";
                Map<String,String> newMap = new HashMap();
                newMap.put("procDefId", procDefId);
                newMap.put("procDefKey", procDefKey);
                newMap.put("businessTable", businessTable);
                newMap.put("businessId", businessId);
                newMap.put("title", title);
                newMap.put("assignee", assignee);
                newMap.put("recordType", recordType);
                String procInsId = SpringUtil.getBean(IFlowableApi.class).startForFen(newMap);
            }
        }

        //先删除家庭成员信息，在重新添加
        familyMembersMapper.deleteByRegisterId(report.getId());
        List<RegistrationFamilyMembers> familyMembers = reportData.getFamilyMembers();
        if (CollectionUtils.isNotEmpty(familyMembers)){
            familyMembers.forEach(fa->{
                // 生成id
                String amountId = SnowFlake.getId();
                fa.setId(amountId);
                fa.setCreateById(userDTO.getId());
                fa.setCreateTime(new Date());
                fa.setUpdateById(userDTO.getId());
                fa.setUpdateTime(new Date());
                fa.setDelFlag(0);
                fa.setRegistrationId(report.getId());

                familyMembersMapper.insert(fa);
            });
        }
        //先删除实习经历信息
        experienceMapper.deleteByRegisterId(report.getId());
        List<RegistrationExperience> experiences = reportData.getExperiences();
        if (CollectionUtils.isNotEmpty(experiences)){
            experiences.forEach(fa->{
                // 生成id
                String amountId = UUID.randomUUID().toString().replace("-", "");
                fa.setId(amountId);
                fa.setCreateById(userDTO.getId());
                fa.setCreateTime(new Date());
                fa.setUpdateById(userDTO.getId());
                fa.setUpdateTime(new Date());
                fa.setDelFlag(0);
                fa.setRegistrationId(report.getId());

                experienceMapper.insert(fa);
            });
        }
        mapper.updateById(report);

        return report;
    }

    /**
     * 新增
     */
    @Transactional(rollbackFor = Exception.class)
    public Registration add(Registration reportData) throws Exception{

        String currentToken = TokenProvider.getCurrentToken();
        Registration report = new Registration();
        BeanUtils.copyProperties(reportData, report);

        QueryWrapper<Registration> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_card", reportData.getIdCard());
        queryWrapper.eq("del_flag", 0);
        Integer integer = mapper.selectCount(queryWrapper);

        Integer mobilePhoneOnly = enrollmentRegistrationService.findMobilePhoneOnly(reportData.getMobilePhone());
        // 删除基础信息表
        if (integer <=0 && mobilePhoneOnly <=0){

            String id = SnowFlake.getId();
            report.setId(id);
            report.setCreateById("1");
            report.setCreateTime(new Date());
            report.setUpdateById("1");
            report.setUpdateTime(new Date());

            String uid = SnowFlake.getId();
            report.setId(uid);

            //先删除家庭成员信息，在重新添加
            familyMembersMapper.deleteByRegisterId(report.getId());
            List<RegistrationFamilyMembers> familyMembers = reportData.getFamilyMembers();
            if (CollectionUtils.isNotEmpty(familyMembers)){

                for (RegistrationFamilyMembers familyMember : familyMembers) {
                    // 生成id
                    String amountId = SnowFlake.getId();
                    familyMember.setId(amountId);
                    familyMember.setCreateById("1");
                    familyMember.setCreateTime(new Date());
                    familyMember.setUpdateById("1");
                    familyMember.setUpdateTime(new Date());
                    familyMember.setDelFlag(0);
                    familyMember.setRegistrationId(report.getId());
                    familyMembersMapper.insert(familyMember);
                }
            }
            //先删除实习经历信息
            experienceMapper.deleteByRegisterId(report.getId());
            List<RegistrationExperience> experiences = reportData.getExperiences();
            if (CollectionUtils.isNotEmpty(experiences)){
                for (RegistrationExperience experience : experiences) {
                    // 生成id
                    String amountId = SnowFlake.getId();
                    experience.setId(amountId);
                    experience.setCreateById("1");
                    experience.setCreateTime(new Date());
                    experience.setUpdateById("1");
                    experience.setUpdateTime(new Date());
                    experience.setDelFlag(0);
                    experience.setRegistrationId(report.getId());

                    experienceMapper.insert(experience);
                }
            }



            //if (null == currentToken) {
                //发起实习登记流程
                Map map = SpringUtil.getBean(IFlowableApi.class).getByNameForFen("实习登记");
                String procDefId = map.get("id")+"";

                report.setProcessDefinitionId(procDefId);
                mapper.insert(report);

                Map<String ,Map<String,String >>  allMap = new HashMap<>();

                String procDefKey = map.get("key")+"";
                String businessTable = "human_resources_practice_registration";

                String businessId = uid;
                String title = "管理员发起了[" + report.getName() + "-实习登记]";

                //获取实习信息审核员信息
                RoleDTO roleDTO = SpringUtil.getBean(IRoleApi.class).getRoleDTOByName2("实习信息审核员");
                String assignee = getAssignee(roleDTO.getId());
                String recordType = "";

                Map<String, String> newMap = pingMap(procDefId, procDefKey, businessTable, businessId, title, assignee, recordType);
                allMap.put("实习",newMap);
                SpringUtil.getBean(IFlowableApi.class).startForFenNew(allMap);
            /*} else {
                mapper.insert(report);
            }*/

        }


        return report;
    }

    public Map<String,String> pingMap(String procDefId,String procDefKey,String businessTable,
                                      String businessId,String title,String assignee,String recordType){
        Map<String,String> map = new HashMap();
        map.put("procDefId", procDefId);
        map.put("procDefKey", procDefKey);
        map.put("businessTable", businessTable);
        map.put("businessId", businessId);
        map.put("title", title);
        map.put("assignee", assignee);
        map.put("recordType", recordType);
        return map;
    }

    public String getAssignee(String roleId){
        List<UserDTO> userDTOS = SpringUtil.getBean(IUserApi.class).findListByRoleId(roleId);
        StringJoiner idJoiner = new StringJoiner(",");
        for (UserDTO user : userDTOS) {
            idJoiner.add(String.valueOf(user.getId()));
        }

        return idJoiner.toString();
    }

    /**
     * 根据实习生的用户id修改实习状态
     * @param createById
     */
    public void updatePracticeStatus(String createById,String endTime) {
        mapper.updatePracticeStatus(createById,endTime);
    }

    /**
     * 查询超过3天未发起日志的实习中的信息
     * @return
     */
    public List<Registration> getTimeOutRegisters() {
        String dictValue = SpringUtil.getBean(IDictApi.class).getDictValue("remind_day", "practice_log_remind_day", "");
        Integer day = 7;//给个默认值，防止没有字典信息
        if(StringUtils.isNotBlank(dictValue)){
            day = Integer.valueOf(dictValue);
        }
        //获取3天前的时间
        String threeDayAgo = LocalDateTime.now().plusDays(-day).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        List<Registration> registrations = mapper.getTimeOutRegisters(threeDayAgo);
        return registrations;
    }

    /**
     * 获取最后一次发起报销且实习状态为结束，并且报销状态为完成的
     * @return
     */
    public List<Registration> getTimeOutReimburseRegisters() {
        List<Registration> registrations = mapper.getTimeOutReimburseRegisters();
        return registrations;
    }


    /**
     * 保存实习人员登记信息
     * @param registration
     */
    public void saveForm(Registration registration) throws Exception {
        if (StringUtils.isNotEmpty(registration.getId())){
            updateRegistration(registration);
        }else {
            addRegistration(registration);
        }
    }

    /**
     * 修改实习人员信息
     * @param reportData
     */
    public void updateRegistration(Registration reportData) {

        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));

        Registration report = new Registration();
        BeanUtils.copyProperties(reportData, report);
        report.setUpdateById(userDTO.getId());
        report.setUpdateTime(new Date());

        //先删除家庭成员信息，在重新添加
        familyMembersMapper.deleteByRegisterId(report.getId());
        List<RegistrationFamilyMembers> familyMembers = reportData.getFamilyMembers();
        if (CollectionUtils.isNotEmpty(familyMembers)){
            familyMembers.forEach(fa->{
                // 生成id
                String amountId = SnowFlake.getId();
                fa.setId(amountId);
                fa.setCreateById(userDTO.getId());
                fa.setCreateTime(new Date());
                fa.setUpdateById(userDTO.getId());
                fa.setUpdateTime(new Date());
                fa.setDelFlag(0);
                fa.setRegistrationId(report.getId());

                familyMembersMapper.insert(fa);
            });
        }
        //先删除实习经历信息
        experienceMapper.deleteByRegisterId(report.getId());
        List<RegistrationExperience> experiences = reportData.getExperiences();
        if (CollectionUtils.isNotEmpty(experiences)){
            experiences.forEach(fa->{
                // 生成id
                String amountId = SnowFlake.getId();
                fa.setId(amountId);
                fa.setCreateById(userDTO.getId());
                fa.setCreateTime(new Date());
                fa.setUpdateById(userDTO.getId());
                fa.setUpdateTime(new Date());
                fa.setDelFlag(0);
                fa.setRegistrationId(report.getId());

                experienceMapper.insert(fa);
            });
        }
        mapper.updateById(report);

        //根据用户手机号查询出用户信息
        UserDTO userInfo = SpringUtil.getBean(IUserApi.class).getByMobile(report.getMobilePhone());
        if (userInfo != null){
            //往用户表中新增一条数据
            UserDTO dto = new UserDTO();
            dto.setId(userInfo.getId());
            dto.setName(report.getName());
            dto.setLoginName(report.getName());
            dto.setMobile(report.getMobilePhone());
            dto.setNo(report.getMobilePhone());
            dto.setPhoto("");
            //根据实习部门获取部门信息
            OfficeDTO officeDTO = SpringUtil.getBean(IOfficeApi.class).getOfficeById(report.getPracticeOffice());
            dto.setOfficeDTO(officeDTO);
            OfficeDTO officeDTO1 = new OfficeDTO();
            officeDTO1.setId(officeDTO.getParent().getId());
            dto.setCompanyDTO(officeDTO1);
            List <RoleDTO> roleIdList = new ArrayList<>();

            if (null != officeDTO) {
                Map<String,String> keyMap = new HashMap<>();
                TenantDTO tenantDTO = new TenantDTO();
                tenantDTO.setId(officeDTO.getTenantId());
                dto.setTenantDTO(tenantDTO);
                if (officeDTO.getTenantId().equals("10003")){
                    dto.setLoginFlag("1");
                    keyMap.put("name", "实习生");
                    keyMap.put("tenantId", officeDTO.getTenantId());
                    roleIdList = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(keyMap);
                }else if (officeDTO.getTenantId().equals("10004")) {
                    keyMap.put("name", "中审员工,共有权限（中审）");
                    keyMap.put("tenantId", officeDTO.getTenantId());
                    roleIdList = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(keyMap);
                }else if (officeDTO.getTenantId().equals("10001")) {
                    dto.setLoginFlag("1");
                    keyMap.put("name", "实习生");
                    keyMap.put("tenantId", officeDTO.getTenantId());
                    roleIdList = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(keyMap);
                }
            } else {
                TenantDTO tenantDTO = new TenantDTO();
                tenantDTO.setId("10002");
                dto.setTenantDTO(tenantDTO);
            }
            dto.setRoleDTOList(roleIdList);
            //判断是否是中审证券部门的
            if (report.getPracticeStatus().equals("0") &&!officeDTO.getTenantId().equals("10004") && !officeDTO.getName().contains("证券")){
                dto.setLoginFlag("1");
            }

            SpringUtil.getBean ( IUserApi.class ).saveOrUpdate(dto);
        }


    }

    /**
     * 新增实习人员信息
     * @param reportData
     */
    public void addRegistration(Registration reportData) {

        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));

        Registration report = new Registration();
        BeanUtils.copyProperties(reportData, report);
        report.setUpdateById(userDTO.getId());
        report.setUpdateTime(new Date());
        report.setCreateById(userDTO.getId());
        report.setCreateTime(new Date());
        report.setType("5");
        String reportId = SnowFlake.getId();
        report.setId(reportId);
        //家庭成员信息添加
        List<RegistrationFamilyMembers> familyMembers = reportData.getFamilyMembers();
        if (CollectionUtils.isNotEmpty(familyMembers)){
            familyMembers.forEach(fa->{
                // 生成id
                String amountId = SnowFlake.getId();
                fa.setId(amountId);
                fa.setCreateById(userDTO.getId());
                fa.setCreateTime(new Date());
                fa.setUpdateById(userDTO.getId());
                fa.setUpdateTime(new Date());
                fa.setDelFlag(0);
                fa.setRegistrationId(report.getId());

                familyMembersMapper.insert(fa);
            });
        }
        //实习经历信息
        List<RegistrationExperience> experiences = reportData.getExperiences();
        if (CollectionUtils.isNotEmpty(experiences)){
            experiences.forEach(fa->{
                // 生成id
                String amountId = SnowFlake.getId();
                fa.setId(amountId);
                fa.setCreateById(userDTO.getId());
                fa.setCreateTime(new Date());
                fa.setUpdateById(userDTO.getId());
                fa.setUpdateTime(new Date());
                fa.setDelFlag(0);
                fa.setRegistrationId(report.getId());

                experienceMapper.insert(fa);
            });
        }
        mapper.insert(report);

        //往用户表中新增一条数据
        UserDTO dto = new UserDTO();
        dto.setId(SnowFlake.getId());
        dto.setName(report.getName());
        dto.setPassword(SecurityUtils.encryptPassword("123456"));
        dto.setLoginName(report.getName());
        dto.setLoginFlag("0");
        dto.setMobile(report.getMobilePhone());
        dto.setNo(report.getMobilePhone());
        dto.setPhoto("");
        //根据实习部门获取部门信息
        OfficeDTO officeDTO = SpringUtil.getBean(IOfficeApi.class).getOfficeById(report.getPracticeOffice());
        dto.setOfficeDTO(officeDTO);
        OfficeDTO officeDTO1 = new OfficeDTO();
        officeDTO1.setId(officeDTO.getParent().getId());
        dto.setCompanyDTO(officeDTO1);
        List <RoleDTO> roleIdList = new ArrayList<>();

        if (null != officeDTO) {
            Map<String,String> keyMap = new HashMap<>();
            TenantDTO tenantDTO = new TenantDTO();
            tenantDTO.setId(officeDTO.getTenantId());
            dto.setTenantDTO(tenantDTO);
            if (officeDTO.getTenantId().equals("10003")){
                dto.setLoginFlag("1");
                keyMap.put("name", "实习生");
                keyMap.put("tenantId", officeDTO.getTenantId());
                roleIdList = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(keyMap);
            }else if (officeDTO.getTenantId().equals("10004")) {
                keyMap.put("name", "中审员工,共有权限（中审）");
                keyMap.put("tenantId", officeDTO.getTenantId());
                roleIdList = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(keyMap);
            }else if (officeDTO.getTenantId().equals("10001")) {
                dto.setLoginFlag("1");
                keyMap.put("name", "实习生");
                keyMap.put("tenantId", officeDTO.getTenantId());
                roleIdList = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(keyMap);
            }else if (officeDTO.getTenantId().equals("10005")) {
                keyMap.put("name", "项目公司员工,共有权限（项目）");
                keyMap.put("tenantId", officeDTO.getTenantId());
                roleIdList = SpringUtil.getBean(IRoleApi.class).getRoleDTOByNameAndTenantId(keyMap);
            }
        } else {
            TenantDTO tenantDTO = new TenantDTO();
            tenantDTO.setId("10002");
            dto.setTenantDTO(tenantDTO);
        }
        dto.setRoleDTOList(roleIdList);
        SpringUtil.getBean ( IUserApi.class ).saveOrUpdate(dto);
    }

    /**
     * 下载实习登记信息
     * @param response
     * @param id
     * @return
     */
    public Map getInfoMap(HttpServletResponse response, String id) {
        Map data = new HashMap<>();

        Registration registration = mapper.getById(id);
        if (registration != null){
            //基本信息
            if (StringUtils.isNotBlank(registration.getName())){
                data.put("name",registration.getName());
            }else {
                data.put("name","");
            }
            if (StringUtils.isNotBlank(registration.getSex())){
                if (registration.getSex().equals("1")){
                    data.put("sex","男");
                }else {
                    data.put("sex","女");
                }
            }else {
                data.put("sex","");
            }
            if (StringUtils.isNotBlank(registration.getIdCard())) {
                data.put("idCard", registration.getIdCard());
            } else {
                data.put("idCard", "");
            }
            //出生地
            if (StringUtils.isNotBlank(registration.getNativePlace())) {
                data.put("nativePlace", registration.getNativePlace());
            } else {
                data.put("nativePlace", "");
            }
            //民族
            if (StringUtils.isNotBlank(registration.getNation())) {
                data.put("nation", registration.getNation());
            } else {
                data.put("nation", "");
            }

            if (StringUtils.isNotBlank(registration.getPoliticalOutlook())) {
                String dictLabel = SpringUtil.getBean(IDictApi.class).getDictLabel(registration.getPoliticalOutlook(), "political_outlook", "");
                data.put("politicalOutlook", dictLabel);
            } else {
                data.put("politicalOutlook", "");
            }

            if (StringUtils.isNotBlank(registration.getGraduatedFrom())) {
                data.put("graduatedFrom", registration.getGraduatedFrom());
            } else {
                data.put("graduatedFrom", "");
            }

            if (StringUtils.isNotBlank(registration.getSpeciality())) {
                data.put("speciality", registration.getSpeciality());
            } else {
                data.put("speciality", "");
            }

            if (StringUtils.isNotBlank(registration.getMobilePhone())) {
                data.put("mobilePhone", registration.getMobilePhone());
            } else {
                data.put("mobilePhone", "");
            }

            if (StringUtils.isNotBlank(registration.getQqNum())) {
                data.put("qqNum", registration.getQqNum());
            } else {
                data.put("qqNum", "");
            }

            if (StringUtils.isNotBlank(registration.getPracticeStartDay())) {
                data.put("practiceStartDay", registration.getPracticeStartDay());
            } else {
                data.put("practiceStartDay", "");
            }

            if (StringUtils.isNotBlank(registration.getPracticeOffice())) {
                OfficeDTO officeDTO = SpringUtil.getBean(IOfficeApi.class).getOfficeById(registration.getPracticeOffice());
                data.put("practiceOffice", officeDTO.getName());
            } else {
                data.put("practiceOffice", "");
            }

            if (StringUtils.isNotBlank(registration.getPracticeUnitName())) {
                data.put("practiceUnitName", registration.getPracticeUnitName());
            } else {
                data.put("practiceUnitName", "");
            }

            if (StringUtils.isNotBlank(registration.getProjectManager())) {
                UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getById(registration.getProjectManager());
                data.put("projectManager", userDTO.getName());
            } else {
                data.put("projectManager", "");
            }

            if (StringUtils.isNotBlank(registration.getRemarks())) {
                int maxLineLength = 42; // 您可以根据需要调整这个值
                StringBuilder formattedRemarks = new StringBuilder();

                // 遍历每个字符并在需要时添加换行符
                for (int i = 0; i < registration.getRemarks().length(); i++) {
                    formattedRemarks.append(registration.getRemarks().charAt(i));
                    // 在每maxLineLength个字符后添加换行符
                    if ((i + 1) % maxLineLength == 0) {
                        formattedRemarks.append("\n");
                    }
                }

                data.put("remarks", formattedRemarks.toString());
            } else {
                data.put("remarks", "");
            }

            if (StringUtils.isNotBlank(registration.getPracticeCompleteDay())) {
                data.put("practiceCompleteDay", registration.getPracticeCompleteDay());
            } else {
                data.put("practiceCompleteDay", "");
            }

            // 实习经历
            List<RegistrationExperience> experiences = experienceMapper.getByRegisterId(id);
            if (CollectionUtils.isNotEmpty(experiences)) {
                for (RegistrationExperience experience : experiences) {
                    if (StringUtils.isBlank(experience.getStartTime())){
                        experience.setStartTime("");
                    }
                    if (StringUtils.isBlank(experience.getEndTime())){
                        experience.setEndTime("");
                    }
                    if (StringUtils.isBlank(experience.getPracticeUnit())){
                        experience.setPracticeUnit("");
                    }
                    if (StringUtils.isBlank(experience.getPost())){
                        experience.setPost("");
                    }
                }
                while (experiences.size() < 2) {
                    RegistrationExperience registrationExperience = new RegistrationExperience();
                    registrationExperience.setStartTime("");
                    registrationExperience.setEndTime("");
                    registrationExperience.setPracticeUnit("");
                    registrationExperience.setPost("");
                    experiences.add(registrationExperience);
                }
                data.put("experiences", experiences);
            } else {
                ArrayList<RegistrationExperience> list = new ArrayList<>();
                for (int i = 0; i < 2; i++) {
                    RegistrationExperience registrationExperience = new RegistrationExperience();
                    registrationExperience.setStartTime("");
                    registrationExperience.setEndTime("");
                    registrationExperience.setPracticeUnit("");
                    registrationExperience.setPost("");
                    list.add(registrationExperience);
                }
                data.put("experiences",list);
            }

            // 家庭成员
            List<RegistrationFamilyMembers> familyMembers = familyMembersMapper.getByRegisterId(id);
            if (CollectionUtils.isNotEmpty(familyMembers)) {
                for (RegistrationFamilyMembers familyMember : familyMembers) {
                    if (StringUtils.isBlank(familyMember.getCallName())){
                        familyMember.setCallName("");
                    }
                    if (StringUtils.isBlank(familyMember.getName())){
                        familyMember.setName("");
                    }
                    if (StringUtils.isBlank(familyMember.getPhone())){
                        familyMember.setPhone("");
                    }
                    if (StringUtils.isBlank(familyMember.getWorkUnit())){
                        familyMember.setWorkUnit("");
                    }
                }
                while (familyMembers.size()<2){
                    RegistrationFamilyMembers members = new RegistrationFamilyMembers();
                    members.setCallName("");
                    members.setName("");
                    members.setPhone("");
                    members.setWorkUnit("");
                    familyMembers.add(members);
                }
                data.put("familyMembers", familyMembers);
            } else {
                ArrayList<RegistrationFamilyMembers> list = new ArrayList<>();
                for (int i = 0; i < 2; i++) {
                    RegistrationFamilyMembers members = new RegistrationFamilyMembers();
                    members.setCallName("");
                    members.setName("");
                    members.setPhone("");
                    members.setWorkUnit("");
                    list.add(members);
                }
                data.put("familyMembers",list );
            }

        }else {
            data.put("name","");
            data.put("sex","");
            data.put("idCard", "");
            data.put("nativePlace", "");
            data.put("nation", "");
            data.put("politicalOutlook", "");
            data.put("graduatedFrom", "");
            data.put("speciality", "");
            data.put("mobilePhone", "");
            data.put("qqNum", "");
            data.put("practiceStartDay", "");
            data.put("practiceOffice", "");
            data.put("practiceUnitName", "");
            data.put("remarks", "");
            data.put("projectManager", "");
            data.put("practiceCompleteDay", "");
            ArrayList<RegistrationExperience> list = new ArrayList<>();
            while (list.size()<2){
                RegistrationExperience registrationExperience = new RegistrationExperience();
                registrationExperience.setStartTime("");
                registrationExperience.setEndTime("");
                registrationExperience.setPracticeUnit("");
                registrationExperience.setPost("");
                list.add(registrationExperience);
            }
            data.put("experiences",list);

            ArrayList<RegistrationFamilyMembers> list1 = new ArrayList<>();
            while (list1.size()<2){
                RegistrationFamilyMembers members = new RegistrationFamilyMembers();
                members.setCallName("");
                members.setName("");
                members.setPhone("");
                members.setWorkUnit("");
                list1.add(members);
            }
            data.put("familyMembers",list1 );
        }


        return data;
    }

    /**
     * 获取所有的实习人员信息
     * @return
     */
    public List<Registration> getAllRegister() {
        return mapper.getAllRegister();
    }

    /**
     * 定时任务修改实习状态
     * @param id
     */
    public void adminUpdatePracticeStatus(String id) {
        mapper.adminUpdatePracticeStatus(id);
    }
}
