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.QueryWrapper;
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.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@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;

    public IPage<RosterBaseDTO> findList(Page<RosterBaseDTO> page, QueryWrapper<RosterBase> queryWrapper){
        queryWrapper.eq("rb.del_flag","0");
        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);
                }
            });
        }
        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);
                    }
                });
            }
        }
        return rosterBaseDTO;
    }

    public ResponseEntity saveRoster(RosterBaseDTO rosterBaseDTO) throws Exception{

        if(ObjectUtil.isNotEmpty(rosterBaseDTO)){
            if(StringUtils.isNotBlank(rosterBaseDTO.getId())){
                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{
                //获取当前登录人信息
                UserDTO userDTO = UserUtils.getCurrentUserDTO();
                //工号生成
                String serialNum = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), RosterBaseDTO.BIZ_CODE);
                rosterBaseDTO.setJobNo(serialNum);

                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("基础信息-手机号码 已存在，保存失败");
                    }
                }
            }

        }

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

        this.saveOrUpdate(rosterBase);

        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);
            }
            //保存银行卡信息
            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()));
            }
        }
        return ResponseEntity.ok("花名册保存成功");
    }
}
