package com.engine.salary.biz;

import com.engine.salary.entity.taxrate.SysTaxRateBase;
import com.engine.salary.entity.taxrate.TaxRateBase;
import com.engine.salary.entity.taxrate.TaxRateDetail;
import com.engine.salary.entity.taxrate.bo.TaxRateBO;
import com.engine.salary.entity.taxrate.param.TaxRateSaveParam;
import com.engine.salary.entity.taxrate.vo.TaxRateFormVo;
import com.engine.salary.enums.SalarySystemTypeEnum;
import com.engine.salary.exception.SalaryRunTimeException;
import com.engine.salary.mapper.SysTaxRateBaseMapper;
import com.engine.salary.mapper.TaxRateBaseMapper;
import com.engine.salary.mapper.TaxRateDetailMapper;
import com.engine.salary.util.SalaryEntityUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.BeanUtils;
import weaver.conn.mybatis.MyBatisFactory;
import weaver.general.BaseBean;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 税率操作类
 * <p>Copyright: Copyright (c) 2022</p>
 * <p>Company: 泛微软件</p>
 *
 * @author qiantao
 * @version 1.0
 **/
public class TaxRateBiz extends BaseBean {


    public TaxRateBase getById(Long id) {

        SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
        try {
            TaxRateBaseMapper taxRateBaseMapper = sqlSession.getMapper(TaxRateBaseMapper.class);
            SysTaxRateBaseMapper sysTaxRateBaseMapper = sqlSession.getMapper(SysTaxRateBaseMapper.class);
            TaxRateBase taxRateBase = taxRateBaseMapper.getById(id);

            // 如果自定义税率表中没有再查询系统默认的税率表
            if (Objects.isNull(taxRateBase)) {
                SysTaxRateBase sysTaxRateBase = sysTaxRateBaseMapper.getById(id);
                if (sysTaxRateBase == null) {
                    return null;
                }
                taxRateBase = new TaxRateBase();
                BeanUtils.copyProperties(sysTaxRateBase, taxRateBase);
            }
            return taxRateBase;
        } finally {
            sqlSession.close();
        }
    }

    public List<TaxRateBase> listByIds(Collection<Long> ids) {

        SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
        try {
            TaxRateBaseMapper taxRateBaseMapper = sqlSession.getMapper(TaxRateBaseMapper.class);
            SysTaxRateBaseMapper sysTaxRateBaseMapper = sqlSession.getMapper(SysTaxRateBaseMapper.class);

            if (CollectionUtils.isEmpty(ids)) {
                return Collections.emptyList();
            }
            List<TaxRateBase> resultList = Lists.newArrayListWithExpectedSize(ids.size());
            // 查询系统默认的税率表
            List<SysTaxRateBase> sysTaxRateBases = sysTaxRateBaseMapper.selectByIds(ids);
            List<TaxRateBase> TaxRateBaseS4Sys = sysTaxRateBases.stream()
                    .map(sysTaxRateBase -> {
                        TaxRateBase TaxRateBase = new TaxRateBase();
                        BeanUtils.copyProperties(sysTaxRateBase, TaxRateBase);
                        return TaxRateBase;
                    })
                    .collect(Collectors.toList());
            resultList.addAll(TaxRateBaseS4Sys);

            // 查询自定义税率表
            List<TaxRateBase> taxRateBases = taxRateBaseMapper.selectByIds(ids);
            resultList.addAll(taxRateBases);

            return resultList;

        } finally {
            sqlSession.close();
        }
    }


