package com.engine.salary.report.wrapper;

import com.cloudstore.eccom.constant.WeaBoolAttr;
import com.cloudstore.eccom.pc.table.WeaTable;
import com.cloudstore.eccom.pc.table.WeaTableColumn;
import com.cloudstore.eccom.result.WeaResultMsg;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.salary.component.SalaryWeaTable;
import com.engine.salary.entity.salaryacct.po.SalaryAcctEmployeePO;
import com.engine.salary.entity.salaryarchive.dto.SalaryArchiveListDTO;
import com.engine.salary.entity.salaryitem.po.SalaryItemPO;
import com.engine.salary.report.common.constant.SalaryConstant;
import com.engine.salary.report.entity.bo.SalaryStatisticsReportBO;
import com.engine.salary.report.entity.dto.SalaryStatisticsEmployeeDetailResultDTO;
import com.engine.salary.report.entity.dto.SalaryStatisticsEmployeeListDTO;
import com.engine.salary.report.entity.param.SalaryStatisticsEmployeeDetailQueryParam;
import com.engine.salary.report.entity.param.SalaryStatisticsEmployeeQueryParam;
import com.engine.salary.report.entity.param.SalaryStatisticsEmployeeSalaryQueryParam;
import com.engine.salary.report.service.SalaryStatisticsEmployeeService;
import com.engine.salary.report.service.impl.SalaryStatisticsEmployeeServiceImpl;
import com.engine.salary.report.util.ReportDataUtil;
import com.engine.salary.util.SalaryI18nUtil;
import com.engine.salary.util.excel.ExcelUtilPlus;
import com.engine.salary.util.page.PageInfo;
import com.engine.salary.util.page.SalaryPageUtil;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import weaver.general.PageIdConst;
import weaver.general.Util;
import weaver.hrm.User;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 薪酬统计员工明细
 * <p>Copyright: Copyright (c) 2022</p>
 * <p>Company: 泛微软件</p>
 *
 * @author qiantao
 * @version 1.0
 **/
public class SalaryStatisticsEmployeeWrapper extends Service {

    private SalaryStatisticsEmployeeService getSalaryStatisticsEmployeeService(User user) {
        return ServiceUtil.getService(SalaryStatisticsEmployeeServiceImpl.class, user);
    }

    /**
     * 员工列表
     *
     * @param queryParam
     * @return
     */
    public PageInfo<SalaryStatisticsEmployeeListDTO> list(SalaryStatisticsEmployeeQueryParam queryParam) {
        return getSalaryStatisticsEmployeeService(user).listPage(queryParam);
    }

    /**
     * 员工详情列表
     *
     * @param queryParam
     * @return
     */
    public Map<String, Object> detailList(SalaryStatisticsEmployeeDetailQueryParam queryParam) {
        // 获取核算数据
        SalaryStatisticsEmployeeDetailResultDTO salaryStatisticsEmployeeDetailResult = getSalaryStatisticsEmployeeService(user).getDetailSalaryAcctResult(queryParam);
        List<Map<String, Object>> records = getSalaryStatisticsEmployeeService(user).listDetailPage(salaryStatisticsEmployeeDetailResult, queryParam);

        Map<String, Object> countResultMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(records)) {
            List<SalaryItemPO> salaryItems = salaryStatisticsEmployeeDetailResult.getSalaryItemList();
            for (SalaryItemPO item : salaryItems) {
                BigDecimal sumBigDecimal = new BigDecimal(SalaryStatisticsReportBO.ZERO);
                String itemKey = item.getId() + SalaryConstant.DYNAMIC_SUFFIX;
                for (Map<String, Object> record : records) {
                    if (record.containsKey(itemKey)) {
                        if (Objects.nonNull(record.get(itemKey)) && StringUtils.isNotEmpty(record.get(itemKey).toString()) && NumberUtils.isCreatable(record.get(itemKey).toString())) {
                            sumBigDecimal = sumBigDecimal.add(new BigDecimal(record.get(itemKey).toString()));
                            record.put(itemKey, ReportDataUtil.thousandthConvert(record.get(itemKey).toString()));
                        }
                    }
                }
                countResultMap.put(itemKey, ReportDataUtil.thousandthConvert(sumBigDecimal.toString()));
            }
        }
        PageInfo<Map<String, Object>> pageInfo = SalaryPageUtil.buildPage(queryParam.getCurrent(), queryParam.getPageSize(), records);

        // 列表columns
        List<WeaTableColumn> weaTableColumns = buildDetailTableColumns(salaryStatisticsEmployeeDetailResult, false);

        SalaryWeaTable<SalaryArchiveListDTO> table = new SalaryWeaTable<SalaryArchiveListDTO>(user, SalaryStatisticsEmployeeDetailResultDTO.class);
        table.setColumns(weaTableColumns);

