package com.engine.salary.service.impl;

import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.salary.constant.SalaryDefaultTenantConstant;
import com.engine.salary.entity.salaryarchive.dto.TaxAgentAdjustRecordListDTO;
import com.engine.salary.entity.salaryarchive.param.SalaryArchiveTaxAgentQueryParam;
import com.engine.salary.entity.salaryarchive.param.SalaryArchiveTaxAgentSaveParam;
import com.engine.salary.entity.salaryarchive.param.TaxAgentAdjustRecordQueryParam;
import com.engine.salary.entity.salaryarchive.po.SalaryArchivePO;
import com.engine.salary.entity.salaryarchive.po.SalaryArchiveTaxAgentPO;
import com.engine.salary.entity.taxagent.po.TaxAgentPO;
import com.engine.salary.enums.UserStatusEnum;
import com.engine.salary.enums.salaryarchive.SalaryArchiveTaxAgentAdjustReasonEnum;
import com.engine.salary.exception.SalaryRunTimeException;
import com.engine.salary.mapper.archive.SalaryArchiveMapper;
import com.engine.salary.mapper.archive.SalaryArchiveTaxAgentMapper;
import com.engine.salary.service.SalaryArchiveTaxAgentService;
import com.engine.salary.service.TaxAgentService;
import com.engine.salary.util.SalaryI18nUtil;
import com.engine.salary.util.db.MapperProxyFactory;
import com.engine.salary.util.excel.ExcelUtil;
import com.engine.salary.util.page.PageInfo;
import com.engine.salary.util.page.SalaryPageUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.hrm.User;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 薪资档案-个税扣缴义务人
 * <p>Copyright: Copyright (c) 2022</p>
 * <p>Company: 泛微软件</p>
 *
 * @author qiantao
 * @version 1.0
 **/
public class SalaryArchiveTaxAgentServiceImpl extends Service implements SalaryArchiveTaxAgentService {
    private static final Logger log = LoggerFactory.getLogger(SalaryArchiveTaxAgentServiceImpl.class);

    private SalaryArchiveTaxAgentMapper getSalaryArchiveTaxAgentMapper() {
        return MapperProxyFactory.getProxy(SalaryArchiveTaxAgentMapper.class);
    }

    private TaxAgentService getTaxAgentService(User user) {
        return ServiceUtil.getService(TaxAgentServiceImpl.class, user);
    }
//    private SalaryBatchService salaryBatchService;

    @Override
    public SalaryArchiveTaxAgentPO getById(Long salaryArchiveTaxAgentId) {
        return getSalaryArchiveTaxAgentMapper().getById(salaryArchiveTaxAgentId);
    }

    @Override
    public PageInfo<TaxAgentAdjustRecordListDTO> taxAgentAdjustRecordListPage(TaxAgentAdjustRecordQueryParam queryParam) {
        List<TaxAgentAdjustRecordListDTO> taxAgentAdjustRecordListDTOS = getSalaryArchiveTaxAgentMapper().taxAgentAdjustRecordList(queryParam);
        return SalaryPageUtil.buildPage(queryParam.getCurrent(), queryParam.getPageSize(),
                taxAgentAdjustRecordListDTOS, TaxAgentAdjustRecordListDTO.class);
    }

    @Override
    public List<TaxAgentAdjustRecordListDTO> taxAgentAdjustRecordList(TaxAgentAdjustRecordQueryParam queryParam) {
        return getSalaryArchiveTaxAgentMapper().taxAgentAdjustRecordList(queryParam);
    }

    /**
     * 获取未生效
     *
     * @param salaryArchiveId
     * @return
     */
    private SalaryArchiveTaxAgentPO getIneffectiveTaxAgent(Long salaryArchiveId) {
        List<SalaryArchiveTaxAgentPO> ineffectiveTaxAgentList = getSalaryArchiveTaxAgentMapper().getIneffectiveTaxAgentList(SalaryArchiveTaxAgentQueryParam.builder().salaryArchiveId(salaryArchiveId).effectiveTime(new Date()).build());
        return CollectionUtils.isNotEmpty(ineffectiveTaxAgentList) ? ineffectiveTaxAgentList.get(0) : null;
    }

    /**
     * 获取当前已生效
     *
     * @param salaryArchiveId
     * @return
     */
    @Override
    public SalaryArchiveTaxAgentPO getEffectiveTaxAgent(Long salaryArchiveId) {
        List<SalaryArchiveTaxAgentPO> effectiveTaxAgentList = getSalaryArchiveTaxAgentMapper().getEffectiveTaxAgentList(SalaryArchiveTaxAgentQueryParam.builder().salaryArchiveId(salaryArchiveId).effectiveTime(new Date()).build());
        return CollectionUtils.isNotEmpty(effectiveTaxAgentList) ? effectiveTaxAgentList.get(0) : null;
    }

