package com.dcsoft.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.dcsoft.common.core.exception.ServiceException;
import com.dcsoft.common.core.utils.DateUtils;
import com.dcsoft.system.domain.SysBranch;
import com.dcsoft.system.domain.SysPeople;
import com.dcsoft.system.mapper.SysBranchMapper;
import com.dcsoft.system.mapper.SysPeopleMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dcsoft.system.mapper.SysPeopleLeaveMapper;
import com.dcsoft.system.domain.SysPeopleLeave;
import com.dcsoft.system.service.ISysPeopleLeaveService;
import org.springframework.util.CollectionUtils;

/**
 * 离职管理Service业务层处理
 *
 * @author nichun
 * @date 2023-09-09
 */
@Service
public class SysPeopleLeaveServiceImpl implements ISysPeopleLeaveService
{
    @Autowired
    private SysPeopleLeaveMapper sysPeopleLeaveMapper;

    @Autowired
    private SysPeopleMapper sysPeopleMapper;

    @Autowired
    private SysBranchMapper sysBranchMapper;

    /**
     * 查询离职管理
     *
     * @param id 离职管理主键
     * @return 离职管理
     */
    @Override
    public SysPeopleLeave selectSysPeopleLeaveById(Long id)
    {
        return sysPeopleLeaveMapper.selectSysPeopleLeaveById(id);
    }

    /**
     * 查询离职管理列表
     *
     * @param sysPeopleLeave 离职管理
     * @return 离职管理
     */
    @Override
    public List<SysPeopleLeave> selectSysPeopleLeaveList(SysPeopleLeave sysPeopleLeave)
    {
        return sysPeopleLeaveMapper.selectSysPeopleLeaveList(sysPeopleLeave);
    }

    /**
     * 新增离职管理
     *
     * @param sysPeopleLeave 离职管理
     * @return 结果
     */
    @Override
    public int insertSysPeopleLeave(SysPeopleLeave sysPeopleLeave)
    {
        sysPeopleLeave.setCreateTime(DateUtils.getNowDate());
        return sysPeopleLeaveMapper.insertSysPeopleLeave(sysPeopleLeave);
    }

    /**
     * 修改离职管理
     *
     * @param sysPeopleLeave 离职管理
     * @return 结果
     */
    @Override
    public int updateSysPeopleLeave(SysPeopleLeave sysPeopleLeave)
    {
        sysPeopleLeave.setUpdateTime(DateUtils.getNowDate());
        return sysPeopleLeaveMapper.updateSysPeopleLeave(sysPeopleLeave);
    }

    /**
     * 批量删除离职管理
     *
     * @param ids 需要删除的离职管理主键
     * @return 结果
     */
    @Override
    public int deleteSysPeopleLeaveByIds(Long[] ids)
    {
       for(Long peopleId:ids){
           SysPeopleLeave peopleLeave =sysPeopleLeaveMapper.selectSysPeopleLeaveById(peopleId);
           if(peopleLeave.getPeopleId()!=null){
               SysPeople people=new SysPeople();
               people.setId(peopleLeave.getPeopleId());
               people.setDelFlag(0L);
               sysPeopleMapper.updateSysPeople(people);
           }
       }
        return sysPeopleLeaveMapper.deleteSysPeopleLeaveByIds(ids);
    }

    /**
     * 删除离职管理信息
     *
     * @param id 离职管理主键
     * @return 结果
     */
    @Override
    public int deleteSysPeopleLeaveById(Long id)
    {
        SysPeopleLeave peopleLeave =sysPeopleLeaveMapper.selectSysPeopleLeaveById(id);
        if(peopleLeave.getPeopleId()!=null){
            SysPeople people=new SysPeople();
            people.setId(peopleLeave.getPeopleId());
            people.setDelFlag(0L);
            sysPeopleMapper.updateSysPeople(people);
        }
        return sysPeopleLeaveMapper.deleteSysPeopleLeaveById(id);
    }

