package com.kingdee.eas.custom.expandassess.app.task;

import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.custom.expandassess.*;
import com.kingdee.eas.custom.expandassess.app.ExpandStatusEunm;
import com.kingdee.eas.custom.notify.NotifyTodoFactory;
import com.kingdee.eas.custom.notify.SendContextInfo;
import com.kingdee.eas.custom.performancenew.*;
import com.kingdee.eas.custom.utils.PropertiesUtil;
import com.kingdee.eas.hr.ats.AtsUtil;
import com.tool.simplecode.Compare;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.ejb.*;
import java.net.URLEncoder;
import java.rmi.RemoteException;

import com.kingdee.bos.*;
import com.kingdee.bos.util.BOSObjectType;
import com.kingdee.bos.metadata.IMetaDataPK;
import com.kingdee.bos.metadata.rule.RuleExecutor;
import com.kingdee.bos.metadata.MetaDataPK;
//import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.framework.ejb.AbstractEntityControllerBean;
import com.kingdee.bos.framework.ejb.AbstractBizControllerBean;
//import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.IObjectCollection;
import com.kingdee.bos.service.ServiceContext;
import com.kingdee.bos.service.IServiceContext;

import com.kingdee.eas.common.EASBizException;

import java.lang.String;
import java.sql.Timestamp;
import java.util.*;

public class ExpandassessFacadeControllerBean extends AbstractExpandassessFacadeControllerBean {
    private static Logger logger =
            Logger.getLogger("com.kingdee.eas.custom.expandassess.app.task.ExpandassessFacadeControllerBean");
    public String linkTemplate = "%s/dynamic.do?uipk=%s&inFrame=true&billId=%s";

    @Override
    protected String _warnPrincipal(Context ctx, String periodId) throws BOSException, EASBizException {
        //获取shr域名
        String shrAddress = PropertiesUtil.getConfigValue("shrAddress");
        //计算正态分布得分Uipk
        String expandassessUipk = PropertiesUtil.getConfigValue("expandassessUipk");
        StringBuilder resultMsg = new StringBuilder();
        int success = 0;
        int fail = 0;
        IExpandAssessEntry iExpandAssessEntry = ExpandAssessEntryFactory.getLocalInstance(ctx);
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        filterItems.add(new FilterItemInfo("asseStatus", 1, CompareType.NOTEQUALS));
        filterItems.add(new FilterItemInfo("asseStatus", 4, CompareType.NOTEQUALS));
        if (!StringUtils.isEmpty(periodId)) {
            filterItems.add(new FilterItemInfo("parent.id", periodId));
        }
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("principal.oaUserName");
        sic.add("principal.name");
        sic.add("principal.id");
        sic.add("adminOrg.number");
        sic.add("adminOrg.name");
        sic.add("parent.year");
        sic.add("parent.quarter");
        sic.add("asseStatus");
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        ExpandAssessEntryCollection expandAssessEntryCollection = iExpandAssessEntry.getExpandAssessEntryCollection(entityViewInfo);
        Set<String> set = new HashSet<>();
        List<ExpandAssessEntryInfo> list = new ArrayList();
        //考核人发送
        for (int i = 0; i < expandAssessEntryCollection.size(); i++) {
            ExpandAssessEntryInfo entry = expandAssessEntryCollection.get(i);
            if (entry.getAsseStatus() == ExpandStatusEunm.START) {
                try {
                    ExpandAssessInfo parent = entry.getParent();
                    sendPress(ctx, periodId, entry, parent, shrAddress, expandassessUipk, true);
                    success++;
                } catch (Exception e) {
                    e.printStackTrace();
                    fail++;
                }
            }
            String principal = entry.getPrincipal().getId().toString();
            String adminOrgId = entry.getAdminOrg().getId().toString();
            if (!set.contains(principal + adminOrgId)) {
                set.add(principal + adminOrgId);
                list.add(entry);
            }
        }
        //负责人发送
        for (ExpandAssessEntryInfo entryInfo : list) {
            try {
                if (entryInfo.getAsseStatus() == ExpandStatusEunm.ASSESUBMINT) {
                    ExpandAssessInfo parent = entryInfo.getParent();
                    sendPress(ctx, periodId, entryInfo, parent, shrAddress, expandassessUipk, false);
                    success++;
                }
            } catch (Exception e) {
                e.printStackTrace();
                fail++;
            }
        }
        resultMsg.append("待办任务总数").append(expandAssessEntryCollection.size()).append("条，");
        resultMsg.append("催办成功").append(success).append("条，");
        resultMsg.append("失败").append(fail).append("条。");
        return resultMsg.toString();
    }

    private void sendPress(Context ctx, String periodId, ExpandAssessEntryInfo entryInfo, ExpandAssessInfo parent, String shrAddress, String expandassessUipk, Boolean is) throws BOSException, EASBizException {
        //周期年度季度
        int year = parent.getYear();
        int quarter = parent.getQuarter();
        String msg = year + "年" + quarter + "季度";
        PersonInfo personInfo = null;
        if (is) {
            personInfo = entryInfo.getAssessor();
        } else {
            personInfo = entryInfo.getPrincipal();

        }
        String scorerName = personInfo.getName();
        //oa用户名
        String oaUserName = personInfo.getString("oaUserName");
        if (StringUtils.isEmpty(oaUserName)) {
            throw new BOSException("周期[" + msg + "]，负责人[" + scorerName + "]的oa用户名为空!");
        }
        //发送待办
        SendContextInfo context = new SendContextInfo();
        context.setAppName("shr");
        context.setModelName("shr_正态分布模块");
        context.setModelId(UUID.randomUUID().toString());
        StringBuilder subject = new StringBuilder();
        subject.append("请您尽快提交 周期[" + msg + "]，拓展人员考核的考核人明细表!");
        context.setSubject(subject.toString());
        String periodIdUrlID = URLEncoder.encode(periodId);
        String link = String.format(linkTemplate, shrAddress, expandassessUipk, periodIdUrlID);
        context.setLink(link);
        //context.setType();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("LoginName", oaUserName);
        context.setTargets(jsonObject.toJSONString());
        context.setCreateTime(new Timestamp(new Date().getTime()));
        NotifyTodoFactory.getLocalInstance(ctx).sendTodo(context);
    }
}