package com.jeeplus.test.changes.dimission.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.google.common.collect.Lists;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.test.changes.dimission.domain.ChangesDimission;
import com.jeeplus.test.changes.dimission.domain.ChangesDimissionAudit;
import com.jeeplus.test.changes.dimission.domain.ChangesDimissionFiles;
import com.jeeplus.test.changes.dimission.domain.ChangesDimissionRea;
import com.jeeplus.test.changes.dimission.mapper.ChangesDimissionMapper;
import com.jeeplus.test.changes.dimission.service.dto.ChangesDimissionDTO;
import com.jeeplus.test.changes.dimission.service.dto.ChangesDimissionFilesDTO;
import com.jeeplus.test.changes.dimission.service.dto.ChangesDimissionReaDTO;
import com.jeeplus.test.changes.dimission.service.mapstruct.ChangesDimissionFilesWrapper;
import com.jeeplus.test.changes.dimission.service.mapstruct.ChangesDimissionWrapper;
import com.jeeplus.test.roster.domain.RosterBase;
import com.jeeplus.test.roster.service.dto.RosterBaseDTO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class ChangesDimissionService extends ServiceImpl<ChangesDimissionMapper, ChangesDimission> {

    @Resource
    private ChangesDimissionMapper changesDimissionMapper;
    @Resource
    private ChangesDimissionReaService changesDimissionReaService;
    @Resource
    private ChangesDimissionFilesService changesDimissionFilesService;
    @Resource
    private ChangesDimissionAuditService changesDimissionAuditService;

    public IPage<ChangesDimissionDTO> findList(Page<ChangesDimissionDTO> page, QueryWrapper<ChangesDimission> queryWrapper){
        queryWrapper.eq("cd.del_flag","0");
        return changesDimissionMapper.findList(page,queryWrapper);
    }

    public ChangesDimissionDTO queryById(String id) {

        ChangesDimissionDTO changesDimissionDTO = changesDimissionMapper.queryById(id);

        if(ObjectUtil.isNotEmpty(changesDimissionDTO)){
            if(CollectionUtil.isNotEmpty(changesDimissionDTO.getChangesDimissionReaDTOList())){
                List<String> collect = changesDimissionDTO.getChangesDimissionReaDTOList().stream().map(ChangesDimissionReaDTO::getDimissionReason).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(collect)){
                    changesDimissionDTO.setReaTypeList(collect);
                }
            }
        }

        return changesDimissionDTO;
    }

    public ResponseEntity saveDimission(ChangesDimissionDTO changesDimissionDTO) {
        if(ObjectUtil.isNotEmpty(changesDimissionDTO)){
            if(StringUtils.isNotBlank(changesDimissionDTO.getId())){
                List<ChangesDimission> list = this.list(new QueryWrapper<ChangesDimission>().lambda()
                        .eq(ChangesDimission::getRosterId, changesDimissionDTO.getRosterId())
                        .ne(ChangesDimission::getId, changesDimissionDTO.getId()));
                if(CollectionUtil.isNotEmpty(list)){
                    return ResponseEntity.badRequest().body("此员工已提交离职，请勿重复提交");
                }
            }else{
                List<ChangesDimission> list = this.list(new QueryWrapper<ChangesDimission>().lambda()
                        .eq(ChangesDimission::getRosterId, changesDimissionDTO.getRosterId()));
                if(CollectionUtil.isNotEmpty(list)){
                    return ResponseEntity.badRequest().body("此员工已提交离职，请勿重复提交");
                }
            }
            if(StringUtils.isBlank(changesDimissionDTO.getVettingStatus())){
                changesDimissionDTO.setVettingStatus("1");
            }
            if(StringUtils.isBlank(changesDimissionDTO.getHandoverStatus())){
                changesDimissionDTO.setHandoverStatus("1");
            }
        }
        ChangesDimission changesDimission = ChangesDimissionWrapper.INSTANCE.toEntity(changesDimissionDTO);
        if(ObjectUtil.isNotEmpty(changesDimission)){
            if(StringUtils.isNotBlank(changesDimission.getId())){
                this.update(changesDimission,new LambdaUpdateWrapper<ChangesDimission>()
                        .eq(ChangesDimission::getId,changesDimission.getId())
                        .set(ObjectUtils.isEmpty(changesDimission.getDimissionDate()),ChangesDimission::getDimissionDate,null)
                        .set(ObjectUtils.isEmpty(changesDimission.getLastWorkDate()),ChangesDimission::getLastWorkDate,null)
                        .set(ObjectUtils.isEmpty(changesDimission.getPayrollSettlementDate()),ChangesDimission::getPayrollSettlementDate,null)
                );
            }else{
                this.save(changesDimission);
            }
        }


        if(ObjectUtil.isNotEmpty(changesDimissionDTO)){
            ChangesDimissionAudit audit = new ChangesDimissionAudit();
            audit.setVettingStatus(changesDimissionDTO.getVettingStatus());
            List<ChangesDimissionAudit> list = changesDimissionAuditService.list(new QueryWrapper<ChangesDimissionAudit>().lambda().eq(ChangesDimissionAudit::getId, changesDimission.getId()));
            if(CollectionUtil.isNotEmpty(list)){
                changesDimissionAuditService.update(audit,new QueryWrapper<ChangesDimissionAudit>().lambda().eq(ChangesDimissionAudit::getId,changesDimission.getId()));
            }else{
                audit.setId(changesDimission.getId());
                changesDimissionAuditService.save(audit);
            }
            if(CollectionUtil.isNotEmpty(changesDimissionDTO.getReaTypeList())){
                changesDimissionReaService.remove(new QueryWrapper<ChangesDimissionRea>().lambda()
                        .eq(ChangesDimissionRea::getCdId,changesDimission.getId())
                );
                List<ChangesDimissionRea> reaList = new ArrayList<>();
                changesDimissionDTO.getReaTypeList().stream().forEach(item->{
                    ChangesDimissionRea rea = new ChangesDimissionRea();
                    rea.setCdId(changesDimission.getId());
                    rea.setDimissionReason(item);
                    reaList.add(rea);
                });
                changesDimissionReaService.saveBatch(reaList);
            }

            if(CollectionUtil.isNotEmpty(changesDimissionDTO.getChangesDimissionFilesDTOList())){
                List<String> fileIdList = changesDimissionDTO.getChangesDimissionFilesDTOList().stream()
                        .filter(item -> StringUtils.isNotBlank(item.getId()))
                        .map(ChangesDimissionFilesDTO::getId).collect(Collectors.toList());
                changesDimissionFilesService.remove(new QueryWrapper<ChangesDimissionFiles>().lambda()
                        .eq(ChangesDimissionFiles::getCdId,changesDimission.getId())
                        .notIn(CollectionUtil.isNotEmpty(fileIdList),ChangesDimissionFiles::getId,fileIdList)
                );
                List<ChangesDimissionFiles> fileList = new ArrayList<>();
                changesDimissionDTO.getChangesDimissionFilesDTOList().stream().forEach(item->{
                    ChangesDimissionFiles file = ChangesDimissionFilesWrapper.INSTANCE.toEntity(item);
                    file.setCdId(changesDimission.getId());
                    fileList.add(file);
                });
                changesDimissionFilesService.saveOrUpdateBatch(fileList);
            }else{
                changesDimissionFilesService.remove(new QueryWrapper<ChangesDimissionFiles>().lambda()
                        .eq(ChangesDimissionFiles::getCdId,changesDimission.getId())
                );
            }
        }
        return ResponseEntity.ok("保存成功");
    }

    public ResponseEntity deleteByIds(String ids) {
        String idArray[] =ids.split(",");
        this.removeByIds (Lists.newArrayList (idArray));
        changesDimissionFilesService.remove(new QueryWrapper<ChangesDimissionFiles>().lambda().in(ChangesDimissionFiles::getCdId,Lists.newArrayList (idArray)));
        changesDimissionReaService.remove(new QueryWrapper<ChangesDimissionRea>().lambda().in(ChangesDimissionRea::getCdId,Lists.newArrayList (idArray)));
        return ResponseEntity.ok ("放弃离职成功");
    }

    public ResponseEntity updateStatus(String id){
        this.update(new UpdateWrapper<ChangesDimission>().lambda().set(ChangesDimission::getStatus,'1').eq(ChangesDimission::getId,id));
        return ResponseEntity.ok ("取消确认成功");
    }

    /**
     * 根据离职id来修改离职审批状态 vetting_status的值
     * @param changesDimissionDTO
     */
    public void updateVettingStatusById(ChangesDimissionDTO changesDimissionDTO){
        ChangesDimissionAudit changesDimissionAudit = new ChangesDimissionAudit();
        changesDimissionAudit.setVettingStatus(changesDimissionDTO.getVettingStatus());
        this.changesDimissionAuditService.update(changesDimissionAudit,new QueryWrapper<ChangesDimissionAudit>().lambda().eq(ChangesDimissionAudit::getId,changesDimissionDTO.getId()));
        ChangesDimission changesDimission = new ChangesDimission();
        changesDimission.setVettingStatus(changesDimissionDTO.getVettingStatus());
        this.update(changesDimission,new QueryWrapper<ChangesDimission>().lambda().eq(ChangesDimission::getId,changesDimissionDTO.getId()));
    }

}
