package com.kingdee.shr.customer.gtiit.osf;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.bsf.service.app.IHRMsfService;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.customer.gtiit.osf.util.DateUtils;

/**
 * 获取部门的接口
 *
 * @author cb
 */
public class GtiitOrgAdminService implements IHRMsfService {

    private static final Logger logger = LoggerFactory.getLogger(GtiitOrgPositionService.class);

    @Override
    public Object process(Context ctx, Map param) throws EASBizException, BOSException {
    	List<Map<String, String>> dataList=null;
    	
    	try {
    		   // 开始日期
            String startDate = (String) param.get("startDate");
            // 截止日期
            String endDate = (String) param.get("endDate");
            logger.info(">>> GtiitOrgAdminService...入参...startDate = " + startDate + "; endDate = " + endDate);
            String sql="SELECT\r\n" + 
            		"	oa.FID ID,\r\n" + 
            		"	oa.fnumber ORGANIZATION_CODE,\r\n" + 
            		"	oa.FNAME_L1 ORGANIZATION_NAME_EN,\r\n" + 
            		"	oa.FNAME_L2 ORGANIZATION_NAME_CN,\r\n" + 
            		"	oa.FSIMPLENAME ORGANIZATION_SHORT_NAME,\r\n" + 
            		"	p.FNUMBER DEPARTMENT_HEAD_PERSON_NUMBER,\r\n" + 
            		"	p.FNAME_L2 DEPARTMENT_HEAD_NAME,\r\n" + 
            		"	oa.FCREATETIME ERP_CREATION_DATE,\r\n" + 
            		"	oa.FLASTUPDATETIME ERP_LAST_UPDATE_DATE \r\n" + 
            		"   FROM\r\n" + 
            		"	T_ORG_Admin oa\r\n" + 
            		"	LEFT JOIN t_bd_person p ON p.fid = oa.FPRINCIPALID";
            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
                startDate = DateUtils.formatDate(startDate, true);
                endDate = DateUtils.formatDate(endDate, false);
                logger.info(">>> GtiitOrgAdminService...修改后的入参...startDate = " + startDate + "; endDate = " + endDate);
                sql += " where oa.FLASTUPDATETIME >= '" + startDate + "' and oa.FLASTUPDATETIME <= '" + endDate + "'";
            }
            logger.info(">>> GtiitOrgAdminService 的执行 sql = " + sql);
            List<String> fieldList = initMappingField();
            IRowSet rs = DbUtil.executeQuery(ctx, sql.toString());
             dataList = this.getRsListData(fieldList, rs);
            //处理部门负责人及pvc校长
             if(dataList!=null && dataList.size()>0) {
 				processHead(ctx,dataList);

 			}
    	}catch(Exception e) {
    		throw new BOSException(e);
    	}
    	
     
        return dataList;
    }
    

    /**
	 * 赋值部门负责人
	 * @param ctx
	 * @param dataList
	 * @throws BOSException
	 * @throws SQLException
	 */
	private void processHead(Context ctx,List<Map<String, String>> dataList) throws BOSException, SQLException {
		List<String> ids=new ArrayList<>();
		for (int i = 0; i < dataList.size(); i++) {
			ids.add(dataList.get(i).get("ID"));
		}
		
		//部门id集合
		String processStr = processStr(ids);
		
		//部门负责人
		Map<String, String> heads = getHead(ctx,processStr);
		
		//pvc
		Map<String, String> pvcMap = getPvc(ctx,processStr);
		
		for (int i = 0; i < dataList.size(); i++) {
			Map<String, String> data = dataList.get(i);
			data.put("DEPARTMENT_HEAD_PERSON_NUMBER", heads.get(data.get("ORGANIZATION_CODE")+"-number"));
			data.put("DEPARTMENT_HEAD_NAME", heads.get(data.get("ORGANIZATION_CODE")+"-name"));
			data.put("PVC_PERSON_NUMBER", pvcMap.get(data.get("ORGANIZATION_CODE")+"-number"));
			data.put("PVC_NAME", pvcMap.get(data.get("ORGANIZATION_CODE")+"-name"));
		}
		
		
	}
	
	private Map<String,String> getPvc(Context ctx,String processStr) throws BOSException, SQLException{
		Map<String,String> resultMap=new HashMap<>();
		String sql="SELECT\r\n" + 
				"	org.fnumber orgNumber,\r\n" + 
				"	org.Fname_l1 orgName,\r\n" + 
				"	bp.fnumber pNumber,\r\n" + 
				"	bp.Fname_l1 pName\r\n" + 
				"FROM\r\n" + 
				"	T_WFR_WFROLE wf\r\n" + 
				"	LEFT JOIN T_WFR_PERSONROLE wp ON wp.froleid= wf.fid\r\n" + 
				"	LEFT JOIN T_BD_Person bp ON bp.fid= wp.fpsersonid\r\n" + 
				"	LEFT JOIN T_ORG_Admin org ON org.fid= wp.forgid \r\n" + 
				"WHERE\r\n" + 
				"	wf.fnumber= '02' and org.fid in("+processStr+")";
		
		logger.info("GtiitOrgAdminService->getPvc->sql{} ",sql);
       IRowSet rs = DbUtil.executeQuery(ctx, sql.toString());
		
		while(rs.next()) {
			String orgNumber = rs.getString("orgNumber");
			if(StringUtils.isBlank(orgNumber)) {
				continue;
			}
			 
			if(StringUtils.isNotBlank(resultMap.get(orgNumber+"-number"))) {
				resultMap.put(orgNumber+"-number", resultMap.get(orgNumber+"-number")+","+rs.getString("pNumber"));
			}else {
				resultMap.put(orgNumber+"-number", rs.getString("pNumber"));
			}
			
			if(StringUtils.isNotBlank(resultMap.get(orgNumber+"-name"))) {
				resultMap.put(orgNumber+"-name", resultMap.get(orgNumber+"-name")+","+rs.getString("pName"));
			}else {
				resultMap.put(orgNumber+"-name", rs.getString("pName"));
			}
		}
		return resultMap;
		
		
	}
    
	/**
	 * 获取部门负责人
	 * @param numbers
	 * @return
	 * @throws BOSException 
	 * @throws SQLException 
	 */
	private Map<String,String> getHead(Context ctx,String processStr) throws BOSException, SQLException{
		Map<String,String> resultMap=new HashMap<>();
		
		String  sql="SELECT\r\n" + 
				"	a.fid AS oId,\r\n" + 
				"	a.fnumber AS oNumber,\r\n" + 
				"	d.fnumber AS pNumber,\r\n" + 
				"	d.fname_L1 AS pNameL1,\r\n" + 
				"	d.fname_L2 AS pNameL2 \r\n" + 
				"FROM\r\n" + 
				"	T_ORG_Admin a\r\n" + 
				"	LEFT JOIN T_ORG_POSITION b ON a.FResponPositionID= b.fid\r\n" + 
				"	LEFT JOIN (\r\n" + 
				"	SELECT\r\n" + 
				"		ca.fpositionid,\r\n" + 
				"		ca.fpersonid, \r\n" + 
				"		ca.fislatestinaday, \r\n" + 
				"		ca.fadminorgid, \r\n" + 
				"		ca.flastupdatetime \r\n" + 
				"	FROM\r\n" + 
				"		T_HR_EmpOrgRelation ca\r\n" + 
				"		INNER JOIN ( SELECT fpositionid, MAX ( fleffdt ) maxDate FROM T_HR_EmpOrgRelation GROUP BY fpositionid ) cb ON ca.fpositionid= cb.fpositionid \r\n" + 
				"		AND ca.fleffdt= cb.maxDate \r\n" + 
				"	) c ON c.fpositionid= b.fid\r\n" + 
				"	LEFT JOIN T_BD_Person d ON d.fid= c.fpersonid\r\n" + 
				"	LEFT JOIN T_HR_BDEmployeeType e ON e.fid= d.femployeetypeid \r\n" + 
				"WHERE\r\n" + 
				"	a.fid IN ("+processStr+") \r\n" + 
				"	AND b.FIsRespPosition= 1 \r\n" + 
				"	AND e.finservice= 1 \r\n" + 
				"	AND b.fdeletedstatus= 1 \r\n"+
				"	AND c.fislatestinaday=1  \r\n";
		
		logger.info("GtiitOrgAdminService->getHead->sql{} ",sql);
		
		IRowSet rs = DbUtil.executeQuery(ctx, sql.toString());
		
		while(rs.next()) {
			String oNumber = rs.getString("oNumber");
			if(StringUtils.isBlank(oNumber)) {
				continue;
			}
			 
			if(StringUtils.isNotBlank(resultMap.get(oNumber+"-number"))) {
				resultMap.put(oNumber+"-number", resultMap.get(oNumber+"-number")+","+rs.getString("pNumber"));
			}else {
				resultMap.put(oNumber+"-number", rs.getString("pNumber"));
			}
			
			if(StringUtils.isNotBlank(resultMap.get(oNumber+"-name"))) {
				resultMap.put(oNumber+"-name", resultMap.get(oNumber+"-name")+","+rs.getString("pNameL1"));
			}else {
				resultMap.put(oNumber+"-name", rs.getString("pNameL1"));
			}
		}
		return resultMap;
		
	}
	
	/**
	 * 处理字符串
	 * @param numbers
	 * @return
	 */
	private String processStr(List<String> numbers) {
		String result="";
		StringBuilder sb = new StringBuilder();
        for (String s : numbers) {
            sb.append("'").append(s).append("'").append(",");
        }

        if(sb.length()>0){
            sb.deleteCharAt(sb.lastIndexOf(","));
            result=sb.toString();
        }
        return result;
        
	}

    private List<String> initMappingField() {
        List<String> list = new ArrayList<>();
        list.add("ID");
        list.add("ORGANIZATION_CODE");
        list.add("ORGANIZATION_NAME_EN");
        list.add("ORGANIZATION_NAME_CN");
        list.add("ORGANIZATION_SHORT_NAME");
        list.add("DEPARTMENT_HEAD_PERSON_NUMBER");
        list.add("DEPARTMENT_HEAD_NAME");
/*        list.add("PVC_PERSON_NUMBER");
        list.add("PVC_NAME");*/
        list.add("ERP_CREATION_DATE");
        list.add("ERP_LAST_UPDATE_DATE");
        return list;
    }

    private List<Map<String, String>> getRsListData(List<String> fieldList, IRowSet rs) throws BOSException {
        List<Map<String, String>> dataList = new ArrayList<>();
        try {
            while (rs.next()) {
                HashMap<String, String> dataMap = new HashMap<>();
                int i = 0;
                for (int size = fieldList.size(); i < size; ++i) {
                    String field = fieldList.get(i);
                    dataMap.put(field, rs.getString(field));
                }
                dataList.add(dataMap);
            }
            return dataList;
        } catch (SQLException ex) {
            throw new BOSException(ex);
        }
    }
}