package com.engine.salary.report.wrapper;

import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.salary.component.WeaFormOption;
import com.engine.salary.entity.hrm.dto.EmployeeInfoExpandDTO;
import com.engine.salary.entity.salaryitem.po.SalaryItemPO;
import com.engine.salary.enums.salaryitem.SalaryDataTypeEnum;
import com.engine.salary.exception.SalaryRunTimeException;
import com.engine.salary.report.common.constant.SalaryStatisticsDimensionConstant;
import com.engine.salary.report.entity.dto.SalaryStatisticsDimensionFormDTO;
import com.engine.salary.report.entity.dto.SalaryStatisticsDimensionListDTO;
import com.engine.salary.report.entity.param.SalaryStatisticsDimensionQueryParam;
import com.engine.salary.report.entity.param.SalaryStatisticsDimensionSaveParam;
import com.engine.salary.report.entity.po.SalaryStatisticsDimensionPO;
import com.engine.salary.report.entity.po.SalaryStatisticsReportPO;
import com.engine.salary.report.enums.SalaryStatisticsDimensionTypeEnum;
import com.engine.salary.report.service.SalaryStatisticsDimensionService;
import com.engine.salary.report.service.SalaryStatisticsReportService;
import com.engine.salary.report.service.impl.SalaryStatisticsDimensionServiceImpl;
import com.engine.salary.report.service.impl.SalaryStatisticsReportServiceImpl;
import com.engine.salary.service.SalaryItemService;
import com.engine.salary.service.impl.SalaryItemServiceImpl;
import com.engine.salary.util.JsonUtil;
import com.engine.salary.util.SalaryI18nUtil;
import com.engine.salary.util.page.PageInfo;
import com.engine.salary.util.page.SalaryPageUtil;
import com.engine.salary.util.valid.ValidUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import weaver.hrm.User;

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

/**
 * 薪酬统计维度
 * <p>Copyright: Copyright (c) 2022</p>
 * <p>Company: 泛微软件</p>
 *
 * @author qiantao
 * @version 1.0
 **/
public class SalaryStatisticsDimensionWrapper extends Service {


    private SalaryStatisticsDimensionService salaryStatisticsDimensionService(User user) {
        return ServiceUtil.getService(SalaryStatisticsDimensionServiceImpl.class, user);
    }

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

    private SalaryStatisticsDimensionService getSalaryStatisticsDimensionService(User user) {
        return ServiceUtil.getService(SalaryStatisticsDimensionServiceImpl.class, user);
    }

    private SalaryStatisticsReportService getSalaryStatisticsReportService(User user) {
        return ServiceUtil.getService(SalaryStatisticsReportServiceImpl.class, user);
    }

    /**
     * 薪酬统计维度列表
     *
     * @param queryParam
     * @return
     */
    public PageInfo<SalaryStatisticsDimensionListDTO> list(SalaryStatisticsDimensionQueryParam queryParam) {
        PageInfo<SalaryStatisticsDimensionPO> page = salaryStatisticsDimensionService(user).listPage(queryParam);
        List<SalaryStatisticsDimensionPO> list = page.getList();
        List<SalaryStatisticsDimensionListDTO> dtoList = new ArrayList<>();

        // 获取默认维度统计
        List<SalaryStatisticsDimensionPO> defaultSalaryStatisticsDimensions = getSalaryStatisticsDimensionService(user).listAllDefaultDimension();
        List<Long> defaultDimensionIds = defaultSalaryStatisticsDimensions.stream().map(SalaryStatisticsDimensionPO::getId).collect(Collectors.toList());
        // 获取有薪资统计报表引用的统计维度
        Set<String> haveUsedDimIds = new HashSet<>();
        List<SalaryStatisticsReportPO> salaryStatisticsReports = getSalaryStatisticsReportService(user).listAll();
        salaryStatisticsReports.stream().forEach(report -> Collections.addAll(haveUsedDimIds, report.getDimension().split(",")));
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(m -> {
                SalaryStatisticsDimensionListDTO dto = SalaryStatisticsDimensionListDTO.builder()
                        .id(m.getId())
                        .dimName(m.getDimName())
                        .remark(m.getRemark())
                        .dimType(SalaryStatisticsDimensionTypeEnum.getDefaultLabelByValue(m.getDimType()))
                        .isDefault(m.getIsDefault())
                        .canEdit(true)
                        .canDelete(true)
                        .build();
                if (defaultDimensionIds.contains(dto.getId())) {
                    // 默认维度不允许修改、删除
                    dto.setCanEdit(false);
                    dto.setCanDelete(false);
                } else if (haveUsedDimIds.contains(dto.getId().toString())) {
                    // 被薪资统计报表引用的不能删除
                    dto.setCanDelete(false);
                }
                dtoList.add(dto);
            });
        }

