package com.jeeplus.test.roster.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.core.excel.utils.EasyPoiUtil;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.security.util.SecurityUtils;
import com.jeeplus.sys.constant.enums.OfficeTypeEnum;
import com.jeeplus.sys.domain.*;
import com.jeeplus.sys.mapper.UserMapper;
import com.jeeplus.sys.service.CertService;
import com.jeeplus.sys.service.OfficeService;
import com.jeeplus.sys.service.UserService;
import com.jeeplus.sys.service.dto.CertDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.service.mapstruct.CertWrapper;
import com.jeeplus.sys.utils.DictUtils;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.cw.common.CommonUtils;
import com.jeeplus.test.cw.invoice.service.dto.CwFinanceInvoiceDetailDTO;
import com.jeeplus.test.jobPosion.service.dto.JobPositionDTO;
import com.jeeplus.test.jobPosion.utils.BeanUtils;
import com.jeeplus.test.mould.service.SerialnumTplService;
import com.jeeplus.test.oss.service.OssService;
import com.jeeplus.test.rank.service.dto.RankSystemTableDTO;
import com.jeeplus.test.roster.domain.*;
import com.jeeplus.test.roster.mapper.RosterBaseMapper;
import com.jeeplus.test.roster.service.dto.*;
import com.jeeplus.test.roster.service.mapstruct.*;
import com.jeeplus.test.workContract.service.dto.WorkContractInfoDto;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.jeeplus.test.jobPosion.utils.BeanUtils.objectCheckIsNull;

@Service
@Transactional(rollbackFor = Exception.class)
public class RosterBaseService extends ServiceImpl<RosterBaseMapper, RosterBase> {

    @Autowired
    private RosterBaseMapper rosterBaseMapper;

    @Autowired
    private RosterContractService rosterContractService;

    @Autowired
    private RosterBankCardsService rosterBankCardsService;

    @Autowired
    private RosterEducateService rosterEducateService;

    @Autowired
    private RosterFamilyService rosterFamilyService;

    @Autowired
    private RosterWorkService rosterWorkService;

    @Autowired
    private RosterFilesService rosterFilesService;

    @Autowired
    private RosterCertificateService rosterCertificateService;

    @Autowired
    private RosterLeadershipService rosterLeadershipService;

    @Autowired
    private OssService ossService;

    @Autowired
    private SerialnumTplService serialnumTplService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CertService certService;

    public IPage<RosterBaseDTO> findList(Page<RosterBaseDTO> page, RosterBaseDTO rosterBaseDTO) throws Exception {
        RosterBase rosterBase = RosterBaseWrapper.INSTANCE.toEntity(rosterBaseDTO);
        QueryWrapper<RosterBase> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( rosterBase, RosterBase.class );
        queryWrapper.eq("rb.del_flag","0");
        if(ObjectUtil.isNotEmpty(rosterBaseDTO)){
            if(StringUtils.isNotBlank(rosterBaseDTO.getCompanyId())){
                // 根据公司层级筛选
                queryWrapper.eq("soc.id",rosterBaseDTO.getCompanyId());
            }else if(StringUtils.isNotBlank(rosterBaseDTO.getOfficeId())){
                // 根据部门层级筛选
                queryWrapper.eq("soo.id",rosterBaseDTO.getOfficeId());
            }
            if (StringUtils.isNotBlank(rosterBaseDTO.getOfficeSelect())) {
                //  根据部门筛选
                List<User> userList = userService.list(new LambdaQueryWrapper<User>().eq(User::getOfficeId, rosterBaseDTO.getOfficeSelect()));
                List<String> ids = userList.stream().distinct().map(User::getRosterId).collect(Collectors.toList());
                queryWrapper.in("rb.id",ids);
            }
            if (StringUtils.isNotBlank(rosterBaseDTO.getPostSelect())) {
                //  根据岗位筛选
                List<User> userByPost = userService.getUserIdByPost(rosterBaseDTO.getPostSelect());
                List<String> ids = userByPost.stream().distinct().map(User::getRosterId).collect(Collectors.toList());
                queryWrapper.in("rb.id",ids);
            }
            if (ObjectUtil.isNotEmpty(rosterBaseDTO.getDates())) {
                queryWrapper.between("rb.onboarding_date", rosterBaseDTO.getDates()[0], rosterBaseDTO.getDates()[1]);
            }
        }
        IPage<RosterBaseDTO> rosterBaseDTOIPage = rosterBaseMapper.findList(page, queryWrapper);
        if(CollectionUtil.isNotEmpty(rosterBaseDTOIPage.getRecords())){
            rosterBaseDTOIPage.getRecords().stream().forEach(item->{
//                头像获取到新的临时地址展示
//                if(StringUtils.isNotBlank(item.getHeadshot())){
//                    String fileTemporaryLookUrl = ossService.getFileTemporaryLookUrl(item.getHeadshot());
//                    item.setHeadshotLsUrl(fileTemporaryLookUrl);
//                }
                if (CollectionUtil.isNotEmpty(item.getPostList())) {
                    String postNames = item.getPostList().stream().filter(filter ->{
                        if(ObjectUtil.isNotEmpty(filter)) {
                            if (StringUtils.isNotBlank(filter.getName())) {
                                return true;
                            }
                        }
                        return false;
                    }).map(Post::getName).collect(Collectors.joining(","));
                    item.setPostNames(postNames);
                }
                if (CollectionUtil.isNotEmpty(item.getRoleList())) {
                    String roleNames = item.getRoleList().stream().filter(filter ->{
                        if(ObjectUtil.isNotEmpty(filter)) {
                            if (StringUtils.isNotBlank(filter.getName())) {
                                return true;
                            }
                        }
                        return false;
                    }).map(Role::getName).collect(Collectors.joining(","));
                    item.setRoleNames(roleNames);
                }
            });
        }
        return rosterBaseDTOIPage;
    }

