package com.engine.salary.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.cloudstore.eccom.constant.WeaBoolAttr;
import com.cloudstore.eccom.pc.table.WeaTableColumn;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.salary.entity.salaryitem.po.SalaryItemPO;
import com.engine.salary.entity.setting.dto.PageListTemplateDTO;
import com.engine.salary.entity.setting.param.*;
import com.engine.salary.entity.setting.po.PageLinkPO;
import com.engine.salary.entity.setting.po.PageListSettingPO;
import com.engine.salary.entity.setting.po.PageListTemplatePO;
import com.engine.salary.entity.taxagent.po.TaxAgentPO;
import com.engine.salary.exception.SalaryRunTimeException;
import com.engine.salary.mapper.setting.PageLinkMapper;
import com.engine.salary.mapper.setting.PageListSettingMapper;
import com.engine.salary.mapper.setting.PageListTemplateMapper;
import com.engine.salary.report.common.constant.SalaryConstant;
import com.engine.salary.service.SalaryItemService;
import com.engine.salary.service.SettingService;
import com.engine.salary.service.TaxAgentService;
import com.engine.salary.util.SalaryEntityUtil;
import com.engine.salary.util.SalaryI18nUtil;
import com.engine.salary.util.db.IdGenerator;
import com.engine.salary.util.db.MapperProxyFactory;
import com.engine.salary.util.valid.ValidUtil;
import weaver.hrm.User;

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

import static com.engine.salary.constant.SalaryDefaultTenantConstant.DEFAULT_TENANT_KEY;
import static com.engine.salary.enums.setting.PageListSettingPageEnum.SALARY_DETAILS_REPORT;

/**
 * 薪资核算
 * <p>Copyright: Copyright (c) 2022</p>
 * <p>Company: 泛微软件</p>
 *
 * @author qiantao
 * @version 1.0
 **/
public class SettingServiceImpl extends Service implements SettingService {

    private PageListSettingMapper getPageListSettingMapper() {
        return MapperProxyFactory.getProxy(PageListSettingMapper.class);
    }

    private PageListTemplateMapper getPageListTemplateMapper() {
        return MapperProxyFactory.getProxy(PageListTemplateMapper.class);
    }

    private PageLinkMapper getPageLinkMapper() {
        return MapperProxyFactory.getProxy(PageLinkMapper.class);
    }

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

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

    @Override
    public void savePageListSetting(PageListSettingSaveParam pageListSettingSaveParam) {
        Date now = new Date();

        PageListSettingPO pageListSettingPO = getPageListSettingMapper().getByPage(pageListSettingSaveParam.getPage());
        List<Long> checked = pageListSettingSaveParam.getSetting().stream().distinct().collect(Collectors.toList());
        if (pageListSettingPO != null) {
            pageListSettingPO.setSetting(checked);
            pageListSettingPO.setUpdateTime(now);
            getPageListSettingMapper().updateIgnoreNull(pageListSettingPO);
        } else {
            pageListSettingPO = PageListSettingPO.builder()
                    .id(IdGenerator.generate())
                    .page(pageListSettingSaveParam.getPage())
                    .setting(checked)
                    .creator((long) user.getUID())
                    .createTime(now)
                    .updateTime(now)
                    .deleteType(0)
                    .tenantKey(DEFAULT_TENANT_KEY)
                    .build();
            getPageListSettingMapper().insertIgnoreNull(pageListSettingPO);
        }
    }

    @Override
    public Map getPageListSetting(PageListSettingQueryParam param) {
        String page = param.getPage();
        Map result = new HashMap();
        PageListSettingPO pageListSettingPO = getPageListSettingMapper().getByPage(page);
        if (SALARY_DETAILS_REPORT.getValue().equals(page)) {
            List<SalaryItemPO> salaryItemList = getSalaryItemService(user).listAll();
            salaryItemList = salaryItemList.stream()
                    .filter(po -> {
                        String name = param.getName();
                        if (StrUtil.isNotEmpty(name)) {
                            return po.getName() != null && po.getName().contains(name);
                        }
                        return true;
                    })
                    .sorted((o1, o2) -> {
                        if (o1.getSortedIndex() == null && o2.getSortedIndex() == null) {
                            Integer systemType1 = o1.getSystemType() == null ? 0 : o1.getSystemType();
                            Integer systemType2 = o2.getSystemType() == null ? 0 : o2.getSystemType();
                            return systemType1.compareTo(systemType2);
                        } else {
                            Integer sortedIndex1 = o1.getSortedIndex() == null ? 0 : o1.getSortedIndex();
                            Integer sortedIndex2 = o2.getSortedIndex() == null ? 0 : o2.getSortedIndex();
                            return sortedIndex2.compareTo(sortedIndex1);
                        }
                    })
                    .collect(Collectors.toList());
            result.put("setting", salaryItemList);
            if (pageListSettingPO != null && CollUtil.isNotEmpty(pageListSettingPO.getSetting())) {
                result.put("checked", pageListSettingPO.getSetting());
            } else {
                List<Long> collect = salaryItemList.stream().map(SalaryItemPO::getId).collect(Collectors.toList());
                result.put("checked", collect);
            }
        }
        return result;
    }