    @Override
    public String saveTaxAgent(SalaryArchiveTaxAgentSaveParam saveParam) {

        // 校验参数
        SalaryArchiveTaxAgentSaveParam.checkParam(saveParam);

        // 薪资档案
        SalaryArchiveMapper salaryArchiveMapper = MapperProxyFactory.getProxy(SalaryArchiveMapper.class);
        SalaryArchivePO salaryArchive = salaryArchiveMapper.getById(saveParam.getSalaryArchiveId());
        // 获取当前已生效
        SalaryArchiveTaxAgentPO effectiveTaxAgent = getEffectiveTaxAgent(saveParam.getSalaryArchiveId());
        // 获取当前已生效之前的
        List<SalaryArchiveTaxAgentPO> salaryArchiveTaxAgents = Lists.newArrayList();
        if (effectiveTaxAgent != null) {
            salaryArchiveTaxAgents = getSalaryArchiveTaxAgentMapper().getTaxAgentLtTimeBySalaryArchiveId(SalaryArchiveTaxAgentQueryParam.builder().salaryArchiveId(saveParam.getSalaryArchiveId()).effectiveTime(effectiveTaxAgent.getEffectiveTime()).build());
        }
        // 获取未生效数据
        SalaryArchiveTaxAgentPO ineffectiveTaxAgent = getIneffectiveTaxAgent(saveParam.getSalaryArchiveId());

        // 待保存生效时间
        Date saveEffectiveTime = saveParam.getEffectiveTime();
        // 当天
        Date today = new Date();

        // 1.检验是否可以调整
        if (effectiveTaxAgent != null) {
            // 当前已经生效的时间
            Date effectiveTime = effectiveTaxAgent.getEffectiveTime();
            // 1.1 如果早于<当前已生效
            if (saveEffectiveTime.before(effectiveTime)) {
                throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(100429, "生效日期不可早于当前已生效的调整日期"));
                // 1.2 如果等于当前已生效
            } else if (saveEffectiveTime.equals(effectiveTime)) {
                if (CollectionUtils.isNotEmpty(salaryArchiveTaxAgents) && salaryArchiveTaxAgents.get(0).getTaxAgentId().equals(saveParam.getTaxAgentId())) {
                    throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(100432, "调整前后不可相同"));
                }
                if (ineffectiveTaxAgent != null && ineffectiveTaxAgent.getTaxAgentId().equals(saveParam.getTaxAgentId())) {
                    throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(100434, "与未生效的调整后不可相同"));
                }
                // 1.3 如果>已经生效且<=今天
            } else if (saveEffectiveTime.after(effectiveTime) && !saveEffectiveTime.after(today)) {
                if (effectiveTaxAgent.getTaxAgentId().equals(saveParam.getTaxAgentId())) {
                    throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(100432, "调整前后不可相同"));
                }
                if (ineffectiveTaxAgent != null && ineffectiveTaxAgent.getTaxAgentId().equals(saveParam.getTaxAgentId())) {
                    throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(100434, "与未生效的调整后不可相同"));
                }
                // 1.4 如果>今天
            } else if (saveEffectiveTime.after(today) && effectiveTaxAgent.getTaxAgentId().equals(saveParam.getTaxAgentId())) {
                throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(100432, "调整前后不可相同"));
            }
        } else if (ineffectiveTaxAgent != null && ineffectiveTaxAgent.getTaxAgentId().equals(saveParam.getTaxAgentId())) {
            throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(100434, "与未生效的调整后不可相同"));
        }
        // 2.数据处理
        // 2.数据处理,有的就先删后增
        if (effectiveTaxAgent != null && saveEffectiveTime.equals(effectiveTaxAgent.getEffectiveTime())) {
            getSalaryArchiveTaxAgentMapper().delete(SalaryArchiveTaxAgentPO.builder().id(effectiveTaxAgent.getId()).build());
        }
        if (ineffectiveTaxAgent != null && saveEffectiveTime.after(today)) {
            getSalaryArchiveTaxAgentMapper().delete(SalaryArchiveTaxAgentPO.builder().id(ineffectiveTaxAgent.getId()).build());
        }
        insertTaxAgent(salaryArchive, saveParam);
        // 3.todo 日志处理

        return StringUtils.EMPTY;
    }

    /**
     * 插入
     *
     * @param salaryArchive
     * @param saveParam
     */
    private void insertTaxAgent(SalaryArchivePO salaryArchive, SalaryArchiveTaxAgentSaveParam saveParam) {
        long employeeId = user.getUID();
        Date now = new Date();
        SalaryArchiveTaxAgentPO salaryArchiveTaxAgent = SalaryArchiveTaxAgentPO.builder()
                .salaryArchiveId(saveParam.getSalaryArchiveId()).employeeId(salaryArchive.getEmployeeId()).effectiveTime(saveParam.getEffectiveTime()).adjustReason(saveParam.getAdjustReason())
                // 调整后
                .taxAgentId(saveParam.getTaxAgentId()).operator(employeeId).operateTime(now).createTime(now).updateTime(now).creator(employeeId).tenantKey(SalaryDefaultTenantConstant.DEFAULT_TENANT_KEY).build();
        getSalaryArchiveTaxAgentMapper().insertIgnoreNull(salaryArchiveTaxAgent);
    }

    @Override
    public String deleteTaxAgent(Long salaryArchiveTaxAgentId) {
        SalaryArchiveTaxAgentPO salaryArchiveTaxAgent = getSalaryArchiveTaxAgentMapper().getById(salaryArchiveTaxAgentId);
        if (salaryArchiveTaxAgent == null) {
            return StringUtils.EMPTY;
        }
        if (salaryArchiveTaxAgent.getEffectiveTime().after(new Date())) {
            salaryArchiveTaxAgent.setDeleteType(1);
            // 删除未生效数据
            getSalaryArchiveTaxAgentMapper().delete(salaryArchiveTaxAgent);
        }
        return StringUtils.EMPTY;
    }

    @Override
    public XSSFWorkbook exportAdjustRecordList(TaxAgentAdjustRecordQueryParam queryParam) {
        // 1.工作簿名称
        String sheetName = SalaryI18nUtil.getI18nLabel(99978, "个税扣缴义务人调整记录");
        // 2.表头
        List<Object> header = new ArrayList<>();
        header.add(SalaryI18nUtil.getI18nLabel(85429, "姓名"));
        header.add(SalaryI18nUtil.getI18nLabel(86187, "员工状态"));
        header.add(SalaryI18nUtil.getI18nLabel(86185, "部门"));
        header.add(SalaryI18nUtil.getI18nLabel(85433, "调整前"));
        header.add(SalaryI18nUtil.getI18nLabel(85434, "调整后"));
        header.add(SalaryI18nUtil.getI18nLabel(85431, "调整原因"));
        header.add(SalaryI18nUtil.getI18nLabel(85904, "生效日期"));
        header.add(SalaryI18nUtil.getI18nLabel(85435, "操作人"));
        header.add(SalaryI18nUtil.getI18nLabel(85436, "操作时间"));
        header.add(SalaryI18nUtil.getI18nLabel(84961, "备注"));
        // 3.表数据
        // 获取记录
        List<TaxAgentAdjustRecordListDTO> list = getSalaryArchiveTaxAgentMapper().taxAgentAdjustRecordList(queryParam);
        List<TaxAgentAdjustRecordListDTO> listAll = getSalaryArchiveTaxAgentMapper().taxAgentAdjustRecordList(TaxAgentAdjustRecordQueryParam.builder().build());
        // 个税扣缴义务人
        Collection<TaxAgentPO> taxAgentList = getTaxAgentService(user).listAll();
        // 人员信息赋值
        list.forEach(m -> {
            if (!org.springframework.util.CollectionUtils.isEmpty(listAll)) {
                listAll.removeIf(a -> a.getId().equals(m.getId()));
            }
            Optional<TaxAgentAdjustRecordListDTO> optional = listAll.stream().filter(f -> f.getSalaryArchiveId().equals(m.getSalaryArchiveId())).findFirst();
            m.setAdjustBefore(optional.isPresent() ? optional.get().getAdjustAfter() : "");
            Optional<TaxAgentPO> optionalBefore = taxAgentList.stream().filter(t -> t.getId().toString().equals(m.getAdjustBefore())).findFirst();
            m.setAdjustBefore(optionalBefore.isPresent() ? optionalBefore.get().getName() : "");
            Optional<TaxAgentPO> optionalAfter = taxAgentList.stream().filter(t -> t.getId().toString().equals(m.getAdjustAfter())).findFirst();
            m.setAdjustAfter(optionalAfter.isPresent() ? optionalAfter.get().getName() : "");

            m.setEmployeeStatus(UserStatusEnum.getDefaultLabelByValue(Integer.parseInt(m.getEmployeeStatus())));
            m.setAdjustReason(SalaryArchiveTaxAgentAdjustReasonEnum.getDefaultLabelByValue(m.getAdjustReason()));
        });
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<List<Object>> rows = new ArrayList<>();
        rows.add(header);
        for (TaxAgentAdjustRecordListDTO dto : list) {
            List<Object> row = new ArrayList<>();
            row.add(dto.getUsername());
            row.add(dto.getEmployeeStatus());
            row.add(dto.getDepartmentName());
            row.add(dto.getAdjustBefore());
            row.add(dto.getAdjustAfter());
            row.add(dto.getAdjustReason());
            row.add(dto.getEffectiveTime() + "");
            row.add(dto.getOperator());
            row.add(format.format(dto.getOperateTime()));
            row.add(dto.getDescription());
            rows.add(row);
        }

        return ExcelUtil.genWorkbookV2(rows, sheetName);

    }

    @Override
    public SalaryArchiveTaxAgentPO getAdjustBeforeTaxAgent(SalaryArchiveTaxAgentPO salaryArchiveTaxAgent) {
        List<SalaryArchiveTaxAgentPO> salaryArchiveTaxAgents = getSalaryArchiveTaxAgentMapper().getAdjustBeforeTaxAgent(SalaryArchiveTaxAgentPO.builder().salaryArchiveId(salaryArchiveTaxAgent.getSalaryArchiveId()).effectiveTime(salaryArchiveTaxAgent.getEffectiveTime()).build());
        return CollectionUtils.isNotEmpty(salaryArchiveTaxAgents) ? salaryArchiveTaxAgents.get(0) : null;
    }

}
