package com.engine.salary.wrapper;

import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.salary.component.WeaFormOption;
import com.engine.salary.config.SalaryElogConfig;
import com.engine.hrmelog.entity.dto.LoggerContext;
import com.engine.salary.entity.salaryformula.ExpressFormula;
import com.engine.salary.entity.salaryitem.bo.SalaryItemBO;
import com.engine.salary.entity.salaryitem.bo.SysSalaryItemBO;
import com.engine.salary.entity.salaryitem.dto.SalaryItemFormDTO;
import com.engine.salary.entity.salaryitem.dto.SalaryItemListDTO;
import com.engine.salary.entity.salaryitem.param.SalaryItemSaveParam;
import com.engine.salary.entity.salaryitem.param.SalaryItemSearchParam;
import com.engine.salary.entity.salaryitem.param.SyncSalaryItemParam;
import com.engine.salary.entity.salaryitem.po.SalaryItemPO;
import com.engine.salary.entity.salaryitem.po.SysSalaryItemPO;
import com.engine.salary.entity.salarysob.po.SalarySobItemPO;
import com.engine.salary.enums.*;
import com.engine.salary.enums.salaryitem.SalaryDataTypeEnum;
import com.engine.salary.exception.SalaryRunTimeException;
import com.engine.salary.service.*;
import com.engine.salary.service.impl.*;
import com.engine.salary.sys.enums.TaxDeclarationFunctionEnum;
import com.engine.salary.sys.service.SalarySysConfService;
import com.engine.salary.sys.service.impl.SalarySysConfServiceImpl;
import com.engine.salary.util.SalaryEntityUtil;
import com.engine.salary.util.SalaryI18nUtil;
import com.engine.salary.util.page.PageInfo;
import com.engine.salary.util.valid.RuntimeTypeEnum;
import com.engine.salary.util.valid.ValidUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.hrm.User;

import java.util.*;

/**
 * 薪资项目
 * <p>Copyright: Copyright (c) 2022</p>
 * <p>Company: 泛微软件</p>
 *
 * @author qiantao
 * @version 1.0
 **/
public class SalaryItemWrapper extends Service {

    private SalaryItemService getSalaryItemService(User user) {
        return ServiceUtil.getService(SalaryItemServiceImpl.class, user);
    }

    private SysSalaryItemService getSysSalaryItemService(User user) {
        return ServiceUtil.getService(SysSalaryItemServiceImpl.class, user);
    }

    private SalaryFormulaService getSalaryFormulaService(User user) {
        return ServiceUtil.getService(SalaryFormulaServiceImpl.class, user);
    }


    private SalarySobItemService getSalarySobItemService(User user) {
        return ServiceUtil.getService(SalarySobItemServiceImpl.class, user);
    }

    private SalarySobBackItemService getSalarySobBackItemService(User user) {
        return ServiceUtil.getService(SalarySobBackItemServiceImpl.class, user);
    }

    private SalarySysConfService getSalarySysConfService(User user) {
        return ServiceUtil.getService(SalarySysConfServiceImpl.class, user);
    }

    /**
     * 薪资项目列表
     *
     * @param searchParam 查询参数
     * @return
     */
    public PageInfo<SalaryItemListDTO> listPage(SalaryItemSearchParam searchParam) {
        SalaryItemServiceImpl.UsingItem usingItem = getSalaryItemService(user).getUsingItem();
        List<Long> usingFormulaIds = usingItem.getUsingFormulaIds();
        List<Long> usingItemIds = usingItem.getUsingItemIds();
        List<String> usingCodes = usingItem.getUsingCodes();

        //删除无用公式
        getSalaryFormulaService(user).deleteNotIn(usingFormulaIds);

        //薪资档案引用的项目转移到字段管理功能项
        searchParam.setUseInEmployeeSalary(SalaryOnOffEnum.OFF.getValue());

        // 1、查询薪资项目
        PageInfo<SalaryItemPO> page = getSalaryItemService(user).listPageByParam(searchParam);
        List<SalaryItemPO> salaryItemList = page.getList();

        //最终返回的分页对象
        PageInfo<SalaryItemListDTO> salaryItemListDTOPage = new PageInfo<>(SalaryItemListDTO.class);
        salaryItemListDTOPage.setPageSize(page.getPageSize());
        salaryItemListDTOPage.setPageNum(page.getPageNum());
        salaryItemListDTOPage.setTotal(page.getTotal());

        //是否需要系统算税，不需要则去除系统项目
        TaxDeclarationFunctionEnum taxDeclarationFunctionEnum = getSalarySysConfService(user).getTaxDeclaration();


        // 被薪资账套引用的薪资项目
        if (CollectionUtils.isNotEmpty(salaryItemList)) {
            //2、填充公式内容
            Set<Long> formulaIds = SalaryEntityUtil.properties(salaryItemList, SalaryItemPO::getFormulaId);
            List<ExpressFormula> expressFormulas = getSalaryFormulaService(user).listExpressFormula(formulaIds);
            // 查询系统薪资项目
            Set<Long> sysSalaryItemIds = SalaryEntityUtil.properties(salaryItemList, SalaryItemPO::getSysSalaryItemId);
            List<SysSalaryItemPO> sysSalaryItemPOS = getSysSalaryItemService(user).listByIds(sysSalaryItemIds);
            // 转换成薪资项目列表dto
            List<SalaryItemListDTO> salaryItemListDTOS = SalaryItemBO.convert2ListDTO(salaryItemList, expressFormulas, sysSalaryItemPOS);
            //系统项目不删除
            salaryItemListDTOS.forEach(dto -> {
                if ((taxDeclarationFunctionEnum != TaxDeclarationFunctionEnum.CLOSURE && StringUtils.isNotBlank(dto.getSystemName()))
                        || usingItemIds.contains(dto.getId())
                        || usingCodes.contains(dto.getCode())) {
                    dto.setCanDelete(false);
                }
            });
            salaryItemListDTOPage.setList(salaryItemListDTOS);
        }

        return salaryItemListDTOPage;

    }