    public List<TaxRateBase> listByName(String name) {
        SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
        try {
            TaxRateBaseMapper taxRateBaseMapper = sqlSession.getMapper(TaxRateBaseMapper.class);
            SysTaxRateBaseMapper sysTaxRateBaseMapper = sqlSession.getMapper(SysTaxRateBaseMapper.class);

            List<TaxRateBase> resultList = Lists.newArrayList();

            // 查询系统默认的税率表
            List<SysTaxRateBase> sysTaxRateBases = sysTaxRateBaseMapper.listBySome(SysTaxRateBase.builder().name(name).build());
            List<TaxRateBase> TaxRateBaseS4Sys = sysTaxRateBases.stream()
                    .map(sysTaxRateBase -> {
                        TaxRateBase TaxRateBase = new TaxRateBase();
                        BeanUtils.copyProperties(sysTaxRateBase, TaxRateBase);
                        return TaxRateBase;
                    })
                    .collect(Collectors.toList());
            resultList.addAll(TaxRateBaseS4Sys);

            // 查询自定义税率表
            List<TaxRateBase> TaxRateBaseS = taxRateBaseMapper.listBySome(TaxRateBase.builder().name(name).build());
            resultList.addAll(TaxRateBaseS);

            return resultList;

        } finally {
            sqlSession.close();
        }
    }


    public List<TaxRateBase> list() {
        List<TaxRateBase> resultList = Lists.newArrayList();
        SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
        try {
            SysTaxRateBaseMapper sysTaxRateBaseMapper = sqlSession.getMapper(SysTaxRateBaseMapper.class);
            TaxRateBaseMapper taxRateBaseMapper = sqlSession.getMapper(TaxRateBaseMapper.class);

            // 查询系统默认的税率表
            List<SysTaxRateBase> sysTaxRateBases = sysTaxRateBaseMapper.listAll();
            List<TaxRateBase> TaxRateBaseS4Sys = sysTaxRateBases.stream()
                    .map(sysTaxRateBase -> {
                        TaxRateBase TaxRateBase = new TaxRateBase();
                        BeanUtils.copyProperties(sysTaxRateBase, TaxRateBase);
                        return TaxRateBase;
                    })
                    .collect(Collectors.toList());
            resultList.addAll(TaxRateBaseS4Sys);

            // 查询自定义税率表
            List<TaxRateBase> TaxRateBaseS = taxRateBaseMapper.listAll();
            resultList.addAll(TaxRateBaseS);

        } finally {
            sqlSession.close();
        }

        return resultList;
    }

    public void deleteByIds(Collection<Long> ids) {
        // 查询待删除的个税税率表主表
        List<TaxRateBase> TaxRateBaseS = listByIds(ids);
        if (CollectionUtils.isEmpty(TaxRateBaseS)) {
            throw new SalaryRunTimeException("个税税率表不存在");
        }
        // 系统默认的个税税率表不允许删除
        boolean containSystem = TaxRateBaseS.stream()
                .anyMatch(taxRateBatchPO -> SalarySystemTypeEnum.parseByValue(taxRateBatchPO.getSystemType()) == SalarySystemTypeEnum.SYSTEM);
        if (containSystem) {
            throw new SalaryRunTimeException("系统默认的税率表不允许删除");
        }
        ids = SalaryEntityUtil.properties(TaxRateBaseS, TaxRateBase::getId);
        // todo 记录日志
//        TaxRateBaseS.forEach(taxRateBatchPO -> {
//            LoggerContext<TaxRateBase> loggerContext = new LoggerContext<>();
//            loggerContext.setTargetId(String.valueOf(taxRateBatchPO.getId()));
//            loggerContext.setTargetName(taxRateBatchPO.getName());
//            loggerContext.setOperateType(OperateTypeEnum.DELETE.getValue());
//            loggerContext.setOperateTypeName(SalaryI18nUtil.getI18nLabel(98120, "删除个税税率表"));
//            loggerContext.setOperatedesc(SalaryI18nUtil.getI18nLabel(98120, "删除个税税率表"));
//            loggerContext.setNewValues(taxRateBatchPO);
//            taxRateLoggerTemplate.write(loggerContext);
//        });


        SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
        try {
            TaxRateBaseMapper taxRateBaseMapper = sqlSession.getMapper(TaxRateBaseMapper.class);
            TaxRateDetailMapper taxRateDetailMapper = sqlSession.getMapper(TaxRateDetailMapper.class);
            // 删除主表
            taxRateBaseMapper.deleteByIds(ids);
            // 删除明细表
            taxRateDetailMapper.deleteByBatchIds(ids);

            sqlSession.commit();
        } finally {
            sqlSession.close();
        }

    }

