package com.engine.organization.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.api.browser.bean.SearchConditionGroup;
import com.api.browser.bean.SearchConditionItem;
import com.cloudstore.dev.api.service.Service_DevTable;
import com.cloudstore.eccom.constant.WeaBoolAttr;
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.organization.component.OrganizationWeaTable;
import com.engine.organization.entity.department.bo.DepartmentBO;
import com.engine.organization.entity.department.dto.DepartmentListDTO;
import com.engine.organization.entity.department.po.DepartmentPO;
import com.engine.organization.entity.hrmresource.po.SearchTemplatePO;
import com.engine.organization.entity.hrmresource.vo.HrmResourceVO;
import com.engine.organization.entity.staff.po.StaffPO;
import com.engine.organization.entity.staff.vo.StaffTableVO;
import com.engine.organization.mapper.department.DepartmentMapper;
import com.engine.organization.mapper.resource.HrmResourceMapper;
import com.engine.organization.mapper.resource.ResourceMapper;
import com.engine.organization.mapper.staff.StaffMapper;
import com.engine.organization.mapper.staff.StaffPlanMapper;
import com.engine.organization.service.ExportCommonService;
import com.engine.organization.transmethod.JobTransMethod;
import com.engine.organization.transmethod.StaffPlanTransMethod;
import com.engine.organization.transmethod.StaffTransMethod;
import com.engine.organization.util.HrmI18nUtil;
import com.engine.organization.util.PageInfoSortUtil;
import com.engine.organization.util.db.MapperProxyFactory;
import com.engine.organization.util.detach.DetachUtil;
import com.engine.organization.util.excel.ExcelUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.systeminfo.SystemEnv;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author weaver_cl
 * @Description:
 * @Date 2022/6/28
 * @Version V1.0
 **/
public class ExportCommonServiceImpl extends Service implements ExportCommonService {


    private static DepartmentMapper getDepartmentMapper() {
        return MapperProxyFactory.getProxy(DepartmentMapper.class);
    }

    private static StaffMapper getStaffMapper() {
        return MapperProxyFactory.getProxy(StaffMapper.class);
    }

    private static StaffPlanMapper getStaffPlanMapper() {
        return MapperProxyFactory.getProxy(StaffPlanMapper.class);
    }



    @Override
    public XSSFWorkbook resourceExport(List<Long> ids) {

        List<HrmResourceVO> hrmResourceVOS ;
        DetachUtil detachUtil = new DetachUtil(user);
        if (detachUtil.isDETACH()) {
            if (StringUtils.isBlank(detachUtil.getJclRoleLevels())) {
                hrmResourceVOS = new ArrayList<>();
            } else {
                List<Long> jclRoleLevelList = Arrays.stream(detachUtil.getJclRoleLevels().split(",")).map(Long::parseLong).collect(Collectors.toList());
                hrmResourceVOS = MapperProxyFactory.getProxy(ResourceMapper.class).listDetachAll(ids, jclRoleLevelList);
            }
        } else {
            hrmResourceVOS = MapperProxyFactory.getProxy(ResourceMapper.class).listAll(ids);
        }
        if (hrmResourceVOS == null) {
            hrmResourceVOS = new ArrayList<>();
        }
        // 1.工作簿名称
        String sheetName = HrmI18nUtil.getI18nLabel(85368, "人员档案数据");
        // 2.表头(后面动态获取)
        List<List<Object>> excelSheetData = new ArrayList<>();

        Object[] header = {
                HrmI18nUtil.getI18nLabel( 93270, "姓名"),
                HrmI18nUtil.getI18nLabel( 93272, "部门"),
                HrmI18nUtil.getI18nLabel( 93274, "分部"),
                HrmI18nUtil.getI18nLabel( 93275, "移动电话"),
                HrmI18nUtil.getI18nLabel( 93278, "办公室电话"),
                HrmI18nUtil.getI18nLabel( 93279, "直接上级")};
        List<Object> strings = Arrays.asList(header);
        excelSheetData.add(strings);

        //数据
        List<List<Object>> rows = new LinkedList<>();
        for (HrmResourceVO vo : hrmResourceVOS) {
            List<Object> row = new LinkedList<>();
            row.add(vo.getLastName());
            row.add(vo.getDepartmentName());
            row.add(vo.getCompanyName());
            row.add(vo.getMobile());
            row.add(vo.getTelephone());
            row.add(vo.getManagerName());
            rows.add(row);
        }
        excelSheetData.addAll(rows);
        return ExcelUtil.genWorkbookV2(excelSheetData, sheetName);
    }