    @Override
    public PageListTemplateDTO getPageListTemplate(PageListTemplateQueryParam param) {
        String page = param.getPage();
        Long id = param.getId();
        if (SALARY_DETAILS_REPORT.getValue().equals(page)) {
            List<WeaTableColumn> columns = new ArrayList<>();
            columns.add(new WeaTableColumn("100px", SalaryI18nUtil.getI18nLabel(87614, "薪资所属月"), "salaryMonth"));
            columns.add(new WeaTableColumn("100px", SalaryI18nUtil.getI18nLabel(86184, "个税扣缴义务人"), "taxAgent"));
            columns.add(new WeaTableColumn("100px", SalaryI18nUtil.getI18nLabel(86184, "账套"), "salarySob"));
            columns.add(new WeaTableColumn("100px", SalaryI18nUtil.getI18nLabel(0, "姓名"), "userName"));
            columns.add(new WeaTableColumn("100px", SalaryI18nUtil.getI18nLabel(0, "分部"), "subCompany"));
            columns.add(new WeaTableColumn("100px", SalaryI18nUtil.getI18nLabel(0, "部门"), "department"));
            columns.add(new WeaTableColumn("100px", SalaryI18nUtil.getI18nLabel(0, "岗位"), "jobTitle"));
            columns.add(new WeaTableColumn("100px", SalaryI18nUtil.getI18nLabel(0, "员工状态"), "status"));
            columns.add(new WeaTableColumn("100px", SalaryI18nUtil.getI18nLabel(0, "工号"), "workCode"));
            columns.add(new WeaTableColumn("100px", SalaryI18nUtil.getI18nLabel(0, "入职日期"), "companystartdate"));
            columns.add(new WeaTableColumn("100px", SalaryI18nUtil.getI18nLabel(86184, "次数"), "acctTimes").setDisplay(WeaBoolAttr.FALSE));
            if (StrUtil.isNotBlank(param.getName())) {
                columns = columns.stream().filter(column -> column.getText().contains(param.getName())).collect(Collectors.toList());
            }

            List<SalaryItemPO> salaryItemList = getSalaryItemService(user).listAll();
            List<WeaTableColumn> collect = salaryItemList.stream()
                    .filter(po -> {
                        String name = param.getName();
                        if (StrUtil.isNotEmpty(name)) {
                            return po.getName() != null && po.getName().contains(name);
                        }
                        return true;
                    })
                    .sorted((o1, o2) -> {
                        if (o1.getSortedIndex() == null && o2.getSortedIndex() == null) {
                            Integer systemType1 = o1.getSystemType() == null ? 0 : o1.getSystemType();
                            Integer systemType2 = o2.getSystemType() == null ? 0 : o2.getSystemType();
                            return systemType1.compareTo(systemType2);
                        } else {
                            Integer sortedIndex1 = o1.getSortedIndex() == null ? 0 : o1.getSortedIndex();
                            Integer sortedIndex2 = o2.getSortedIndex() == null ? 0 : o2.getSortedIndex();
                            return sortedIndex2.compareTo(sortedIndex1);
                        }
                    })
                    .map(item -> new WeaTableColumn("100px", item.getName(), item.getId() + SalaryConstant.DYNAMIC_SUFFIX))
                    .collect(Collectors.toList());

            columns.addAll(collect);

            Map<String, WeaTableColumn> columnMap = SalaryEntityUtil.convert2Map(columns, WeaTableColumn::getColumn);
            List<WeaTableColumn> checkedList = new ArrayList<>();
            if (id != null) {
                PageListTemplatePO po = getPageListTemplateMapper().getById(id);
                if (po != null) {
                    checkedList = Optional.ofNullable(po.getSetting()).orElse(new ArrayList<>())
                            .stream()
                            .map(s -> columnMap.getOrDefault(s, new WeaTableColumn()))
                            .collect(Collectors.toList());

                }
            }
            return PageListTemplateDTO.builder().setting(columns).checked(checkedList).build();
        }

        return PageListTemplateDTO.builder().build();
    }