    public RosterBaseDTO queryById(String id){
        RosterBaseDTO rosterBaseDTO = rosterBaseMapper.queryById(id);
        if(ObjectUtil.isNotEmpty(rosterBaseDTO)){
            if(StringUtils.isNotBlank(rosterBaseDTO.getCertificatesFront())){
                String front = ossService.getFileTemporaryLookUrl(rosterBaseDTO.getCertificatesFront());
                rosterBaseDTO.setCertificatesFrontLsUrl(front);
            }
            if(StringUtils.isNotBlank(rosterBaseDTO.getHeadshot())){
                String headshot = ossService.getFileTemporaryLookUrl(rosterBaseDTO.getHeadshot());
                rosterBaseDTO.setHeadshotLsUrl(headshot);
            }
            if(StringUtils.isNotBlank(rosterBaseDTO.getCertificatesBack())){
                String back = ossService.getFileTemporaryLookUrl(rosterBaseDTO.getCertificatesBack());
                rosterBaseDTO.setCertificatesBackLsUrl(back);
            }
            if(CollectionUtil.isNotEmpty(rosterBaseDTO.getRosterBankCardsDTOList())){
                rosterBaseDTO.getRosterBankCardsDTOList().stream().forEach(item->{
                    if(StringUtils.isNotBlank(item.getPayrollCardPic())){
                        String cardPic = ossService.getFileTemporaryLookUrl(item.getPayrollCardPic());
                        item.setPayrollCardPicLsUrl(cardPic);
                    }
                });
            }
            if(CollectionUtil.isNotEmpty(rosterBaseDTO.getRosterEducateDTOList())){
                rosterBaseDTO.getRosterEducateDTOList().stream().forEach(item->{
                    if(StringUtils.isNotBlank(item.getEducationCertFirst())){
                        String certFirst = ossService.getFileTemporaryLookUrl(item.getEducationCertFirst());
                        item.setEducationCertFirstLsUrl(certFirst);
                    }
                    if(StringUtils.isNotBlank(item.getEducationCertFirst())){
                        String certSecond = ossService.getFileTemporaryLookUrl(item.getEducationCertSecond());
                        item.setEducationCertSecondLsUrl(certSecond);
                    }
                });
            }
            if(CollectionUtil.isNotEmpty(rosterBaseDTO.getRosterFamilyDTOList())){
                rosterBaseDTO.getRosterFamilyDTOList().stream().forEach(item->{
                    if(StringUtils.isNotBlank(item.getBirthCertificate())){
                        String birth = ossService.getFileTemporaryLookUrl(item.getBirthCertificate());
                        item.setBirthCertificateLsUrl(birth);
                    }
                });
            }
            // 查询花名册关联用户的信息
            User user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getRosterId, id));
            List<CertDTO> certDTOList = new ArrayList<>();
            if (ObjectUtil.isNotEmpty(user)) {
                // 获取用户资质
                List<Cert> certList = userService.getCertListByUserId(user.getId());  // 根据用户id获取资质信息
                if (CollectionUtil.isNotEmpty(certList)) {
                    certList.stream().forEach(c -> {
                        CertDTO certDTO = CertWrapper.INSTANCE.toDTO(c);
                        if (StringUtils.isNotBlank(certDTO.getFileUrl())) {  //  根据oss图片路径获取图片临时地址
                            String fileLsUrl = ossService.getFileTemporaryLookUrl(certDTO.getFileUrl());
                            certDTO.setFileLsUrl(fileLsUrl);
                        }
                        certDTOList.add(certDTO);
                    });
                }
                // 获取用户的公司
                if (StringUtils.isNotBlank(user.getCompanyId())) {
                    rosterBaseDTO.setCompanyId(user.getCompanyId());
                }
                // 获取用户角色
                List<String> userRole = userMapper.getUserRole(user.getId());
                if (CollectionUtil.isNotEmpty(userRole)) {
                    rosterBaseDTO.setRoleIdList(userRole);
                }
                // 获取用户岗位
                List<String> userPost = userMapper.getUserPost(user.getId());
                if (CollectionUtil.isNotEmpty(userPost)) {
                    rosterBaseDTO.setPostIdList(userPost);
                }
                // 获取用户的管理部门
                if (StringUtils.isNotBlank(user.getManageOfficeIds())) {
                    rosterBaseDTO.setManageOfficeIds(user.getManageOfficeIds());
                }
            }
            rosterBaseDTO.setCertDTOList(certDTOList);
        }
        return rosterBaseDTO;
    }

    public ResponseEntity saveRoster(RosterBaseDTO rosterBaseDTO) throws Exception{

        if(ObjectUtil.isNotEmpty(rosterBaseDTO)){
            if(StringUtils.isNotBlank(rosterBaseDTO.getId())){
                RosterBase byId = this.getById(rosterBaseDTO.getId());
                // 原数据的人员类型为员工，现在要修改成游客，
                // 原数据关联的用户删除掉
                // 删除原数据关联表的数据，删除与游客无关的数据
                if ("1".equals(byId.getPersonType()) && "2".equals(rosterBaseDTO.getPersonType())) {
                    // 原数据关联的用户删除掉
                    // 通过花名册id查询用户
                    List<User> ulist = userService.list(new QueryWrapper<User>().lambda().eq(User::getRosterId, rosterBaseDTO.getId()));
                    if (CollectionUtil.isNotEmpty(ulist)) {
                        ulist.stream().forEach(i -> {
                            // 通过花名册id删除用户
                            userService.removeById(i.getId());
                            UserDTO u = new UserDTO();
                            u.setId(i.getId());
                            // 删除用户关联的管理部门信息
                            userMapper.deleteUserManageOffice(u);  //  根据用户id删除用户的管理部门信息
                            // 删除用户关联的岗位信息
                            userMapper.deleteUserPost(i.getId());
                            // 删除用户关联的角色信息
                            userMapper.deleteUserRole(i.getId());
                        });
                    }
                    //  删除原数据关联表的数据，清空与游客无关的字段
                    rosterBaseDTO = this.deleteRosterWorker(rosterBaseDTO);
                }
                // 身份证号唯一验证（排除自己）
                if(StringUtils.isNotBlank(rosterBaseDTO.getIdCard())){
                    List<RosterBase> rosterBaseList = this.list(new QueryWrapper<RosterBase>().eq("id_card", rosterBaseDTO.getIdCard()).ne("id",rosterBaseDTO.getId()));
                    if(CollectionUtil.isNotEmpty(rosterBaseList)){
                        return ResponseEntity.badRequest().body("基础信息-身份证号 已存在，保存失败");
                    }
                }
                // 手机号唯一验证（排除自己）
                if(StringUtils.isNotBlank(rosterBaseDTO.getMobile())){
                    List<RosterBase> rosterBaseList = this.list(new QueryWrapper<RosterBase>().eq("mobile", rosterBaseDTO.getMobile()).ne("id",rosterBaseDTO.getId()));
                    if(CollectionUtil.isNotEmpty(rosterBaseList)){
                        return ResponseEntity.badRequest().body("基础信息-手机号码 已存在，保存失败");
                    }
                }
            }else{
                // 身份证号唯一验证
                if(StringUtils.isNotBlank(rosterBaseDTO.getIdCard())){
                    List<RosterBase> rosterBaseList = this.list(new QueryWrapper<RosterBase>().eq("id_card", rosterBaseDTO.getIdCard()));
                    if(CollectionUtil.isNotEmpty(rosterBaseList)){
                        return ResponseEntity.badRequest().body("基础信息-身份证号 已存在，保存失败");
                    }
                }
                // 手机号唯一验证
                if(StringUtils.isNotBlank(rosterBaseDTO.getMobile())){
                    List<RosterBase> rosterBaseList = this.list(new QueryWrapper<RosterBase>().eq("mobile", rosterBaseDTO.getMobile()));
                    if(CollectionUtil.isNotEmpty(rosterBaseList)){
                        return ResponseEntity.badRequest().body("基础信息-手机号码 已存在，保存失败");
                    }
                }
            }
            if ("1".equals(rosterBaseDTO.getPersonType())) { // 当前人员是员工时
                //获取当前登录人信息
                UserDTO userDTO = UserUtils.getCurrentUserDTO();
                //工号生成
                String serialNum = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), RosterBaseDTO.BIZ_CODE);
                if (StringUtils.isNotBlank(rosterBaseDTO.getId())) {
                    RosterBase byId = this.getById(rosterBaseDTO.getId());
                    if (StringUtils.isBlank(byId.getJobNo())) {
                        rosterBaseDTO.setJobNo(serialNum);  // 游客转员工，保存时，生成工号
                    }
                } else {
                    rosterBaseDTO.setJobNo(serialNum);  // 员工新增生成工号
                }
            }
        }


        RosterBase rosterBase = RosterBaseWrapper.INSTANCE.toEntity(rosterBaseDTO);



        // 新增或修改花名册数据
        this.saveOrUpdate(rosterBase);

        // 新增或修改用户数据(花名册的人员类型为员工时)
        if ("1".equals(rosterBase.getPersonType())) {
            this.saveOrUpdateUser(rosterBase, CommonUtils.getFirstCompanyId());
        }

        if(ObjectUtil.isNotEmpty(rosterBaseDTO)){
            //保存合同信息
            if(ObjectUtil.isNotEmpty(rosterBaseDTO.getRosterContractDTO())){
                RosterContract rosterContract = RosterContractWrapper.INSTANCE.toEntity(rosterBaseDTO.getRosterContractDTO());
                rosterContract.setBaseId(rosterBase.getId());
                rosterContractService.remove(new QueryWrapper<RosterContract>().eq("base_id",rosterBase.getId()));
                rosterContractService.saveOrUpdate(rosterContract);
            } else {
                rosterContractService.remove(new QueryWrapper<RosterContract>().eq("base_id",rosterBase.getId()));
            }
            //保存银行卡信息
            if(CollectionUtil.isNotEmpty(rosterBaseDTO.getRosterBankCardsDTOList())){
                List<String> collect = rosterBaseDTO.getRosterBankCardsDTOList().stream().map(RosterBankCardsDTO::getId).collect(Collectors.toList());
                rosterBankCardsService.remove(new QueryWrapper<RosterBankCards>().eq("base_id",rosterBase.getId()).notIn(CollectionUtil.isNotEmpty(collect),"id",collect));
                rosterBaseDTO.getRosterBankCardsDTOList().stream().forEach(item->{
                    if(ObjectUtil.isNotEmpty(item)&& BeanUtils.objectCheckIsNull(item)){
                        RosterBankCards rosterBankCards = RosterBankCardsWrapper.INSTANCE.toEntity(item);
                        rosterBankCards.setBaseId(rosterBase.getId());
                        rosterBankCardsService.saveOrUpdate(rosterBankCards);
                    }
                });
            }else{
                rosterBankCardsService.remove(new QueryWrapper<RosterBankCards>().eq("base_id",rosterBase.getId()));
            }
            //保存教育经历
            if(CollectionUtil.isNotEmpty(rosterBaseDTO.getRosterEducateDTOList())){
                List<String> collect = rosterBaseDTO.getRosterEducateDTOList().stream().map(RosterEducateDTO::getId).collect(Collectors.toList());
                rosterEducateService.remove(new QueryWrapper<RosterEducate>().eq("base_id",rosterBase.getId()).notIn(CollectionUtil.isNotEmpty(collect),"id",collect));
                rosterBaseDTO.getRosterEducateDTOList().stream().forEach(item->{
                    if(ObjectUtil.isNotEmpty(item)&& BeanUtils.objectCheckIsNull(item)){
                        RosterEducate rosterEducate = RosterEducateWrapper.INSTANCE.toEntity(item);
                        rosterEducate.setBaseId(rosterBase.getId());
                        rosterEducateService.saveOrUpdate(rosterEducate);
                    }
                });
            }else{
                rosterEducateService.remove(new QueryWrapper<RosterEducate>().eq("base_id",rosterBase.getId()));
            }
            //保存工作经历
            if(CollectionUtil.isNotEmpty(rosterBaseDTO.getRosterWorkDTOList())){
                List<String> collect = rosterBaseDTO.getRosterWorkDTOList().stream().map(RosterWorkDTO::getId).collect(Collectors.toList());
                rosterWorkService.remove(new QueryWrapper<RosterWork>().eq("base_id",rosterBase.getId()).notIn(CollectionUtil.isNotEmpty(collect),"id",collect));
                rosterBaseDTO.getRosterWorkDTOList().stream().forEach(item->{
                    if(ObjectUtil.isNotEmpty(item)&& BeanUtils.objectCheckIsNull(item)){
                        RosterWork rosterWork = RosterWorkWrapper.INSTANCE.toEntity(item);
                        rosterWork.setBaseId(rosterBase.getId());
                        rosterWorkService.saveOrUpdate(rosterWork);
                    }
                });
            }else{
                rosterWorkService.remove(new QueryWrapper<RosterWork>().eq("base_id",rosterBase.getId()));
            }
            //保存家庭成员
            if(CollectionUtil.isNotEmpty(rosterBaseDTO.getRosterFamilyDTOList())){
                List<String> collect = rosterBaseDTO.getRosterFamilyDTOList().stream().map(RosterFamilyDTO::getId).collect(Collectors.toList());
                rosterFamilyService.remove(new QueryWrapper<RosterFamily>().eq("base_id",rosterBase.getId()).notIn(CollectionUtil.isNotEmpty(collect),"id",collect));
                rosterBaseDTO.getRosterFamilyDTOList().stream().forEach(item->{
                    if(ObjectUtil.isNotEmpty(item)&& BeanUtils.objectCheckIsNull(item)){
                        RosterFamily rosterFamily = RosterFamilyWrapper.INSTANCE.toEntity(item);
                        rosterFamily.setBaseId(rosterBase.getId());
                        rosterFamilyService.saveOrUpdate(rosterFamily);
                    }
                });
            }else{
                rosterFamilyService.remove(new QueryWrapper<RosterFamily>().eq("base_id",rosterBase.getId()));
            }
            //保存员工证书
            if(CollectionUtil.isNotEmpty(rosterBaseDTO.getRosterCertificateDTOList())){
                List<String> collect = rosterBaseDTO.getRosterCertificateDTOList().stream().map(RosterCertificateDTO::getId).collect(Collectors.toList());
                rosterCertificateService.remove(new QueryWrapper<RosterCertificate>().eq("base_id",rosterBase.getId()).notIn(CollectionUtil.isNotEmpty(collect),"id",collect));
                rosterBaseDTO.getRosterCertificateDTOList().stream().forEach(item->{
                    if(ObjectUtil.isNotEmpty(item)&& BeanUtils.objectCheckIsNull(item)){
                        RosterCertificate rosterCertificate = RosterCertificateWrapper.INSTANCE.toEntity(item);
                        rosterCertificate.setBaseId(rosterBase.getId());
                        rosterCertificateService.saveOrUpdate(rosterCertificate);
                    }
                });
            }else{
                rosterCertificateService.remove(new QueryWrapper<RosterCertificate>().eq("base_id",rosterBase.getId()));
            }
            //保存附件
            if(CollectionUtil.isNotEmpty(rosterBaseDTO.getRosterFilesDTOList())){
                List<String> collect = rosterBaseDTO.getRosterFilesDTOList().stream().distinct().filter(item->{
                    if(StringUtils.isNotBlank(item.getId())){
                        return true;
                    }
                    return false;
                }).map(RosterFilesDTO::getId).collect(Collectors.toList());
                rosterFilesService.remove(new QueryWrapper<RosterFiles>().eq("base_id",rosterBase.getId()).notIn(CollectionUtil.isNotEmpty(collect),"id",collect));
                rosterBaseDTO.getRosterFilesDTOList().stream().forEach(item->{
                    if(ObjectUtil.isNotEmpty(item)&& BeanUtils.objectCheckIsNull(item)){
                        RosterFiles rosterFiles = RosterFilesWrapper.INSTANCE.toEntity(item);
                        rosterFiles.setBaseId(rosterBase.getId());
                        if(StringUtils.isNotBlank(item.getCreateBy().getId())){
                            rosterFiles.setCreateBy(item.getCreateBy().getId());
                        }
                        rosterFilesService.saveOrUpdate(rosterFiles);
                    }
                });
            }else{
                rosterFilesService.remove(new QueryWrapper<RosterFiles>().eq("base_id",rosterBase.getId()));
            }
            //保存直属领导
            if(ObjectUtil.isNotEmpty(rosterBaseDTO.getRosterLeadershipDTO())){
                RosterLeadership rosterLeadership = RosterLeadershipWrapper.INSTANCE.toEntity(rosterBaseDTO.getRosterLeadershipDTO());
                rosterLeadership.setBaseId(rosterBase.getId());
                rosterLeadershipService.remove(new QueryWrapper<RosterLeadership>().eq("base_id",rosterBase.getId()));
                rosterLeadershipService.saveOrUpdate(rosterLeadership);
            }else{
                rosterLeadershipService.remove(new QueryWrapper<RosterLeadership>().eq("base_id",rosterBase.getId()));
            }
            User user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getRosterId, rosterBase.getId()));
            if (ObjectUtil.isNotEmpty(user)) {
                // 保存花名册关联用户的资质信息
                certService.remove(new QueryWrapper<Cert>().lambda().eq(Cert::getUserId,user.getId()));
                if(ObjectUtil.isNotEmpty(rosterBaseDTO.getCertDTOList())){
                    List<Cert> certList = new ArrayList<>();
                    rosterBaseDTO.getCertDTOList().stream().forEach(i -> {
                        Cert cert = CertWrapper.INSTANCE.toEntity(i);
                        cert.setUserId(user.getId());
                        cert.setId("");
                        certList.add(cert);
                    });
                    if (CollectionUtil.isNotEmpty(certList)) {
                        certService.saveBatch(certList);
                    }
                }
                // 保存花名册关联用户的角色
                userMapper.deleteUserRole(user.getId());  //  删除用户的角色
                if (CollectionUtil.isNotEmpty(rosterBaseDTO.getRoleIdList())) {
                    rosterBaseDTO.getRoleIdList().stream().forEach(i -> {
                        userMapper.insertUserRole(user.getId(), i);  // 插入用户的角色
                    });
                }
                // 保存花名册关联用户的岗位
                userMapper.deleteUserPost(user.getId());  //  删除用户的岗位
                if (CollectionUtil.isNotEmpty(rosterBaseDTO.getPostIdList())) {
                    rosterBaseDTO.getPostIdList().stream().forEach(i -> {
                        userMapper.insertUserPost(user.getId(), i);  // 插入用户的岗位
                    });
                }
                // 保存花名册关联用户的管理部门
                UserDTO u = new UserDTO();
                u.setId(user.getId());
                userMapper.deleteUserManageOffice(u);  //  删除用户的管理部门 （用户、管理部门关联表）
                String oIds = "";
                if (StringUtils.isNotBlank(rosterBaseDTO.getManageOfficeIds())) {
                    List<String> officeIds= Arrays.asList(rosterBaseDTO.getManageOfficeIds().split(","));
                    officeIds.stream().forEach(officeId -> {
                        userMapper.insertUserManageOffice(officeId,user.getId());  // 插入用户的管理部门 （用户、管理部门关联表）
                    });
                    oIds = rosterBaseDTO.getManageOfficeIds();
                }
                userMapper.updateUserManageOffice(oIds, user.getId()); // 修改用户的管理部门 （用户表）
            }
        }
        return ResponseEntity.ok("花名册保存成功");
    }

    // 导入花名册excel
    public ResponseEntity importFile(MultipartFile file) {
        try {
            Integer successNum = 0;
            List<RosterBase> rosterList = new ArrayList<>();
            // 获取上传文件中的数据
            List <RosterBaseDTO> list = EasyPoiUtil.importExcel ( file, 1, 1, RosterBaseDTO.class );
            //去除excel中的空行
            list = getExcelList(list);
            for (RosterBaseDTO rosterBaseDTO : list) {
                // 姓名为必填项
                if (StringUtils.isBlank(rosterBaseDTO.getName())) {
                    return ResponseEntity.badRequest().body ("导入花名册失败！文件中有姓名未填写");
                }
                // 姓名唯一验证
//                List<RosterBase> rs = this.list(new QueryWrapper<RosterBase>().lambda().eq(RosterBase::getName, rosterBaseDTO.getName()));
//                if (CollectionUtil.isNotEmpty(rs)) {
//                    return ResponseEntity.badRequest().body ("导入花名册失败！人员“"+ rosterBaseDTO.getName() +"”已存在，请重新填写");
//                }

                // 人员类型必填
                if (StringUtils.isBlank(rosterBaseDTO.getPersonType())) {
                    return ResponseEntity.badRequest().body ("导入花名册失败！文件中有人员类型未填写");
                }
                // 验证人员类型填写是否符合要求
                String personType = DictUtils.getDictValue(rosterBaseDTO.getPersonType(), "roster_person_type","null");
                if ("null".equals(personType)) {
                    return ResponseEntity.badRequest().body ("导入花名册失败！文件中有人员类型填写错误，请重新填写");
                }
                // 人员类型转换
                rosterBaseDTO.setPersonType(personType);

                // 人员类型为员工
                if ("1".equals(personType)) {
                    if (StringUtils.isBlank(rosterBaseDTO.getOfficeName())) {
                        return ResponseEntity.badRequest().body ("导入花名册失败！人员类型为员工的时候，部门为必填项");
                    }
                    if (StringUtils.isBlank(rosterBaseDTO.getCertificatesType())) {
                        return ResponseEntity.badRequest().body ("导入花名册失败！人员类型为员工的时候，证件类型为必填项");
                    }
                    if (StringUtils.isBlank(rosterBaseDTO.getIdCard())) {
                        return ResponseEntity.badRequest().body ("导入花名册失败！人员类型为员工的时候，证件号为必填项");
                    }
                    if (StringUtils.isBlank(rosterBaseDTO.getWorkerType())) {
                        return ResponseEntity.badRequest().body ("导入花名册失败！人员类型为员工的时候，员工类型为必填项");
                    }
                } else {
                    // 人员类型为 游客 的时候，不填写部门和员工类型
                    rosterBaseDTO.setOfficeName("");
                    rosterBaseDTO.setWorkerType("");
                }

                if (StringUtils.isNotBlank(rosterBaseDTO.getOfficeName())) {
                    // 查询这个部门是否存在于当前系统中，不存在则不进行导入数据操作，抛出提示
                    List<Office> officeList = officeService.list(new QueryWrapper<Office>().lambda().eq(Office::getType, OfficeTypeEnum.OFFICE.getValue()).eq(Office::getName, rosterBaseDTO.getOfficeName()));
                    if (CollectionUtil.isEmpty(officeList)) {
                        return ResponseEntity.badRequest().body("导入花名册失败！文件中的部门”" + rosterBaseDTO.getOfficeName() + "“不存在，请重新填写");
                    }
                    // 部门填写符合要求，将部门名字转换为部门id
                    rosterBaseDTO.setOfficeId(officeList.get(0).getId());
                }

                if (StringUtils.isNotBlank(rosterBaseDTO.getCertificatesType())) {
                    // 验证证件类型填写是否符合要求
                    String certificatesType = DictUtils.getDictValue(rosterBaseDTO.getCertificatesType(), "certificates_type","null");
                    if ("null".equals(certificatesType)) {
                        return ResponseEntity.badRequest().body ("导入花名册失败！文件中有证件类型填写错误，请重新填写");
                    }
                    // 证件类型转换
                    rosterBaseDTO.setCertificatesType(certificatesType);
                }

                if (StringUtils.isNotBlank(rosterBaseDTO.getIdCard())) {
                    // 证件号唯一验证
                    List<RosterBase> rosterBaseList = this.list(new QueryWrapper<RosterBase>().eq("id_card", rosterBaseDTO.getIdCard()));
                    if(CollectionUtil.isNotEmpty(rosterBaseList)){
                        return ResponseEntity.badRequest().body("导入花名册失败！文件中证件号”" + rosterBaseDTO.getIdCard() + "“已存在，请重新填写");
                    }
                }

                // 电话号码必填
                if (StringUtils.isBlank(rosterBaseDTO.getMobile())) {
                    return ResponseEntity.badRequest().body ("导入花名册失败！文件中有电话号码未填写");
                }
                // 电话号码唯一验证
                List<RosterBase> mobileList = this.list(new QueryWrapper<RosterBase>().lambda().eq(RosterBase::getMobile, rosterBaseDTO.getMobile()));
                if (CollectionUtil.isNotEmpty(mobileList)) {
                    return ResponseEntity.badRequest().body ("导入花名册失败！文件中有电话号码已存在，请重新填写");
                }

                if (StringUtils.isNotBlank(rosterBaseDTO.getWorkerType())) {
                    // 验证员工类型填写是否符合要求
                    String workerType = DictUtils.getDictValue(rosterBaseDTO.getWorkerType(), "worker_type","null");
                    if ("null".equals(workerType)) {
                        return ResponseEntity.badRequest().body ("导入花名册失败！文件中有员工类型填写错误，请重新填写");
                    }
                    // 员工类型转换
                    rosterBaseDTO.setWorkerType(workerType);
                }

                // 生成最终数据
                RosterBase rosterBase = RosterBaseWrapper.INSTANCE.toEntity(rosterBaseDTO);
                rosterList.add(rosterBase);
                successNum++;
            }
            if (CollectionUtil.isNotEmpty(rosterList)) {
                String companyId = CommonUtils.getFirstCompanyId();
                // 批量新增花名册数据
                this.saveBatch(rosterList);
                rosterList.stream().forEach(r -> {
                    // 人员类型为员工时,同步新增用户信息
                    if ("1".equals(r.getPersonType())) {
                        this.saveOrUpdateUser(r, companyId);
                    }
                });
            }
            return ResponseEntity.ok ( "已成功导入 " + successNum + " 条数据" );
        } catch (Exception e) {
            return ResponseEntity.badRequest().body ( "导入花名册失败！失败信息：" + e.getMessage ( ) );
        }
    }
    /**
     * 去除excel中的空行
     * @param list
     * @return
     */
    public ArrayList<RosterBaseDTO> getExcelList(List<RosterBaseDTO> list){

        ArrayList<RosterBaseDTO> rosterBaseDTOS = new ArrayList<>();

        list.stream().forEach(item->{
            if(objectCheckIsNull(item)){
                rosterBaseDTOS.add(item);
            }
        });

        return rosterBaseDTOS;
    }


    /**
     * 新增或修改花名册的时候，同步创建或修改用户数据
     */
    public void saveOrUpdateUser (RosterBase rosterBase,String companyId) {
        User user = new User();
        user.setRosterId(rosterBase.getId());  // 花名册id
        user.setOfficeId(rosterBase.getOfficeId());  //  部门
        user.setMobile(rosterBase.getMobile());  //  电话号码
        user.setName(rosterBase.getName());  //  姓名
        user.setLoginName(rosterBase.getName());  //  登录名
        user.setNo(rosterBase.getJobNo());  //  工号
        if (StringUtils.isNotBlank(rosterBase.getEmail())) {
            user.setEmail(rosterBase.getEmail()); // 邮箱
        }
        if (StringUtils.isNotBlank(rosterBase.getCompanyId())) { // 公司
            user.setCompanyId(rosterBase.getCompanyId());
        } else {
            user.setCompanyId(companyId);  // 默认给第一个公司
        }
        //  根据花名册id查询用户信息
        User u = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getRosterId, rosterBase.getId()));
        if (ObjectUtil.isNotEmpty(u)) {
            user.setId(u.getId());  //  用户id
            user.setUpPassword("1");  //  密码修改状态改为 ”已修改“
        } else {
            user.setLoginFlag("1");  //  是否允许登录     默认直接给 “1” 允许登录
            user.setPassword(SecurityUtils.encryptPassword("123456"));  //  密码     默认密码 “123456”
        }
        userService.saveOrUpdate(user);
    }

    public ResponseEntity removeByRosterIds(String[] ids) {
        // 删除花名册数据
        this.removeByIds(Arrays.asList(ids));
        // 删除花名册关联用户数据
        // 员工切换为游客、花名册直接删除   这两种情况都要删除用户信息以及用户关联的角色等信息
        userService.remove(new QueryWrapper<User>().lambda().in(User::getRosterId, ids));
        Arrays.asList(ids).stream().forEach(item -> {
            UserDTO u = new UserDTO();
            u.setId(item);
            // 删除用户关联的管理部门信息
            userMapper.deleteUserManageOffice(u);  //  根据用户id删除用户的管理部门信息
            // 删除用户关联的岗位信息
            userMapper.deleteUserPost(item);
            // 删除用户关联的角色信息
            userMapper.deleteUserRole(item);
        });
        return ResponseEntity.ok ("删除花名册成功");
    }

    public RosterBaseDTO deleteRosterWorker (RosterBaseDTO rosterBaseDTO) {
//        删除原数据关联表的数据
        rosterBaseDTO.setRosterContractDTO(null);  // 删除合同信息
        rosterBaseDTO.setRosterBankCardsDTOList(null);  // 删除银行卡信息
        rosterBaseDTO.setRosterEducateDTOList(null);  // 删除教育经历
        rosterBaseDTO.setRosterWorkDTOList(null);  // 删除工作经历
        rosterBaseDTO.setRosterFamilyDTOList(null);  // 删除家庭成员
        rosterBaseDTO.setRosterCertificateDTOList(null);  // 删除员工证书
        rosterBaseDTO.setRosterLeadershipDTO(null);  // 删除直属领导
        rosterBaseDTO.setCertDTOList(null);  //  关联用户的资质
        rosterBaseDTO.setRoleIdList(null);  // 关联用户的角色
        rosterBaseDTO.setPostIdList(null);  //  关联用户的岗位
        rosterBaseDTO.setManageOfficeIds(null);  //  关联用户的管理部门
        // 与游客无关字段置空
        rosterBaseDTO.setOfficeId("");
        rosterBaseDTO.setJobPositionId("");
        rosterBaseDTO.setPositionId("");
        rosterBaseDTO.setRankId("");
        rosterBaseDTO.setJobNo("");
        rosterBaseDTO.setContractType("");
        rosterBaseDTO.setWorkerType("");
        rosterBaseDTO.setOnboardingDate(null);
        rosterBaseDTO.setSeniority("");
        rosterBaseDTO.setContractCompany("");
        rosterBaseDTO.setBirthDate(null);
        rosterBaseDTO.setWorkPlace("");
        rosterBaseDTO.setContactAddress("");
        rosterBaseDTO.setEmploymentSituation("");
        rosterBaseDTO.setWorkingHour("");
        rosterBaseDTO.setAccountType("");
        rosterBaseDTO.setAccountAddr("");
        rosterBaseDTO.setOrigin("");
        rosterBaseDTO.setLiveAddr("");
        rosterBaseDTO.setHighestEducation("");
        rosterBaseDTO.setPoliticalFace("");
        rosterBaseDTO.setMaritalStatus("");
        rosterBaseDTO.setEmergencyContactName("");
        rosterBaseDTO.setEmergencyContactTel("");
        rosterBaseDTO.setSpouseName("");
        rosterBaseDTO.setChildName("");
        rosterBaseDTO.setHeadshot("");
        // 表删除无关字段
        UpdateWrapper<RosterBase> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .set(RosterBase::getOfficeId,null)
                .set(RosterBase::getJobPositionId,null)
                .set(RosterBase::getPositionId,null)
                .set(RosterBase::getRankId,null)
                .set(RosterBase::getJobNo,null)
                .set(RosterBase::getContractType,null)
                .set(RosterBase::getWorkerType,null)
                .set(RosterBase::getOnboardingDate,null)
                .set(RosterBase::getSeniority,null)
                .set(RosterBase::getContractCompany,null)
                .set(RosterBase::getBirthDate,null)
                .set(RosterBase::getWorkPlace,null)
                .set(RosterBase::getContactAddress,null)
                .set(RosterBase::getEmploymentSituation,null)
                .set(RosterBase::getWorkingHour,null)
                .set(RosterBase::getAccountType,null)
                .set(RosterBase::getAccountAddr,null)
                .set(RosterBase::getOrigin,null)
                .set(RosterBase::getLiveAddr,null)
                .set(RosterBase::getHighestEducation,null)
                .set(RosterBase::getPoliticalFace,null)
                .set(RosterBase::getMaritalStatus,null)
                .set(RosterBase::getEmergencyContactName,null)
                .set(RosterBase::getEmergencyContactTel,null)
                .set(RosterBase::getSpouseName,null)
                .set(RosterBase::getChildName,null)
                .set(RosterBase::getHeadshot,null)
                .eq(RosterBase::getId,rosterBaseDTO.getId());
        this.update(wrapper);
        return rosterBaseDTO;
    }
}