    @Override
    public XSSFWorkbook resourceExport(HttpServletRequest request, HttpServletResponse response, String ids) {
        List<String> headerList = new ArrayList<>();
        List<Object> headerNameList = new ArrayList<>();
        OrganizationWeaTable<HrmResourceVO> table = new OrganizationWeaTable<>(user, HrmResourceVO.class);
        String sqlWhere = " where 1 = 1 and (t.accounttype is null or t.accounttype != 1)";
        // 分权查询
        DetachUtil detachUtil = new DetachUtil(user);
        String parentCompanyIds = detachUtil.getJclRoleLevels();
        if (detachUtil.isDETACH()) {
            sqlWhere += " and t.subcompanyid1 in(" + parentCompanyIds + ")";
        }

        if(StringUtils.isNotBlank(ids)){
            sqlWhere += " and t.id in(" + ids + ")";
        }

        table.setSqlwhere(sqlWhere);
        List<WeaTableColumn> weaTableColumnList = new ArrayList<>();
        List<String> fields = new ArrayList<>();
        HrmResourceServiceImpl hrmResourceService = ServiceUtil.getService(HrmResourceServiceImpl.class,user);
        List<SearchConditionGroup> allConditions = hrmResourceService.getAllConditions();

        List<String> columnList;

        // 查询当前台账定制列
        SearchTemplatePO usedCustomTemplate = MapperProxyFactory.getProxy(HrmResourceMapper.class).getUsedCustomTemplateByUser(user.getUID());
        if (null == usedCustomTemplate) {
            // 默认列定制
            String selectKeys = "-1_hrm_lastname,-1_hrm_departmentid,-1_hrm_jobtitle,-1_hrm_mobile,-1_hrm_telephone,-1_hrm_managerid";
            columnList = Arrays.asList(selectKeys.split(","));
        } else {
            columnList = hrmResourceService.getSelectKeys(usedCustomTemplate);
        }



        BigDecimal decimal = new BigDecimal(100 / columnList.size());
        for (SearchConditionGroup allCondition : allConditions) {
            List<SearchConditionItem> items = allCondition.getItems();
            for (SearchConditionItem item : items) {
                String columnName = item.getDomkey()[0];
                fields.add(hrmResourceService.buildTableSql(columnName) + " as " + hrmResourceService.buildTableSql(columnName).replace(".", "_"));

                String scopeId = columnName.split("_")[0];
                String fieldName = columnName.substring(columnName.lastIndexOf("_") + 1);
                WeaTableColumn weaTableColumn = new WeaTableColumn();
                weaTableColumn.setText(MapperProxyFactory.getProxy(HrmResourceMapper.class).queryLabelName(fieldName, scopeId, user.getLanguage()));
                weaTableColumn.setColumn(hrmResourceService.buildTableSql(columnName).replace(".", "_"));
                weaTableColumn.setDisplay(columnList.contains(columnName) ? WeaBoolAttr.TRUE : WeaBoolAttr.FALSE);
                weaTableColumn.setTransmethod("com.engine.organization.transmethod.HrmResourceTransMethod.getFieldTrueValue");
                weaTableColumn.setOtherpara(columnName);
                weaTableColumn.setWidth(decimal.setScale(2, RoundingMode.HALF_UP).doubleValue() + "%");
                if (weaTableColumn.getDisplay().getBoolVal()) {
                    weaTableColumnList.add(weaTableColumn);
                    headerList.add(weaTableColumn.getColumn());
                    headerNameList.add(weaTableColumn.getText());
                }
            }
        }
        // 增加id字段,跳转人员卡片
        WeaTableColumn weaTableColumn = new WeaTableColumn();
        weaTableColumn.setColumn("id");
        weaTableColumn.setDisplay(WeaBoolAttr.FALSE);
        weaTableColumnList.add(weaTableColumn);
        fields.add("t.id");

        // 增加分部字段
        //WeaTableColumn weaTableColumn1 = new WeaTableColumn();
        //weaTableColumn1.setText("分部");
        //weaTableColumn1.setColumn("subcompanyid1");
        //weaTableColumn1.setDisplay(WeaBoolAttr.TRUE);
        //weaTableColumn1.setTransmethod("com.engine.organization.transmethod.HrmResourceTransMethod.getCompanyName");
        //fields.add("t.subcompanyid1");
        //headerList.add(0, weaTableColumn1.getColumn());
        //headerNameList.add(0, weaTableColumn1.getText());
        //weaTableColumnList.add(0, weaTableColumn1);


        table.setBackfields(StringUtils.join(fields, ","));
        table.setColumns(weaTableColumnList);
        WeaResultMsg result = new WeaResultMsg(false);
        result.putAll(table.makeDataResult());
        result.success();
        Map<String, Object> resultMap = result.getResultMap();
        String dataKey = Util.null2String(resultMap.get("datas"));

        String getcounts = new Service_DevTable().getcounts(request, response, dataKey);
        JSONObject jsonObject = JSON.parseObject(getcounts);
        String count = jsonObject.getString("count");

        String datas = new Service_DevTable().datas(request, response, dataKey, count, "[]", "", "", "1", "");
        jsonObject = JSON.parseObject(datas);
        List<Map<String, Object>> datas1 = (List<Map<String, Object>>) jsonObject.get("datas");

        List<List<Object>> rows = new LinkedList<>();
        for (Map<String, Object> map : datas1) {
            List<Object> row = new LinkedList<>();
            for (String s : headerList) {
                JSONObject o = (JSONObject) map;
                String value = o.getString(s + "span");
                row.add(Util.formatMultiLangForExpCustomLabel(value, String.valueOf(user.getLanguage())));
            }
            rows.add(row);
        }
        List<List<Object>> excelSheetData = new ArrayList<>();

        excelSheetData.add(headerNameList);

        excelSheetData.addAll(rows);
        String sheetName = HrmI18nUtil.getI18nLabel(85368, "人员档案数据");
        return ExcelUtil.genWorkbookV2(excelSheetData, sheetName);
    }