    /**
     * 可以删除的薪资项目列表
     *
     * @param searchParam 查询人员
     * @return
     */
    public PageInfo<SalaryItemListDTO> listPage4CanDelete(SalaryItemSearchParam searchParam) {
        // 查询所有薪资账套中的薪资项目副本
        List<SalarySobItemPO> salarySobItemPOS = getSalarySobItemService(user).list();
        // 被引用的薪资项目id
        Set<Long> salaryItemIds = SalaryEntityUtil.properties(salarySobItemPOS, SalarySobItemPO::getSalaryItemId);
        // 排除被引用的薪资项目（被引用的薪资项目不可以删除）
        searchParam.setExcludeIds(salaryItemIds);
        // 转换成前端所需的数据格式
        return listPage(searchParam);

    }

    /**
     * 根据主键id获取薪资项目详情
     *
     * @param ids 薪资项目的主键id
     * @return
     */
    public List<SalaryItemListDTO> listByIds(Collection<Long> ids) {
        List<SalaryItemPO> salaryItemPOS = getSalaryItemService(user).listByIds(ids);
        if (CollectionUtils.isEmpty(salaryItemPOS)) {
            return Collections.emptyList();
        }
        // 查询公式详情
        Set<Long> formulaIds = SalaryEntityUtil.properties(salaryItemPOS, SalaryItemPO::getFormulaId);
        List<ExpressFormula> expressFormulas = getSalaryFormulaService(user).listExpressFormula(formulaIds);
        // 查询系统薪资项目
        Set<Long> sysSalaryItemIds = SalaryEntityUtil.properties(salaryItemPOS, SalaryItemPO::getSysSalaryItemId);
        List<SysSalaryItemPO> sysSalaryItemPOS = getSysSalaryItemService(user).listByIds(sysSalaryItemIds);
        // 转换成薪资项目列表dto
        return SalaryItemBO.convert2ListDTO(salaryItemPOS, expressFormulas, sysSalaryItemPOS);
    }

