package cn.ezhizao.project.business.salary.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import cn.ezhizao.common.exception.ServiceException;
import cn.ezhizao.common.utils.StringUtils;
import cn.ezhizao.project.business.company.domain.BizCompany;
import cn.ezhizao.project.business.salary.domain.BizFinancialSalaryDetail;
import cn.ezhizao.project.business.salary.domain.BizFinancialSalaryDetailEmployee;
import cn.ezhizao.project.business.salary.mapper.BizFinancialSalaryDetailEmployeeMapper;
import cn.ezhizao.project.business.salary.mapper.BizFinancialSalaryDetailMapper;
import cn.ezhizao.project.business.salary.service.IBizFinancialSalaryDetailService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import cn.ezhizao.project.business.salary.mapper.BizFinancialSalaryMapper;
import cn.ezhizao.project.business.salary.domain.BizFinancialSalary;
import cn.ezhizao.project.business.salary.service.IBizFinancialSalaryService;
import org.springframework.util.CollectionUtils;

/**
 * 工资Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-16
 */
@Service
public class BizFinancialSalaryServiceImpl extends ServiceImpl<BizFinancialSalaryMapper, BizFinancialSalary> implements IBizFinancialSalaryService {
    @Resource
    private BizFinancialSalaryMapper bizFinancialSalaryMapper;

    @Resource
    private IBizFinancialSalaryDetailService bizFinancialSalaryDetailService;

    @Resource
    private BizFinancialSalaryDetailEmployeeMapper bizFinancialSalaryDetailEmployeeMapper;

    @Resource
    private BizFinancialSalaryDetailMapper bizFinancialSalaryDetailMapper;

    /**
     * 查询工资列表
     *
     * @param bizFinancialSalary 工资
     * @return 工资
     */
    @Override
    public List<BizFinancialSalary> getList(BizFinancialSalary bizFinancialSalary) {
        return bizFinancialSalaryMapper.getList(bizFinancialSalary);
    }

    /**
     * 物理删除
     *
     * @param bizFinancialSalary
     * @return 删除结果
     */
    @Override
    public int physicalDelete(BizFinancialSalary bizFinancialSalary) {
        return bizFinancialSalaryMapper.physicalDelete(bizFinancialSalary);
    }

    ;


    @Override
    public String importSalary(List<BizFinancialSalaryDetailEmployee> detailList, String year, String month, Long tenantId, Integer isZero) {
        if (StringUtils.isNull(detailList) || detailList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        // 根据 客户名称 字段将元素分组
        Map<String, List<BizFinancialSalaryDetailEmployee>> groupedByName = detailList.stream()
                .collect(Collectors.groupingBy(BizFinancialSalaryDetailEmployee::getCompanyName));
        int number = 0;
        // 循环遍历每个分组
        for (Map.Entry<String, List<BizFinancialSalaryDetailEmployee>> entry : groupedByName.entrySet()) {
            String name = entry.getKey();

            List<BizFinancialSalaryDetailEmployee> employees = entry.getValue();
            BizFinancialSalaryDetailEmployee salaryDetai = employees.get(number++);
            BizFinancialSalary salary = new BizFinancialSalary();
            salary.setCompanyName(salaryDetai.getCompanyName());
            salary.setTenantId(tenantId);
            salary.setIsZero(isZero);
            List<BizFinancialSalary> salaryList = getList(salary);
            //是否存在该客户
            if (salaryList.size() == 0) {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、客户 ").append(salaryDetai.getCompanyName()).append(" 不存在");
                continue;
            }
            if (salaryList.size() > 1) {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、客户 ").append(salaryDetai.getCompanyName()).append("请输入详细客户名称");
                continue;
            }
            salary = salaryList.get(0);
            BizFinancialSalaryDetail salaryDetail = new BizFinancialSalaryDetail();

            salaryDetail.setFinancialSalaryId(salary.getId());
            salaryDetail.setMonth(month);
            salaryDetail.setYear(year);
            boolean status = false;
            List<BizFinancialSalaryDetail> salaryDetailList = bizFinancialSalaryDetailService.getList(salaryDetail);
            if (!CollectionUtils.isEmpty(salaryDetailList)) {
                BizFinancialSalaryDetail bizFinancialSalaryDetail = salaryDetailList.get(0);
                if (bizFinancialSalaryDetail != null) {
                        status = true;
                    Long id = bizFinancialSalaryDetail.getId();
                    List<BizFinancialSalaryDetailEmployee> bizFinancialSalaryDetailEmployees = bizFinancialSalaryDetailEmployeeMapper
                            .selectList(new LambdaQueryWrapper<BizFinancialSalaryDetailEmployee>().eq(BizFinancialSalaryDetailEmployee::getFinancialSalaryDetailId, id));
                    if (!CollectionUtils.isEmpty(bizFinancialSalaryDetailEmployees)) {
                        failureNum++;
                        failureMsg.append("<br/>").append(failureNum).append("、客户 ").append(salaryDetai.getCompanyName()).append(year + "年" + month + "月").append("工资已有数据");
                        continue;
                    } else {
                        salaryDetail.setId(id);
                    }
                }
            }
            //设置状态为待确认
            salaryDetail.setStatus(1);
            salaryDetail.setCompanyId(salary.getCompanyId());
            //新增工资明细
            if (!status) {
                bizFinancialSalaryDetailMapper.insert(salaryDetail);
            }
            for (BizFinancialSalaryDetailEmployee l : employees) {
                //计算应发工资
                l.setActuallySalary(l.getPlanSalary() == null ? BigDecimal.valueOf(0) : l.getPlanSalary().add(l.getBonusAmount() == null ? BigDecimal.valueOf(0) : l.getBonusAmount()));
                //计算实发工资
                l.setActuallySalary(l.getActuallySalary() == null ? BigDecimal.valueOf(0) : l.getActuallySalary().subtract(l.getEndowmentInsurance() == null ? BigDecimal.valueOf(0) : l.getEndowmentInsurance()).subtract(l.getMedicalInsurance() == null ? BigDecimal.valueOf(0) : l.getMedicalInsurance())
                        .subtract(l.getUnemploymentBenefit() == null ? BigDecimal.valueOf(0) : l.getUnemploymentBenefit()).subtract(l.getSeriousIllnessInsurance() == null ? BigDecimal.valueOf(0) : l.getSeriousIllnessInsurance())
                        .subtract(l.getHousingFund() == null ? BigDecimal.valueOf(0) : l.getHousingFund()).subtract(l.getOtherCut() == null ? BigDecimal.valueOf(0) : l.getOtherCut()));
                //设置外键
                l.setFinancialSalaryId(salary.getId());
                l.setFinancialSalaryDetailId(salaryDetail.getId());
                //新增人员明细
                bizFinancialSalaryDetailEmployeeMapper.insert(l);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、工资 ").append(l.getCompanyName()).append(" 导入成功");
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }

    @Override
    public int physicalDeleteIds(List<Long> ids) {
        return bizFinancialSalaryMapper.physicalDeleteIds(ids);
    }

    @Override
    public List<BizFinancialSalary> getList2(BizFinancialSalary bizFinancialSalary) {
        return bizFinancialSalaryMapper.getList2(bizFinancialSalary);
    }
}