    @Override
    public XSSFWorkbook departmentExport() {
        SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
        DepartmentComInfo departmentComInfo = new DepartmentComInfo();
        String orderSql = PageInfoSortUtil.getSortSql("", " showorder ");
        List<DepartmentPO> allList = getDepartmentMapper().listAll(orderSql);
        new DetachUtil(user).filterDepartmentList(allList);
        List<DepartmentListDTO> dtoList = allList.stream().map(e ->
                DepartmentListDTO
                        .builder()
                        .id(e.getId())
                        .departmentMark(e.getDepartmentMark())
                        .departmentName(e.getDepartmentName())
                        .departmentCode(e.getDepartmentCode())
                        .subCompanyId1(e.getSubCompanyId1())
                        .supDepId(e.getSupDepId())
                        .subCompanyName((null == e.getSubCompanyId1() || 0 == e.getSubCompanyId1()) ? "" : subCompanyComInfo.getSubCompanyname(Util.null2String(e.getSubCompanyId1())))
                        .supDepName((null == e.getSupDepId() || 0 == e.getSupDepId()) ? "" : departmentComInfo.getDepartmentname(Util.null2String(e.getSupDepId())))
                        .bmfzr(DepartmentBO.getEmployeeNameById(e.getId()))
                        .canceled(null == e.getCanceled() ? 0 : e.getCanceled())
                        .build()).collect(Collectors.toList());

        int language = user.getLanguage();
        String languageStr = String.valueOf(language);
        // 1.工作簿名称
        String sheetName = HrmI18nUtil.getI18nLabel(85368, language, "部门档案数据");
        // 2.表头(后面动态获取)
        List<List<Object>> excelSheetData = new ArrayList<>();

        String[] header = {
                HrmI18nUtil.getI18nLabel(547598, language, "部门名称"),
                HrmI18nUtil.getI18nLabel(547118, language, "编号"),
                HrmI18nUtil.getI18nLabel(547599, language, "部门简称"),
                HrmI18nUtil.getI18nLabel(547128, language, "所属分部"),
                HrmI18nUtil.getI18nLabel(547189, language, "上级部门"),
                HrmI18nUtil.getI18nLabel(547190, language, "部门负责人"),
                HrmI18nUtil.getI18nLabel(547607, language, "启用状态")
        };
        excelSheetData.add(Arrays.asList(header));

        //数据
        List<List<Object>> rows = new LinkedList<>();
        for (DepartmentListDTO vo : dtoList) {
            List<Object> row = new LinkedList<>();
            row.add(Util.formatMultiLang(vo.getDepartmentName(), languageStr));
            row.add(Util.formatMultiLang(vo.getDepartmentCode(), languageStr));
            row.add(Util.formatMultiLang(vo.getDepartmentMark(), languageStr));
            row.add(Util.formatMultiLang(vo.getSubCompanyName(), languageStr));
            row.add(Util.formatMultiLang(vo.getSupDepName(), languageStr));
            row.add(Util.formatMultiLang(vo.getBmfzr(), languageStr));
            row.add(vo.getCanceled() == 0 ? SystemEnv.getHtmlLabelName(547186, language) : SystemEnv.getHtmlLabelName(547608,user.getLanguage()));
            rows.add(row);
        }
        excelSheetData.addAll(rows);
        return ExcelUtil.genWorkbookV2(excelSheetData, sheetName);
    }

