package com.engine.organization.service.impl;

import com.engine.common.service.HrmCommonService;
import com.engine.common.service.impl.HrmCommonServiceImpl;
import com.engine.core.impl.Service;
import com.engine.organization.entity.personnelcard.*;
import com.engine.organization.entity.personnelcard.po.CardAccessPO;
import com.engine.organization.entity.personnelcard.po.CardButtonPO;
import com.engine.organization.entity.personnelcard.po.CusTreeFormPO;
import com.engine.organization.exception.OrganizationRunTimeException;
import com.engine.organization.mapper.personnelcard.CardAccessMapper;
import com.engine.organization.mapper.personnelcard.CardButtonMapper;
import com.engine.organization.mapper.personnelcard.PersonnelCardMapper;
import com.engine.organization.service.HrmPersonnelCardService;
import com.engine.organization.util.OrganizationAssert;
import com.engine.organization.util.db.MapperProxyFactory;
import com.engine.portal.biz.constants.ModuleConstants;
import com.engine.portal.biz.nonstandardfunction.SysModuleInfoBiz;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import weaver.blog.BlogShareManager;
import weaver.conn.RecordSet;
import weaver.cowork.CoworkShareManager;
import weaver.crm.CrmShareBase;
import weaver.docs.search.DocSearchComInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.definedfield.HrmFieldManager;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.search.WorkflowRequestUtil;

import java.util.*;

/**
 * @author:dxfeng
 * @createTime: 2022/10/08
 * @version: 1.0
 */
public class HrmPersonnelCardServiceImpl extends Service implements HrmPersonnelCardService {

    private PersonnelCardMapper getPersonnelCardMapper() {
        return MapperProxyFactory.getProxy(PersonnelCardMapper.class);
    }

    private CardButtonMapper getCardButtonMapper() {
        return MapperProxyFactory.getProxy(CardButtonMapper.class);
    }