    /**
     * 薪资项目详情
     *
     * @param id 主键id
     * @return
     */
    public SalaryItemFormDTO getForm(Long id) {
        SalaryItemFormDTO salaryItemFormDTO = new SalaryItemFormDTO();
        // 默认可以编辑
        salaryItemFormDTO.setCanEdit(NumberUtils.INTEGER_ONE);
        if (!Objects.isNull(id)) {
            // 查询薪资项目
            SalaryItemPO salaryItemPO = getSalaryItemService(user).getById(id);
            // 系统薪资项目
            SysSalaryItemPO sysSalaryItemPO = getSysSalaryItemService(user).getById(id);
            if (Objects.isNull(salaryItemPO) && Objects.isNull(sysSalaryItemPO)) {
                throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(98299, "参数错误，薪资项目不存在或已被删除"));
            }
            ExpressFormula expressFormula;
//            // 转换成薪资项目详情dto
            if (Objects.isNull(salaryItemPO)) {
                salaryItemFormDTO = SysSalaryItemBO.convert2FormDTO(sysSalaryItemPO);
                expressFormula = getSalaryFormulaService(user).getExpressFormula(sysSalaryItemPO.getFormulaId());
            } else {
                salaryItemFormDTO = SalaryItemBO.convert2FormDTO(salaryItemPO);
                expressFormula = getSalaryFormulaService(user).getExpressFormula(salaryItemPO.getFormulaId());
            }
            String formulaContent = Optional.ofNullable(expressFormula).map(ExpressFormula::getFormula).orElse("");
            salaryItemFormDTO.setFormulaContent(formulaContent);
            salaryItemFormDTO.setOriginFormulaContent(salaryItemFormDTO.getValueType().equals(SalaryValueTypeEnum.FORMULA.getValue()) ? formulaContent : "");
            salaryItemFormDTO.setOriginSqlContent(salaryItemFormDTO.getValueType().equals(SalaryValueTypeEnum.SQL.getValue()) ? formulaContent : "");
        }
        return salaryItemFormDTO;
    }

    /**
     * 获取薪资项目可选的类型（与属性有联动）
     *
     * @return
     */
    public Map<String, List<WeaFormOption>> listSalaryItemTypeOption() {
        return SalaryEntityUtil.group2ListMap(Arrays.asList(SalaryItemTypeEnum.values()),
                e -> e.getCategory().name(),
                e -> new WeaFormOption(e.name(), SalaryI18nUtil.getI18nLabel(e.getLabelId(), e.getDefaultLabel())));
    }

    /**
     * 保存薪资项目
     *
     * @param saveParam 保存参数
     */
    public void save(SalaryItemSaveParam saveParam) {
        ValidUtil.doValidator(saveParam);
        validParam(saveParam);

        SalaryItemPO salaryItemPO = getSalaryItemService(user).save(saveParam);
        // 记录日志
        LoggerContext<SalaryItemPO> loggerContext = new LoggerContext<>();
        loggerContext.setUser(user);
        loggerContext.setTargetId(String.valueOf(salaryItemPO.getId()));
        loggerContext.setTargetName(salaryItemPO.getName());
        loggerContext.setOperateType(OperateTypeEnum.ADD.getValue());
        loggerContext.setOperateTypeName(SalaryI18nUtil.getI18nLabel(0, "新建薪资项目"));
        loggerContext.setOperatedesc(SalaryI18nUtil.getI18nLabel(0, "新建薪资项目") + ": " + salaryItemPO.getName());
        loggerContext.setNewValues(salaryItemPO);
        SalaryElogConfig.salaryItemLoggerTemplate.write(loggerContext);
    }

    private void validParam(SalaryItemSaveParam saveParam) {
        if (SalarySystemTypeEnum.parseByValue(saveParam.getSystemType()) == null) {
            throw new SalaryRunTimeException("系统内置的薪资项目异常");
        }
        if (SalaryRoundingModeEnum.parseByValue(saveParam.getRoundingMode()) == null) {
            throw new SalaryRunTimeException("舍入规则异常");
        }
        if (SalaryValueTypeEnum.parseByValue(saveParam.getValueType()) == null) {
            throw new SalaryRunTimeException("取值方式异常");
        }
        if (SalaryDataTypeEnum.parseByValue(saveParam.getDataType()) == null) {
            throw new SalaryRunTimeException("字段类型异常");
        }
        if (saveParam.getName().contains("{") || saveParam.getName().contains("}") || saveParam.getName().contains(".")) {
            throw new SalaryRunTimeException("薪资项目名称中不得包含大括号或点");
        }
    }

    /**
     * 编辑薪资项目
     *
     * @param saveParam 更新参数
     */
    public void update(SalaryItemSaveParam saveParam) {
        ValidUtil.doValidator(saveParam, RuntimeTypeEnum.UPDATE);
        validParam(saveParam);
        SalaryItemPO salaryItemPO = getSalaryItemService(user).update(saveParam);

        // 记录日志
        SalaryItemPO newSalaryItemPO = getSalaryItemService(user).getById(salaryItemPO.getId());
        LoggerContext<SalaryItemPO> loggerContext = new LoggerContext<>();
        loggerContext.setUser(user);
        loggerContext.setTargetId(String.valueOf(newSalaryItemPO.getId()));
        loggerContext.setTargetName(newSalaryItemPO.getName());
        loggerContext.setOperateType(OperateTypeEnum.UPDATE.getValue());
        loggerContext.setOperateTypeName(SalaryI18nUtil.getI18nLabel(0, "编辑字段"));
        loggerContext.setOperatedesc(SalaryI18nUtil.getI18nLabel(0, "编辑字段") + ": " + newSalaryItemPO.getName());
        loggerContext.setOldValues(salaryItemPO);
        loggerContext.setNewValues(newSalaryItemPO);
        SalaryElogConfig.salaryItemLoggerTemplate.write(loggerContext);
    }

    /**
     * 删除薪资项目
     *
     * @param ids 主键id
     */
    public void delete(Collection<Long> ids) {
        getSalaryItemService(user).deleteByIds(ids);
    }


    /**
     * 获取薪资项目在哪些账套中使用
     * @param salaryItemId
     */
    public List<Map<String, Object>> getSalarySobBySalaryItem(Long salaryItemId) {
        return getSalaryItemService(user).getSalarySobBySalaryItem(salaryItemId);
    }

    /**
     * 将薪资项目管理中的信息同步至账套
     * @param syncSalaryItemParam
     */
    public void syncSalaryItemToSalarySobItem(SyncSalaryItemParam syncSalaryItemParam) {
        getSalaryItemService(user).syncSalaryItemToSalarySobItem(syncSalaryItemParam);
    }
}
