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.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.mapper.comp.CompMapper;
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.service.ExportCommonService;
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 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);
    }


    @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.status < 4 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 = new HrmResourceServiceImpl();
        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));
                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() {
        String orderSql = PageInfoSortUtil.getSortSql("", " showorder ");
        List<DepartmentPO> allList = getDepartmentMapper().listAll(orderSql);
        new DetachUtil(user).filterDepartmentList(allList);
        Map<Integer, DepartmentPO> poMaps = allList.stream().collect(Collectors.toMap(DepartmentPO::getId, item -> item));
        List<DepartmentListDTO> dtoList = allList.stream().map(e ->
                DepartmentListDTO
                        .builder()
                        .id(e.getId())
                        .departmentMark(e.getDepartmentMark())
                        .departmentName(e.getDepartmentName())
                        .departmentCode(e.getDepartmentCode())
                        .subCompanyName(0 == e.getSubCompanyId1() ? "" : MapperProxyFactory.getProxy(CompMapper.class).listById(e.getSubCompanyId1()).getSubCompanyName())
                        .supDepName(null == poMaps.get(e.getSupDepId()) ? "" : poMaps.get(e.getSupDepId()).getDepartmentName())
                        .bmfzr(DepartmentBO.getEmployeeNameById(e.getId()))
                        .canceled(null == e.getCanceled() ? 0 : e.getCanceled())
                        .build()).collect(Collectors.toList());

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

        String[] header = {
                HrmI18nUtil.getI18nLabel( -93270, "部门名称"),
                HrmI18nUtil.getI18nLabel( -93272, "编号"),
                HrmI18nUtil.getI18nLabel( -93274, "部门简称"),
                HrmI18nUtil.getI18nLabel( -93275, "所属分部"),
                HrmI18nUtil.getI18nLabel( -93278, "上级部门"),
                HrmI18nUtil.getI18nLabel( -93279, "部门负责人"),
                HrmI18nUtil.getI18nLabel( -93280, "启用状态")
        };
        excelSheetData.add(Arrays.asList(header));

        //数据
        List<List<Object>> rows = new LinkedList<>();
        for (DepartmentListDTO vo : dtoList) {
            List<Object> row = new LinkedList<>();
            row.add(vo.getDepartmentName());
            row.add(vo.getDepartmentCode());
            row.add(vo.getDepartmentMark());
            row.add(vo.getSubCompanyName());
            row.add(vo.getSupDepName());
            row.add(vo.getBmfzr());
            row.add(vo.getCanceled() == 0 ? "启用" : "未启用");
            rows.add(row);
        }
        excelSheetData.addAll(rows);
        return ExcelUtil.genWorkbookV2(excelSheetData, sheetName);
    }


}