        WeaResultMsg result = new WeaResultMsg(false);
        result.putAll(table.makeDataResult());
        result.success();

        // 结果
        Map<String, Object> resultMap = Maps.newHashMap();
//        resultMap.put("columns", weaTableColumns);
        resultMap.put("dataKey", result.getResultMap());
        resultMap.put("pageInfo", pageInfo);
        resultMap.put("countResult", countResultMap);
        return resultMap;
    }

    private List<WeaTableColumn> buildDetailTableColumns(SalaryStatisticsEmployeeDetailResultDTO salaryStatisticsEmployeeDetailResult, boolean isSalaryList) {
        // 表格表头
        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"));
        if (isSalaryList) {
            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(86184, "次数"), "acctTimes").setDisplay(WeaBoolAttr.FALSE));
//        columns.add(new WeaTableColumn("100px",SalaryI18nUtil.getI18nLabel( 121908, "收入所得项目"), "incomeCategory"));
        salaryStatisticsEmployeeDetailResult.getSalaryItemList().forEach(item -> {
            columns.add(new WeaTableColumn("100px", item.getName(), item.getId() + SalaryConstant.DYNAMIC_SUFFIX));
        });
        return columns;
    }

    /**
     * 获取员工发薪明细列表
     * @param queryParam
     */
    public Map<String, Object> salaryList(SalaryStatisticsEmployeeSalaryQueryParam queryParam) {
        Map<String, Object> resultMap = Maps.newHashMap();
        if (StringUtils.isBlank(queryParam.getStartDateStr()) || StringUtils.isBlank(queryParam.getEndDateStr())) {
            return resultMap;
        }
        // 获取发薪人员
        PageInfo<SalaryAcctEmployeePO> salaryAcctEmployeePageInfo = getSalaryStatisticsEmployeeService(user).listSalaryAcctEmp(queryParam);
        // 获取薪资核算结果
        SalaryStatisticsEmployeeDetailResultDTO salaryStatisticsEmployeeDetailResult  = getSalaryStatisticsEmployeeService(user).getDetailSalaryAcctResultByAcctEmp(salaryAcctEmployeePageInfo.getList());
        List<Map<String, Object>> records = getSalaryStatisticsEmployeeService(user).listDetailPage(salaryStatisticsEmployeeDetailResult, null);

        Map<String, Object> countResultMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(records)) {
            List<SalaryItemPO> salaryItems = salaryStatisticsEmployeeDetailResult.getSalaryItemList();
            for (SalaryItemPO item : salaryItems) {
                BigDecimal sumBigDecimal = new BigDecimal(SalaryStatisticsReportBO.ZERO);
                String itemKey = item.getId() + SalaryConstant.DYNAMIC_SUFFIX;
                for (Map<String, Object> record : records) {
                    if (record.containsKey(itemKey)) {
                        if (Objects.nonNull(record.get(itemKey)) && StringUtils.isNotEmpty(record.get(itemKey).toString()) && NumberUtils.isCreatable(record.get(itemKey).toString())) {
                            sumBigDecimal = sumBigDecimal.add(new BigDecimal(record.get(itemKey).toString()));
                            record.put(itemKey, ReportDataUtil.thousandthConvert(record.get(itemKey).toString()));
                        }
                    }
                }
                // 薪资项目合计
                if (queryParam.isExport()) {
                    countResultMap.put(itemKey, ReportDataUtil.thousandthConvert(sumBigDecimal.toString()));
                }
            }
        }
        PageInfo<Map<String, Object>> pageInfo = SalaryPageUtil.buildPage(queryParam.getCurrent(), queryParam.getPageSize());
        pageInfo.setList(records);
        if (queryParam.isExport()) {
            pageInfo.setList(records);
        }
        pageInfo.setTotal(salaryAcctEmployeePageInfo.getTotal());

        // 列表columns
        List<WeaTableColumn> weaTableColumns = buildDetailTableColumns(salaryStatisticsEmployeeDetailResult, true);

        // 结果
        if (queryParam.isExport()) {
            resultMap.put("columns", weaTableColumns);
            resultMap.put("salaryItems",salaryStatisticsEmployeeDetailResult.getSalaryItemList());
            resultMap.put("countResult", countResultMap);
        } else {
            WeaTable table = new WeaTable();
            String pageId = "b72ed4bb-725e-45de-aea1-4eb4c9184af7";
            table.setPageID(pageId);
            table.setPageUID(pageId + user.getUID());
            table.setPagesize(PageIdConst.getPageSize(pageId, user.getUID()));
            table.setBackfields("");
            table.setColumns(weaTableColumns);

            WeaResultMsg result = new WeaResultMsg(false);
            result.putAll(table.makeDataResult());
            result.success();
            resultMap.put("dataKey", result.getResultMap());
        }
        resultMap.put("pageInfo", pageInfo);
        return resultMap;
    }

    /**
     * 获取员工发薪明细列表
     * @param queryParam
     */
    public Map<String, Object> salaryListSum(SalaryStatisticsEmployeeSalaryQueryParam queryParam) {
        Map<String, Object> resultMap = Maps.newHashMap();
        if (StringUtils.isBlank(queryParam.getStartDateStr()) || StringUtils.isBlank(queryParam.getEndDateStr())) {
            return resultMap;
        }
        queryParam.setExport(true);
        // 获取发薪人员
        PageInfo<SalaryAcctEmployeePO> salaryAcctEmployeePageInfo = getSalaryStatisticsEmployeeService(user).listSalaryAcctEmp(queryParam);
        // 获取薪资核算结果
        SalaryStatisticsEmployeeDetailResultDTO salaryStatisticsEmployeeDetailResult  = getSalaryStatisticsEmployeeService(user).getDetailSalaryAcctResultByAcctEmp(salaryAcctEmployeePageInfo.getList());
        List<Map<String, Object>> records = getSalaryStatisticsEmployeeService(user).listDetailPage(salaryStatisticsEmployeeDetailResult, null);

        Map<String, Object> sumResultMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(records)) {
            List<SalaryItemPO> salaryItems = salaryStatisticsEmployeeDetailResult.getSalaryItemList();
            for (SalaryItemPO item : salaryItems) {
                BigDecimal sumBigDecimal = new BigDecimal(SalaryStatisticsReportBO.ZERO);
                String itemKey = item.getId() + SalaryConstant.DYNAMIC_SUFFIX;
                for (Map<String, Object> record : records) {
                    if (record.containsKey(itemKey)) {
                        if (Objects.nonNull(record.get(itemKey)) && StringUtils.isNotEmpty(record.get(itemKey).toString()) && NumberUtils.isCreatable(record.get(itemKey).toString())) {
                            sumBigDecimal = sumBigDecimal.add(new BigDecimal(record.get(itemKey).toString()));
                        }
                    }
                }
                // 薪资项目合计
                sumResultMap.put(itemKey, ReportDataUtil.thousandthConvert(sumBigDecimal.toString()));
            }
        }
        resultMap.put("sumRow", sumResultMap);
        return resultMap;
    }

    public XSSFWorkbook exportSalaryList(SalaryStatisticsEmployeeSalaryQueryParam queryParam) {
        queryParam.setCurrent(1);
        queryParam.setExport(true);
        Map<String, Object> resultMap = salaryList(queryParam);
        List<WeaTableColumn> columns = (List<WeaTableColumn>)resultMap.get("columns");
        List<SalaryItemPO> salaryItemList = ((List<SalaryItemPO>)resultMap.get("salaryItems"));
        List<Map<String, Object>> resultList = ((PageInfo<Map<String, Object>>) resultMap.get("pageInfo")).getList();
        Map<String, Object> countResult = (Map<String, Object>)resultMap.get("countResult");

        List<List<Object>> rowList = new ArrayList<>();
        // 表头
        rowList.add(columns.stream().map(WeaTableColumn::getText).collect(Collectors.toList()));
        // 数据
        for (Map<String, Object> valueMap : resultList) {
            List<Object> list = new ArrayList<>();
            for (WeaTableColumn column : columns) {
                list.add(Util.null2String(valueMap.get(column.getColumn())));
            }
            rowList.add(list);
        }
        // 合计
        List<Object> sumRow = new ArrayList<>();
        sumRow.add("总计");
        for (int i=1; i<columns.size(); i++) {
            sumRow.add(Util.null2String(countResult.get(columns.get(i).getColumn())));
        }
        rowList.add(sumRow);

        return ExcelUtilPlus.genWorkbookV2(rowList,"薪资明细",true);
    }

//    public Map<String, Object> exportDetailList(SalaryStatisticsEmployeeDetailQueryParam queryParam) {
//        SalaryAssert.notNull(queryParam.getEmployeeId(), SalaryI18nUtil.getI18nLabel(currentTenantKey, currentEmployeeId, 163974, "人员id不能为空"));
//        // 构建异步导出参数
//        Map<String, Object> map = salaryBatchService.buildeExportParam("exportSalaryStatisticsEmployeeDetailList");
//        LocalRunnable localRunnable = new LocalRunnable() {
//            @Override
//            public void execute() {
//                try {
//                    DSTenantKeyThreadVar.tenantKey.set(currentTenantKey);
//                    getSalaryStatisticsEmployeeService(user).exportDetailList(map, queryParam);
//                } finally {
//                    DSTenantKeyThreadVar.tenantKey.remove();
//                }
//            }
//        };
//        ThreadPoolUtil.execute(localRunnable);
//
//        return map;
//    }
}