    /**
     * 离职人员导入
     * @param userList
     * @param updateSupport
     * @param operName
     * @return
     */
    @Override
    public String importPeople(List<SysPeopleLeave> userList, boolean updateSupport, String operName) {
        if (CollectionUtils.isEmpty(userList)) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        // 更具工号查询用户信息
        List<String> collect = userList.stream().map(SysPeopleLeave::getGh).collect(Collectors.toList());
        List<SysPeople> u = sysPeopleMapper.queryPeople(collect);
        Map<String, Long> collect1 = u.stream().collect(Collectors.toMap(SysPeople::getGh, SysPeople::getId));
        int i = 0;
        for (SysPeopleLeave sysPeopleLeave : userList) {
            i++;
            if(StringUtils.isEmpty(sysPeopleLeave.getGh())) {
                throw new ServiceException("第" + i + "行的工号不能为空");
            }
            if(sysPeopleLeave.getLeaveTime() == null) {
                throw new ServiceException("第" + i + "行的离职时间不能为空");
            }
            SysBranch branch=new SysBranch();
            branch.setName(sysPeopleLeave.getBranchName());
            List<SysBranch> branchlist = sysBranchMapper.selectSysBranchList(branch);
            if(CollectionUtils.isEmpty(branchlist)) {
                sysPeopleLeave.setBranchId(branchlist.get(0).getId());
            }
            Long l = collect1.get(sysPeopleLeave.getGh());
            if(l != null) {
                sysPeopleLeave.setPeopleId(l);
            }
        }

        // excel表中工号重复校验
        removeDuplicateOrder(userList);

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        // 获取在人员表中没有工号的数据（需要抛出异常提示工号不存在）
        List<SysPeopleLeave> peopleLeaves = new ArrayList<>(userList);
        peopleLeaves.removeIf(c -> u.stream().anyMatch(n -> n.getGh().equals(c.getGh())));
        for (SysPeopleLeave people : peopleLeaves) {
            failureNum ++;
            failureMsg.append("<br/>").append(failureNum).append("、工号 ").append(people.getGh()).append(" 不存在");
        }

        // 获取在人员表中工号存在的数据（可以正常导入）
        List<SysPeopleLeave> list = new ArrayList<>(userList);
        list.removeIf(c -> u.stream().anyMatch(n -> !c.getGh().equals(n.getGh())));
        if(!CollectionUtils.isEmpty(list) && !CollectionUtils.isEmpty(u)) {
            List<SysPeopleLeave> peopleLeaveList = sysPeopleLeaveMapper.queryPeopleLeaveList(list);
            if(updateSupport) {
                for (SysPeopleLeave sysPeopleLeave : peopleLeaveList) {
                    successMsg.append("<br/>").append(successNum).append("、工号 ").append(sysPeopleLeave.getGh()).append(" 更新成功");
                }
                sysPeopleLeaveMapper.updatePeopleLeaveList(peopleLeaveList);
            }

            list.removeIf(c -> peopleLeaveList.stream().anyMatch(n -> n.getGh().equals(c.getGh())));
            if(!CollectionUtils.isEmpty(list)) {
                for (SysPeopleLeave sysPeopleLeave : list) {
                    successMsg.append("<br/>").append(successNum).append("、工号 ").append(sysPeopleLeave.getGh()).append(" 导入成功");
                }
                sysPeopleLeaveMapper.savePeopleLeaveList(list);
            }
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");

        }

        if(failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            return failureMsg.toString();
        }

        return successMsg.toString();
    }


    /**
     * 去重校验
     */
    private void removeDuplicateOrder(List<SysPeopleLeave> orderList) {
        Map<String, Integer> articleNameMap = new HashMap<>();
        for (SysPeopleLeave importArticleInfoVo : orderList) {
            if (articleNameMap.containsKey(importArticleInfoVo.getGh())) {
                throw new ServiceException("excel中有多条工号为：" + importArticleInfoVo.getGh() + "的重复数据");
            } else {
                articleNameMap.put(importArticleInfoVo.getGh(), 1);
            }
        }
    }
}