        PageInfo<SalaryStatisticsDimensionListDTO> salaryStatisticsDimensionListDTOPageInfo = SalaryPageUtil.buildPage(queryParam.getCurrent(), queryParam.getPageSize());
        salaryStatisticsDimensionListDTOPageInfo.setList(dtoList);
        salaryStatisticsDimensionListDTOPageInfo.setTotal(page.getTotal());
        return salaryStatisticsDimensionListDTOPageInfo;
    }

    /**
     * 获取薪酬统计维度表单
     *
     * @param id
     * @return
     */
    public SalaryStatisticsDimensionFormDTO getFrom(Long id) {
        List<SalaryItemPO> salaryItemList = salaryItemService(user).listAll();

        List<WeaFormOption> statsDimOptions = Lists.newArrayList();
//        statsDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_SEX, SalaryI18nUtil.getI18nLabel(98622, "性别")));
//        statsDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_JOB_CALL, SalaryI18nUtil.getI18nLabel(173995, "职称")));
//        statsDimOptions.add(new WeaFormOption("", SalaryI18nUtil.getI18nLabel(173996, "办公地点")));
//        statsDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_SUPERIOR, SalaryI18nUtil.getI18nLabel(173997, "上级")));
//        statsDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_MARITAL_STATUS, SalaryI18nUtil.getI18nLabel(174007, "婚姻状况")));
//        statsDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_EDUCATION, SalaryI18nUtil.getI18nLabel(174005, "学历")));
//        statsDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_DEGREE, SalaryI18nUtil.getI18nLabel(174004, "学位")));
//        statsDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_NATION, SalaryI18nUtil.getI18nLabel(174107, "民族")));
//        statsDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_HOUSEHOLD_TYPE, SalaryI18nUtil.getI18nLabel(174106, "户口类型")));
//        statsDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_POLITICS_STATUS, SalaryI18nUtil.getI18nLabel(174105, "政治面貌")));
//        statsDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_AGE, SalaryI18nUtil.getI18nLabel(174001, "年龄")));
        statsDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_WORK_YEAR, SalaryI18nUtil.getI18nLabel(174000, "工龄")));
        statsDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_COMPANY_YEAR, SalaryI18nUtil.getI18nLabel(174003, "司龄")));
        statsDimOptions.addAll(salaryItemList.stream().map(item -> new WeaFormOption(item.getId().toString(), item.getName())).collect(Collectors.toList()));

        List<WeaFormOption> groupDimOptions = Lists.newArrayList();
//        groupDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_AGE, SalaryI18nUtil.getI18nLabel(174001, "年龄")));
        groupDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_WORK_YEAR, SalaryI18nUtil.getI18nLabel(174000, "工龄")));
        groupDimOptions.add(new WeaFormOption(SalaryStatisticsDimensionConstant.DM_COMPANY_YEAR, SalaryI18nUtil.getI18nLabel(174003, "司龄")));
        groupDimOptions.addAll(salaryItemList.stream()
                .filter(item -> SalaryDataTypeEnum.NUMBER.getValue().equals(item.getDataType()))
                .map(item -> new WeaFormOption(item.getId().toString(), item.getName())).collect(Collectors.toList()));
        // 1.构建基础信息表单
        Map baseForm = new HashMap<>();
        baseForm.put("statsDimOptions", statsDimOptions);
        baseForm.put("groupDimOptions", groupDimOptions);
        // 2.分组设置
        String groupSetting = "[]";
        if (id != null) {
            SalaryStatisticsDimensionPO po = this.salaryStatisticsDimensionService(user).getById(id);
            if (po == null) {
                throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(161116, "薪酬统计维度不存在"));
            }
            groupSetting = po.getSetting();
            Map<String, Object> result = JsonUtil.parseMap(po, Object.class);
            if (SalaryStatisticsDimensionTypeEnum.QUALITATIVE.getValue().equals(po.getDimType())) {
                result.put("statsDim", po.getDimCode());
            } else {
                result.put("groupDim", po.getDimCode());
            }
            baseForm.put("data", result);

            /**
             * 定量-组距式分组
             * [{"id":"1","includeStart":true,"startValue: "10086", "indludeEnd": true, "endValue:"19999"},{"id":"2","includeStart":true,"startValue":"10086","indludeEnd":true,"endValue":"19999"}]
             *
             * 定量-单项式分组
             * [{id:"3",value:"19999"},{id:"3",value:"19999"}]
             */
        } else {
            SalaryStatisticsDimensionPO po = SalaryStatisticsDimensionPO.builder()
                    .dimType(SalaryStatisticsDimensionTypeEnum.QUALITATIVE.getValue())
                    .build();
            baseForm.put("data", JsonUtil.parseMap(po, Object.class));
        }

        return SalaryStatisticsDimensionFormDTO.builder()
                .id(id)
                .baseForm(baseForm)
                .groupSetting(groupSetting)
                .build();
    }

    /**
     * 保存薪酬统计维度
     *
     * @param saveParam
     * @return
     */
    public String save(SalaryStatisticsDimensionSaveParam saveParam) {
        return salaryStatisticsDimensionService(user).save(saveParam);
    }

    /**
     * 保存薪酬统计维度扩展设置
     *
     * @param saveParam
     * @return
     */
    public void saveExpandFieldSettings(EmployeeInfoExpandDTO saveParam) {
        ValidUtil.modify(saveParam);
//        Optional.ofNullable(saveParam.getFieldSettings()).orElse(new ArrayList<>()).forEach(fieldSetting -> fieldSetting.setField(fieldSetting.getField().trim()));
        salaryStatisticsDimensionService(user).saveExpandFieldSettings(saveParam);
    }


    /**
     * 查询薪酬统计维度扩展字段设置
     *
     * @return
     */
    public EmployeeInfoExpandDTO getExpandFieldSettings(String module) {
        return salaryStatisticsDimensionService(user).getExpandFieldSettings(module);
    }

    /**
     * 删除薪酬统计维度
     *
     * @param ids
     * @return
     */
    public Map<String, Object> delete(Collection<Long> ids) {
        return salaryStatisticsDimensionService(user).delete(ids);
    }

    /**
     * 薪酬统计维度下拉列表
     *
     * @return
     */
    public List<Map<String, Object>> selectList() {
        List<SalaryStatisticsDimensionPO> salaryStatisticsDimensions = salaryStatisticsDimensionService(user).listAll();
        return salaryStatisticsDimensions.stream().map(m -> {
            Map<String, Object> map = new HashMap<>(2);
            map.put("id", String.valueOf(m.getId()));
            map.put("content", m.getDimName());
            return map;
        }).collect(Collectors.toList());
    }

}
