package com.engine.htsc.contacts.service;


import com.engine.core.impl.Service;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;

import java.text.SimpleDateFormat;
import java.util.*;

public class ContactsService extends Service {

    /**
     * 根据userid获取常用联系人的id
     * @param userid
     * @return
     */
    public List<String> getTopContactsIdsByUserid(String userid){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        List<String> contactList = new ArrayList<>();

        try{
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH,-6);
            String beginDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());

            //内审签字意见类型为a
            Map<String,Integer> contactsMap = new HashMap<>();
            String sql = "select receivedpersonids from workflow_requestlog where operator = '"+userid+"' and operatedate >= '"+beginDate+"' and logtype = 'a'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                String receivedIds = Util.null2String(rs.getString("receivedpersonids"));
                for(String receivedId:receivedIds.split(",")){
                    if(StringUtils.isNotBlank(receivedId)){
                        Integer count = contactsMap.get(receivedId);
                        if(count!=null){
                            contactsMap.put(receivedId,++count);
                        }else{
                            contactsMap.put(receivedId,1);
                        }
                    }
                }
            }

            //降序添加
            Set<String> contactSet = new LinkedHashSet<>();
            List<Map.Entry<String,Integer>> sortList = sortByValue(contactsMap);
            if(sortList.size()>0){
                for(int i=0;i<sortList.size()&&i<5;i++){
                    sql = "select status,seclevel from hrmresource where id = '"+sortList.get(i).getKey()+"'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    if(rs.next()){
                        String status = Util.null2String(rs.getString("status"));
                        String seclevel = Util.null2String(rs.getString("seclevel"));
                        if("1".equals(status)&&StringUtils.isNotBlank(seclevel)&&Integer.parseInt(seclevel)<50){
                            contactSet.add(sortList.get(i).getKey());
                        }
                    }
                }
            }

            //内审常用人不足5人从最近联系人补充
            if(contactSet.size()<5){
                sql = "select t1.selectid from hrmresourceselectrecord t1,hrmresource t2 where t2.id = t1.selectid and t2.seclevel < 50 and t2.status = '1' " +
                        "and t1.resourceid = '"+userid+"' and t2.departmentid = (select departmentid from hrmresource where id = '"+userid+"') order by t1.id desc";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                while(rs.next()){
                    String selectid = Util.null2String(rs.getString("selectid"));
                    contactSet.add(selectid);
                    if(contactSet.size()==5){
                        break;
                    }
                }
            }
            contactList.addAll(contactSet);

        }catch (Exception e){
            e.printStackTrace();
        }
        return contactList;
    }

    /**
     * 按照value的值倒序排序
     * @param map
     * @return
     */
    private static List<Map.Entry<String,Integer>> sortByValue(Map<String, Integer> map){
        List<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
        Collections.sort(list,new Comparator<Map.Entry<String,Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        return list;
    }

    /**
     * 获得常用联系人
     * @param userid
     * @return
     */
    public Map<String,Object> getTopContacts(String userid){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        Map<String,Object> resultMap = new HashMap<>();

        try{
            ResourceComInfo resourceComInfo = new ResourceComInfo();

            String cylxr = "";
            String sql = "select cylxr from uf_hqbmfzrcylxr where bmfzr = '"+userid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                cylxr = Util.null2String(rs.getString("cylxr"));
            }

            List<String> contactsList;
            if(StringUtils.isNotBlank(cylxr)){
                contactsList = Arrays.asList(cylxr.split(","));
            }else{
                contactsList = getTopContactsIdsByUserid(userid);
            }

            List<Map<String,String>> contactsMapList = new ArrayList<>();
            for(String id:contactsList){
                if(StringUtils.isNotEmpty(id)){
                    Map<String,String> userMap = new HashMap<>();
                    userMap.put("id",id);
                    userMap.put("name",resourceComInfo.getLastname(id));
                    contactsMapList.add(userMap);
                }
            }
            resultMap.put("contacts",contactsMapList);
        }catch (Exception e){
            e.printStackTrace();
        }

        return resultMap;
    }

    /**
     * 判断自由节点是否满足查询条件
     * 以后可能会拓展规则
     * @param nodeid
     * @return
     */
    public Map<String,Object> checkoutFreeNode(String nodeid){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        Map<String,Object> resultMap = new HashMap<>();

        boolean flag = false;
        String sql = "select nodename from workflow_freenode where id = '"+nodeid+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        if(rs.next()){
            String nodename = Util.null2String(rs.getString("nodename"));
            if("会签部门负责人".equals(nodename)){
                flag = true;
            }
        }
        resultMap.put("result",flag);

        return resultMap;
    }


}