    @Override
    public Map<String, Object> getPersonnelCard(Long uId) {
        Map<String, Object> resultMap = new HashMap<>();
        UserCard userInfo;
        if (null == uId) {
            uId = (long) user.getUID();
        }
        userInfo = getPersonnelCardMapper().getUserById(uId);
        userInfo.setEcId(uId.toString());

        OrganizationAssert.notNull(uId, "未找到对应数据");
        // 人员基本信息

        // 统计报表
        Statistical statistical = getStatistical(userInfo.getEcId());

        // 获取类型分组信息
        List<CusTreeFormPO> cusTreeForms = getPersonnelCardMapper().getCusTreeForms(0);
        cusTreeForms.removeIf(item -> !hasGroupAccess(item.getId(), userInfo.getEcId()));
        List<FormItem> formItemList = new ArrayList<>();
        try {
            for (CusTreeFormPO cusTreeForm : cusTreeForms) {
                FormItem formItem = getFormItem(cusTreeForm, uId);
                if (CollectionUtils.isEmpty(formItem.getItems())) {
                    continue;
                }

                //TODO 明细表暂不处理
                //List<Map<String, Object>> detailList = ServiceUtil.getService(ExtServiceImpl.class, user).getExtendTables(user, "4", groupPO.getId(), "JCL_ORG_HRMRESOURCEEXT_DT1", uId, 1, false);
                //formItem.setTables(detailList);

                formItemList.add(formItem);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 所有锚点
        List<Anchor> anchorList = new ArrayList<>();
        // 添加字段分组信息
        for (FormItem formItem : formItemList) {
            anchorList.add(Anchor.builder().id(formItem.getId()).title(formItem.getTitle()).build());
        }
        // 添加拓展页面信息
        List<ResourceBaseTab> resourceBaseTabList = getPersonnelCardMapper().getResourceBaseTabList();
        for (ResourceBaseTab resourceBaseTab : resourceBaseTabList) {
            anchorList.add(Anchor.builder().id("tab" + resourceBaseTab.getId()).title(resourceBaseTab.getGroupName()).build());
        }
        resultMap.put("buttons", getButtonList(userInfo.getEcId()));
        resultMap.put("user", userInfo);
        resultMap.put("statistical", statistical);
        resultMap.put("formItems", formItemList);
        resultMap.put("anchorList", anchorList);
        resultMap.put("iframeList", getIframeList());
        return resultMap;
    }

    @Override
    public List<Iframe> getIframeList() {
        List<Iframe> iframeList = new ArrayList<>();
        List<ResourceBaseTab> resourceBaseTabList = getPersonnelCardMapper().getResourceBaseTabList();
        for (ResourceBaseTab resourceBaseTab : resourceBaseTabList) {
            iframeList.add(Iframe.builder().id("tab" + resourceBaseTab.getId()).title(resourceBaseTab.getGroupName()).url(resourceBaseTab.getLinkUrl()).build());
        }
        return iframeList;
    }


    /**
     * 获取报表统计数据
     *
     * @param ecResourceId
     * @return
     */
    private Statistical getStatistical(String ecResourceId) {
        try {
            // 获取Ec用户ID
            Statistical statistical = new Statistical();
            if (SysModuleInfoBiz.checkModuleStatus(ModuleConstants.Workflow)) {
                statistical.setWorkflowCount(new WorkflowRequestUtil().getRequestCount(user, ecResourceId));
            } else {
                statistical.setWorkflowCount(0);
            }
            if (SysModuleInfoBiz.checkModuleStatus(ModuleConstants.Doc)) {
                Object[] docCount4Hrm = new DocSearchComInfo().getDocCount4Hrm(ecResourceId, user);
                statistical.setDocCount(null == docCount4Hrm[1] ? 0 : Integer.parseInt(Util.null2String(docCount4Hrm[1])));
            } else {
                statistical.setDocCount(0);
            }
            if (SysModuleInfoBiz.checkModuleStatus(ModuleConstants.Crm)) {
                String[] crmCount4Hrm = new CrmShareBase().getCrmCount4Hrm(ecResourceId, ecResourceId);
                statistical.setCusCount(null == crmCount4Hrm[1] ? 0 : Integer.parseInt(Util.null2String(crmCount4Hrm[1])));
            } else {
                statistical.setCusCount(0);
            }
            if (SysModuleInfoBiz.checkModuleStatus(ModuleConstants.Cowork)) {
                String[] coworkCount4Hrm = new CoworkShareManager().getCoworkCount4Hrm(ecResourceId, ecResourceId);
                statistical.setCollaborationCount(null == coworkCount4Hrm[1] ? 0 : Integer.parseInt(Util.null2String(coworkCount4Hrm[1])));
            } else {
                statistical.setCollaborationCount(0);
            }
            if (SysModuleInfoBiz.checkModuleStatus(ModuleConstants.Blog)) {
                String[] blogCount4Hrm = new BlogShareManager().getBlogCount4Hrm(ecResourceId);
                statistical.setWeiboCount(null == blogCount4Hrm[1] ? 0 : Integer.parseInt(Util.null2String(blogCount4Hrm[1])));
            } else {
                statistical.setWeiboCount(0);
            }
            return statistical;
        } catch (Exception e) {
            new BaseBean().writeLog(e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取人员主表信息、拓展表信息
     *
     * @param cusTreeFormPO
     * @param uId
     * @return
     * @throws Exception
     */
    private FormItem getFormItem(CusTreeFormPO cusTreeFormPO, Long uId) throws Exception {
        FormItem formItem = new FormItem();
        RecordSet recordSet = new RecordSet();
        formItem.setId(cusTreeFormPO.getId().toString());
        formItem.setTitle(cusTreeFormPO.getFormLabel());
        List<Item> itemList = new ArrayList<>();
        HrmFieldManager hfm = new HrmFieldManager("HrmCustomFieldByInfoType", cusTreeFormPO.getId());
        hfm.getHrmData(uId.intValue());
        hfm.getCustomFields();
        while (hfm.next()) {
            String fieldName = hfm.getFieldname();
            JSONObject hrmFieldConf = hfm.getHrmFieldConf(fieldName);
            String fieldLabel = Util.toScreen(SystemEnv.getHtmlLabelName(hrmFieldConf.getInt("fieldlabel"), user.getLanguage()), user.getLanguage());
            if ("resourceimageid".equals(fieldName) || "messagerurl".equals(fieldName) || "职等职级".equals(fieldLabel)) {
                continue;
            }
            String hrmData = "";
            if (hfm.isBaseField(fieldName)) {
                if ("jobactivity".equals(fieldName)) {
                    recordSet.execute("SELECT h1.ID AS jobactivity FROM HRMJOBTITLES h INNER JOIN HRMJOBACTIVITIES h1 ON h.JOBACTIVITYID = h1.ID WHERE h.ID = '" + hfm.getHrmData("jobtitle") + "'");
                    if (recordSet.next()) {
                        hrmData = recordSet.getString(fieldName);
                        // 职务浏览按钮：282
                        hrmFieldConf.put("type", 282);
                    }
                } else if ("jobGroupId".equals(fieldName)) {
                    recordSet.execute("SELECT h2.ID AS jobGroupId FROM HRMJOBTITLES h INNER JOIN HRMJOBACTIVITIES h1 ON h.JOBACTIVITYID = h1.ID INNER JOIN HRMJOBGROUPS h2 ON h1.JOBGROUPID = h2.ID WHERE h.ID = '" + hfm.getHrmData("jobtitle") + "'");
                    if (recordSet.next()) {
                        hrmData = recordSet.getString(fieldName);
                    }
                } else {
                    hrmData = hfm.getHrmData(fieldName);
                }
            } else {
                recordSet.execute("select " + fieldName + " from cus_fielddata where SCOPE = '" + cusTreeFormPO.getScope() + "' and SCOPEID =" + cusTreeFormPO.getId() + " and id = " + uId);
                if (recordSet.next()) {
                    hrmData = recordSet.getString(fieldName);
                }
            }
            String fieldValue = hfm.getFieldvalue(null, user, null, hrmFieldConf.getString("dmlurl"), hrmFieldConf.getInt("id"), hrmFieldConf.getInt("fieldhtmltype"), hrmFieldConf.getInt("type"), hrmData, 0, fieldName);
            itemList.add(Item.builder().fieldId(fieldLabel).fieldValue(fieldValue).build());
        }
        formItem.setItems(itemList);
        return formItem;
    }

    /**
     * 判断当前人员、是否有查看当前数据、当前模块的权限
     *
     * @param typeId 人员卡片分组ID
     * @param userId 当前卡片人员EcId
     * @return
     */
    public boolean hasGroupAccess(Integer typeId, String userId) {
        // 人员信息有误,返回false
        OrganizationAssert.notBlank(userId, "未获取到对应人员");

        boolean hasAccess = false;
        CardAccessPO cardAccessPO = MapperProxyFactory.getProxy(CardAccessMapper.class).selectById(typeId);
        if (null == cardAccessPO || 0 == cardAccessPO.getStatus()) {
            // 未配置相应数据、或者未启用返回false
            return false;
        }

        // 系统管理员、查看本人卡片,或者所有人有权限直接返回true
        if (user.isAdmin() || userId.equals(String.valueOf(user.getUID())) || 1 == cardAccessPO.getAllPeople()) {
            return true;
        }

        try {
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            // 上级
            if ("1".equals(Util.null2String(cardAccessPO.getSuperior()))) {
                String managerID = resourceComInfo.getManagerID(userId);
                hasAccess = Arrays.asList(managerID.split(",")).contains(Util.null2String(user.getUID()));
            }

            // 所有上级
            if (!hasAccess && "1".equals(Util.null2String(cardAccessPO.getAllSuperior()))) {
                String managersIDs = resourceComInfo.getManagersIDs(userId);
                hasAccess = Arrays.asList(managersIDs.split(",")).contains(Util.null2String(user.getUID()));
            }
        } catch (Exception e) {
            new BaseBean().writeLog(e);
            throw new OrganizationRunTimeException("人员卡片权限");
        }
        // 角色判断
        if (!hasAccess && StringUtils.isNotBlank(cardAccessPO.getCustom())) {
            HrmCommonService hrmCommonService = new HrmCommonServiceImpl();
            List<String> roleIds = new ArrayList<>(Arrays.asList(hrmCommonService.getRoleIds(user.getUID()).split(",")));
            List<String> accessRoleIds = new ArrayList<>(Arrays.asList(cardAccessPO.getCustom().split(",")));
            roleIds.retainAll(accessRoleIds);
            hasAccess = CollectionUtils.isNotEmpty(roleIds);

        }
        return hasAccess;
    }


    /**
     * 获取当前人员有权限的按钮，系统管理员展示所有，个人卡片展示系统默认按钮、其余按钮依照配置角色展示
     *
     * @param ecResourceId
     * @return
     */
    private List<CardButtonPO> getButtonList(String ecResourceId) {
        boolean isMySelf = ecResourceId.equals(Util.null2String(user.getUID()));
        boolean isAdmin = user.isAdmin();
        List<CardButtonPO> cardButtonPOS = getCardButtonMapper().listEnableButton();
        List<CardButtonPO> buttonList = new ArrayList<>();
        HrmCommonService hrmCommonService = new HrmCommonServiceImpl();
        List<String> roleIds = new ArrayList<>(Arrays.asList(hrmCommonService.getRoleIds(user.getUID()).split(",")));


        for (CardButtonPO cardButton : cardButtonPOS) {
            List<String> accessRoleIds = new ArrayList<>(Arrays.asList(Util.null2String(cardButton.getRoles()).split(",")));
            roleIds.retainAll(accessRoleIds);
            if (isAdmin || (isMySelf && "0".equals(cardButton.getSysDefault())) || CollectionUtils.isNotEmpty(roleIds)) {
                buttonList.add(CardButtonPO.builder().name(cardButton.getName()).url(cardButton.getUrl()).sysDefault(cardButton.getSysDefault()).build());
            }
        }
        return buttonList;
    }

}