    @Override
    public List<PageListTemplatePO> getPageListTemplates(PageListTemplateQueryParam param) {

        ValidUtil.doValidator(param);

        String page = param.getPage();

        PageListTemplatePO build = PageListTemplatePO.builder().page(page).build();
        List<PageListTemplatePO> pos = getPageListTemplateMapper().listSome(build);

        //获取当前选择的模板
        PageLinkPO link = getPageLinkMapper().getLink((long) user.getUID(), SALARY_DETAILS_REPORT.getValue());

        Collection<TaxAgentPO> taxAgentPOS = getTaxAgentService().listAllTaxAgents((long) user.getUID());
        List<String> taxIds = SalaryEntityUtil.properties(taxAgentPOS, po -> po.getId().toString(), Collectors.toList());
        pos = pos.stream()
                .filter(po -> {
                    if (po.getSharedType() == 1) {
                        List limitIds = po.getLimitIds();
                        List<String> collect = new ArrayList<>();
                        for (int i = 0; i < limitIds.size(); i++) {
                            collect.add(limitIds.get(i).toString());
                        }
                        return CollectionUtil.isNotEmpty(limitIds) && CollectionUtil.intersection(collect, taxIds).size() != 0;
                    }
                    return true;
                })
                .peek(po -> {
                    po.setChecked(link != null && po.getId().equals(link.getTemplateId()));
                })
                .collect(Collectors.toList());
        return pos;
    }

    @Override
    public PageListTemplatePO savePageListTemplate(PageListTemplateSaveParam param) {
        ValidUtil.doValidator(param);
        Date now = new Date();
        Long id = param.getId();

        PageListTemplatePO po;
        if (id == null) {
            po = PageListTemplatePO.builder()
                    .id(IdGenerator.generate())
                    .page(param.getPage())
                    .name(param.getName())
                    .sharedType(param.getSharedType())
                    .limitIds(param.getLimitIds())
                    .setting(param.getSetting())
                    .creator((long) user.getUID())
                    .createTime(now)
                    .updateTime(now)
                    .deleteType(0)
                    .tenantKey(DEFAULT_TENANT_KEY)
                    .build();
            getPageListTemplateMapper().insertIgnoreNull(po);
        } else {
            po = getPageListTemplateMapper().getById(id);
            if (po == null) {
                throw new SalaryRunTimeException("模板不存在!");
            }
            po.setName(param.getName());
            po.setSharedType(param.getSharedType());
            po.setLimitIds(param.getLimitIds());
            po.setSetting(param.getSetting());
            po.setUpdateTime(now);
            getPageListTemplateMapper().updateIgnoreNull(po);
        }

        return po;
    }

    @Override
    public void changePageListTemplate(PageListTemplateChangeParam param) {

        ValidUtil.doValidator(param);

        List<PageLinkPO> pageLinkPOS = getPageLinkMapper().listSome(PageLinkPO.builder().employeeId((long) user.getUID()).page(param.getPage()).build());
        if (CollUtil.isNotEmpty(pageLinkPOS)) {
            Set<Long> ids = SalaryEntityUtil.properties(pageLinkPOS, PageLinkPO::getId);
            getPageLinkMapper().deleteByIds(ids);
        }
        PageLinkPO pageLinkPO = PageLinkPO.builder()
                .id(IdGenerator.generate())
                .employeeId((long) user.getUID())
                .page(param.getPage())
                .templateId(param.getTemplateId())
                .tenantKey(DEFAULT_TENANT_KEY)
                .createTime(new Date())
                .updateTime(new Date())
                .creator((long) user.getUID())
                .deleteType(0)
                .build();

        getPageLinkMapper().insertIgnoreNull(pageLinkPO);
    }

    @Override
    public List<WeaTableColumn> getPageListColumns(String page) {
        PageLinkPO link = getPageLinkMapper().getLink((long) user.getUID(), page);
        if (link != null) {
            PageListTemplateDTO pageListTemplate = getPageListTemplate(PageListTemplateQueryParam.builder().page(page).id(link.getTemplateId()).build());
            return pageListTemplate.getChecked();
        } else {
            PageListTemplateDTO pageListTemplate = getPageListTemplate(PageListTemplateQueryParam.builder().page(page).build());
            return pageListTemplate.getSetting();
        }
    }
}