    @Override
    public XSSFWorkbook staffExport(String planId) {
        SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
        DepartmentComInfo departmentComInfo = new DepartmentComInfo();
        List<Integer> collect = Arrays.stream(planId.split(","))
                .map(String::trim)
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        List<StaffPO> staffPOS = getStaffMapper().selectByPlanIds(collect);
        int language = user.getLanguage();
        String languageStr = String.valueOf(language);

        List<StaffTableVO> voList = staffPOS.stream().map(e ->
                StaffTableVO.builder()
                        .planId(getStaffPlanMapper().getStaffPlanByID(e.getPlanId()).getPlanName())
                        .controlDimension(StaffPlanTransMethod.getControlDimension(Util.null2String(e.getControlPolicy()),languageStr))
                        .compId(null == e.getCompId() ? "" : subCompanyComInfo.getSubCompanyname(Util.null2String(e.getCompId())))
                        .deptId(null == e.getDeptId() ? "/" : departmentComInfo.getDepartmentname(Util.null2String(e.getDeptId())))
                        .jobId(JobTransMethod.getSpanById(Util.null2String(e.getJobId())))
                        .staffNum(e.getStaffNum())
                        .permanentNum(e.getPermanentNum())
                        .freezeNum(e.getFreezeNum())
                        .lackStatus(StaffTransMethod.getLackSpan(Util.null2String(e.getLackStatus()),languageStr))
                        .build()
                ).collect(Collectors.toList());


        // 1.工作簿名称
        String sheetName = HrmI18nUtil.getI18nLabel(547733, language, "编制信息档案");
        // 2.表头(后面动态获取)
        List<List<Object>> excelSheetData = new ArrayList<>();

        String[] header = {
                HrmI18nUtil.getI18nLabel(547344, language, "方案"),
                HrmI18nUtil.getI18nLabel(547293, language, "维度"),
                HrmI18nUtil.getI18nLabel(547332, language, "分部"),
                HrmI18nUtil.getI18nLabel(547331, language, "部门"),
                HrmI18nUtil.getI18nLabel(547333, language, "岗位"),
                HrmI18nUtil.getI18nLabel(547345, language, "编制数"),
                HrmI18nUtil.getI18nLabel(547346, language, "在编数"),
                HrmI18nUtil.getI18nLabel(547347, language, "冻结数"),
                HrmI18nUtil.getI18nLabel(547348, language, "缺编状态")
        };
        excelSheetData.add(Arrays.asList(header));

        //数据
        List<List<Object>> rows = new LinkedList<>();
        for (StaffTableVO vo : voList) {
            List<Object> row = new LinkedList<>();
            row.add(Util.formatMultiLang(vo.getPlanId(), languageStr));
            row.add(vo.getControlDimension());
            row.add(Util.formatMultiLang(vo.getCompId(), languageStr));
            row.add(Util.formatMultiLang(vo.getDeptId(), languageStr));
            row.add(Util.formatMultiLang(vo.getJobId(), languageStr));
            row.add(vo.getStaffNum());
            row.add(vo.getPermanentNum());
            row.add(vo.getFreezeNum());
            row.add(vo.getLackStatus());
            rows.add(row);
        }
        excelSheetData.addAll(rows);
        return ExcelUtil.genWorkbookV2(excelSheetData, sheetName);
    }


}