    public void save(TaxRateSaveParam saveParam, Long employeeId) {

        SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
        try {
            TaxRateBaseMapper taxRateBaseMapper = sqlSession.getMapper(TaxRateBaseMapper.class);

            // 个税税率表主表名称不允许重复
            List<TaxRateBase> TaxRateBaseS = listByName(saveParam.getTaxRateBatch().getName());
            if (CollectionUtils.isNotEmpty(TaxRateBaseS)) {
                throw new SalaryRunTimeException("名称不允许重复");
            }
            // 保存个税税率表主表
            TaxRateBase TaxRateBase = TaxRateBO.convert2BatchPO(saveParam.getTaxRateBatch(), employeeId);
            taxRateBaseMapper.insertIgnoreNull(TaxRateBase);
            // todo 记录日志
//            LoggerContext loggerContext = new LoggerContext<>();
//            loggerContext.setTargetId(String.valueOf(TaxRateBase.getId()));
//            loggerContext.setTargetName(TaxRateBase.getName());
//            loggerContext.setOperateType(OperateTypeEnum.ADD.getValue());
//            loggerContext.setOperateTypeName(SalaryI18nUtil.getI18nLabel(98107, "新增个税税率表（基础信息）"));
//            loggerContext.setOperatedesc(SalaryI18nUtil.getI18nLabel(86124, "基础信息"));
//            loggerContext.setNewValues(TaxRateBase);
//            taxRateLoggerTemplate.write(loggerContext);
            // 保存个税税率表明细表
            List<TaxRateDetail> taxRateDetailPOS = TaxRateBO.convert2RecordPO(TaxRateBase.getId(), saveParam.getTaxRateRecords(), employeeId);
            new TaxRateDetailBiz().saveBatch(taxRateDetailPOS);
            // todo 记录日志
//            LoggerContext detailLoggerContext = new LoggerContext<>();
//            detailLoggerContext.setTargetId(String.valueOf(TaxRateBase.getId()));
//            detailLoggerContext.setTargetName(TaxRateBase.getName());
//            detailLoggerContext.setOperateType(OperateTypeEnum.ADD.getValue());
//            detailLoggerContext.setOperateTypeName(SalaryI18nUtil.getI18nLabel(98125, "新增个税税率表（详细设置）"));
//            detailLoggerContext.setOperatedesc(SalaryI18nUtil.getI18nLabel(96687, "详细设置"));
//            detailLoggerContext.setNewValueList(taxRateDetailPOS);
//            taxRateLoggerTemplate.write(loggerContext);


            sqlSession.commit();

        } finally {
            sqlSession.close();
        }


    }

