package com.kingdee.eas.custom.projectbonus.task;

import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.notify.NotifyTodoFactory;
import com.kingdee.eas.custom.notify.SendContextInfo;
import com.kingdee.eas.custom.projectbonus.*;
import com.kingdee.eas.custom.projectbonus.bizEnum.BusDepProjectStateEnum;
import com.kingdee.eas.custom.utils.PropertiesUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.*;

public class ProjectbonusFacadeControllerBean extends AbstractProjectbonusFacadeControllerBean {
    private static Logger logger = Logger.getLogger(ProjectbonusFacadeControllerBean.class);
    private String linkTemplate = "%s/dynamic.do?uipk=%s&inFrame=true&parentId=%s";


    /**
     * 提醒负责人提交分配明细数据
     *
     * @param ctx
     * @param bonusCycleId 奖金周期id
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected String _noticePrincipal(Context ctx, String bonusCycleId)
            throws BOSException, EASBizException {
        //获取shr域名
        String shrAddress = PropertiesUtil.getConfigValue("shrAddress");
        //负责人事业部uipk
        String principalBusdepUipk = PropertiesUtil.getConfigValue("principalBusdepUipk");
        StringBuilder resultMsg = new StringBuilder();
        int success = 0;
        int fail = 0;
        IBonusCycleBusDepProject iBonusCycleBusDepProject =
                BonusCycleBusDepProjectFactory.getLocalInstance(ctx);
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        filterItems.add(new FilterItemInfo("state", 1));
        filterItems.add(new FilterItemInfo("state", 4));
        filterInfo.setMaskString("(#0 or #1) and #2 and (#3 or #4)");
        if (!StringUtils.isEmpty(bonusCycleId)) {
            filterItems.add(new FilterItemInfo("parent.id", bonusCycleId));
            filterInfo.setMaskString("(#0 or #1) and #2 ");
        } else {
            filterInfo.setMaskString("#0 or #1");
        }
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("parent.cycleName");
        sic.add("principal.oaUserName");
        sic.add("principal.name");
        sic.add("project.name");
        sic.add("busDep.name");
        sic.add("state");
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        BonusCycleBusDepProjectCollection busDepProjectCols =
                iBonusCycleBusDepProject.getBonusCycleBusDepProjectCollection(entityViewInfo);
        for (int i = 0; i < busDepProjectCols.size(); i++) {
            try {
                BonusCycleBusDepProjectInfo depProjectInfo = busDepProjectCols.get(i);
                BusDepProjectStateEnum state = depProjectInfo.getState();
                BonusCycleInfo bonusCycleInfo = depProjectInfo.getParent();
                //周期名称
                String cycleName = bonusCycleInfo.getCycleName();
                String busDepMsg = getBusDepMsg(depProjectInfo);
                PersonInfo principal = depProjectInfo.getPrincipal();
                if (principal == null) {
                    throw new BOSException("周期[" + cycleName + "] " + busDepMsg + "的负责人为空!");
                }
                String principalName = principal.getName();
                //oa用户名
                String oaUserName = principal.getString("oaUserName");
                if (StringUtils.isEmpty(oaUserName)) {
                    throw new BOSException("周期[" + cycleName + "] " + busDepMsg + "的负责人[" + principalName + "]的oa用户名为空!");
                }
                //发送待办
                SendContextInfo context = new SendContextInfo();
                context.setAppName("shr");
                context.setModelName("shr_项目经营奖金模块");
                context.setModelId(BOSUuid.create("projectbonus").toString());
                StringBuilder subject = new StringBuilder();
                if (BusDepProjectStateEnum.ENABLE.equals(state)) {
                    subject.append("请您尽快提交 周期[" + cycleName + "] " + busDepMsg + "的奖金分配人员明细!");
                }else if (BusDepProjectStateEnum.SUBMITCALCULATED.equals(state)) {
                    subject.append("请您尽快复核 周期[" + cycleName + "] " + busDepMsg + "的奖金分配人员明细!");
                }
                context.setSubject(subject.toString());
                String bonusCycleIdEncode = URLEncoder.encode(bonusCycleId);
                String link = String.format(linkTemplate, shrAddress, principalBusdepUipk, bonusCycleIdEncode);
                context.setLink(link);
                //context.setType();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("LoginName", oaUserName);
                //[{"LoginName":"liucanyu"},{"LoginName":"liucanyu1"}]
                context.setTargets(jsonObject.toJSONString());
                context.setCreateTime(new Timestamp(new Date().getTime()));
                NotifyTodoFactory.getLocalInstance(ctx).sendTodo(context);
                success++;
            } catch (Exception e) {
                e.printStackTrace();
                fail++;
            }
        }
        resultMsg.append("待办任务总数").append(busDepProjectCols.size()).append("条，");
        resultMsg.append("催办成功").append(success).append("条，");
        resultMsg.append("失败").append(fail).append("条。");
        return resultMsg.toString();
    }

    private String getBusDepMsg(BonusCycleBusDepProjectInfo info) {
        AdminOrgUnitInfo project = info.getProject();
        if (project != null) {
            String projectProject = project.getName();
            return "项目[" + projectProject + "]";
        } else {
            String busdepName = info.getBusDep().getName();
            return "事业部[" + busdepName + "]";
        }
    }
    // public static void main(String[] args) throws javax.xml.rpc.ServiceException {
//        ISysNotifyTodoWebServiceServiceLocator iSysNotifyTodoWebServiceServiceLocator = new ISysNotifyTodoWebServiceServiceLocator();
//        ISysNotifyTodoWebService iSysNotifyTodoWebServicePort = iSysNotifyTodoWebServiceServiceLocator.getISysNotifyTodoWebServicePort();
//        NotifyTodoSendContext notInfo = new NotifyTodoSendContext();
//        notInfo.setAppName("shr");
//        notInfo.setModelName("shr_项目经营奖金模块");
//        notInfo.setModelId(BOSUuid.create("projectbonus").toString());
//        notInfo.setLink("http://10.0.64.221:6888/shr/home.do");
//        notInfo.setType(1);
//        JSONObject jsonObject1 = new JSONObject();
//        jsonObject1.put("LoginName", "liucanyu");
//        JSONObject jsonObject2 = new JSONObject();
//        jsonObject2.put("LoginName", "liucanyu1");
//        JSONArray jsonArray = new JSONArray();
//        jsonArray.add(jsonObject1);
//        jsonArray.add(jsonObject2);
//        StringBuilder subject = new StringBuilder();
//        subject.append("请您尽快提交 周期的奖金分配人员明细!");
//        notInfo.setSubject(subject.toString());
//        notInfo.setTargets(jsonArray.toString());
//        notInfo.setCreateTime(DateTimeUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
//        System.out.println(JSONObject.toJSON(notInfo).toString());
//        //发送待办
//        NotifyTodoAppResult notifyTodoAppResult = iSysNotifyTodoWebServicePort.sendTodo(notInfo);
//        System.out.println(notifyTodoAppResult.getReturnState());
//        System.out.println(notifyTodoAppResult.getMessage());

    //String encode = URLEncoder.encode("+ng+o0EHRTuIAsGjqwaF+7mfTD4=");
    //System.out.println(encode);
    //}
}