    public void update(TaxRateSaveParam updateParam, Long employeeId) {

        SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
        try {
            SysTaxRateBaseMapper sysTaxRateBaseMapper = sqlSession.getMapper(SysTaxRateBaseMapper.class);
            TaxRateBaseMapper taxRateBaseMapper = sqlSession.getMapper(TaxRateBaseMapper.class);
            TaxRateDetailMapper taxRateDetailMapper = sqlSession.getMapper(TaxRateDetailMapper.class);

            // 查询是否存在指定的个税税率表
            TaxRateBase taxRateBase = getById(updateParam.getTaxRateBatch().getId());
            if (Objects.isNull(taxRateBase)) {
                throw new SalaryRunTimeException("个税税率表不存在");
            }
            // 个税税率表主表名称不允许重复
            List<TaxRateBase> TaxRateBaseS = listByName(updateParam.getTaxRateBatch().getName());
            boolean nameExist = !CollectionUtils.isEmpty(TaxRateBaseS) &&
                    TaxRateBaseS.stream().anyMatch(e -> !Objects.equals(e.getId(), updateParam.getTaxRateBatch().getId()));
            if (nameExist) {
                throw new SalaryRunTimeException("名称不允许重复");
            }
            // 系统默认的个税税率表不允许编辑
            if (SalarySystemTypeEnum.parseByValue(taxRateBase.getSystemType()) == SalarySystemTypeEnum.SYSTEM) {
                throw new SalaryRunTimeException("系统默认的个税税率表不允许编辑");
            }
            // 更新个税税率表主表
            TaxRateBase newTaxRateBase = new TaxRateBase();
            BeanUtils.copyProperties(taxRateBase, newTaxRateBase);
            newTaxRateBase.setName(updateParam.getTaxRateBatch().getName());
            newTaxRateBase.setDescription(updateParam.getTaxRateBatch().getDescription());
            taxRateBaseMapper.updateIgnoreNull(newTaxRateBase);
            // todo 记录日志
//            LoggerContext loggerContext = new LoggerContext<>();
//            loggerContext.setTargetId(String.valueOf(taxRateBase.getId()));
//            loggerContext.setTargetName(taxRateBase.getName());
//            loggerContext.setOperateType(OperateTypeEnum.UPDATE.getValue());
//            loggerContext.setOperateTypeName(SalaryI18nUtil.getI18nLabel(98108, "编辑个税税率表（基础信息）"));
//            loggerContext.setOperatedesc(SalaryI18nUtil.getI18nLabel(86124, "基础信息"));
//            loggerContext.setOldValues(taxRateBase);
//            loggerContext.setNewValues(newTaxRateBase);
//            taxRateLoggerTemplate.write(loggerContext);
            // 更新个税税率表明细表-先删除后插入
            List<TaxRateDetail> taxRateDetailPOS = taxRateDetailMapper.listByBaseId(taxRateBase.getId());
            taxRateDetailMapper.deleteByBatchIds(Collections.singleton(taxRateBase.getId()));
            List<TaxRateDetail> newTaxRateDetailPOS = TaxRateBO.convert2RecordPO(taxRateBase.getId(), updateParam.getTaxRateRecords(), employeeId);
            new TaxRateDetailBiz().saveBatch(newTaxRateDetailPOS);
            // todo 记录日志
//            LoggerContext detailLoggerContext = new LoggerContext<>();
//            detailLoggerContext.setTargetId(String.valueOf(taxRateBase.getId()));
//            detailLoggerContext.setTargetName(taxRateBase.getName());
//            detailLoggerContext.setOperateType(OperateTypeEnum.UPDATE.getValue());
//            detailLoggerContext.setOperateTypeName(SalaryI18nUtil.getI18nLabel(98128, "新增个税税率表（详细设置）"));
//            detailLoggerContext.setOperatedesc(SalaryI18nUtil.getI18nLabel(96687, "详细设置"));
//            detailLoggerContext.setOldValueList(taxRateDetailPOS);
//            detailLoggerContext.setNewValueList(newTaxRateDetailPOS);
//            taxRateLoggerTemplate.write(loggerContext);


            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }


    /**
     * 个税税率表详情
     *
     * @param id 主表主键id
     * @return
     */
    public TaxRateFormVo getForm(Long id) {
        if (id != null) {
            // 查询个税税率表主表
            TaxRateBase taxRateBasePo = getById(id);
            // 查询个税税率表明细表
            List<TaxRateDetail> taxRateDetailPOS = new TaxRateDetailBiz().listByBaseId(id);
            return TaxRateFormVo.builder().taxRateBatch(taxRateBasePo).taxRateRecords(taxRateDetailPOS).systemType(Optional.ofNullable(taxRateBasePo.getSystemType()).map(SalarySystemTypeEnum::parseByValue).orElse(SalarySystemTypeEnum.CUSTOM)).build();
        }
        return TaxRateFormVo.builder().build();
    }


}
