package com.customization.hrm.dept;

import com.api.hrm.service.HrmUserIconService;
import com.api.hrm.service.impl.HrmUserIconServiceImpl;
import com.engine.common.util.ServiceUtil;
import com.engine.hrm.cmd.emmanager.GetOrganizationInfoCmd;
import org.jsoup.helper.StringUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

import com.engine.core.cfg.annotation.CommandDynamicProxy;
import com.engine.core.interceptor.AbstractCommandProxy;
import com.engine.core.interceptor.Command;
import org.apache.log4j.Logger;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.appdetach.AppDetachComInfo;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.hrm.resource.ResourceComInfo;


@CommandDynamicProxy(target = GetOrganizationInfoCmd.class,desc="")
public class ProxyGetOrganizationInfoCmd extends AbstractCommandProxy<Map<String, Object>> {


    private Logger log = Logger.getLogger(this.getClass());
    @Override
    public Map<String, Object> execute(Command<Map<String, Object>> targetCommand) {
        GetOrganizationInfoCmd cmd = (GetOrganizationInfoCmd) targetCommand;
        // new BaseBean().writeLog("");
        Map<String, Object> result = nextExecute(targetCommand);
        Map<String, Object> params = cmd.getParams();
        Map<String, Object> resultNew = cmd.getParams();
        long startTime=System.currentTimeMillis();
        //writeLog("进入getOrganizationInfo方法时间===="+startTime);
        String cmdType = Util.null2String(params.get("cmd"));
        String fetch_mine = Util.null2String(params.get("fetch_mine"));
        // new BaseBean().writeLog("fetch_mine",fetch_mine);
        if(cmdType.equals("getOrganizationInfo") && "0".equals(fetch_mine)){
            resultNew = this.extracted(params,result);;
        }else {
            resultNew = result;
        }

        return resultNew;
    }

    private Map<String, Object> extracted(Map<String, Object> params, Map<String, Object> result) {
        try {
            BaseBean baseBean = new BaseBean();
            Map<String, Object> resultNew = result;
            String id = Util.null2String(params.get("id"));//节点id
            String userid = Util.null2String(params.get("userid"));//节点id
            // int userid = Util.getIntValue(Util.null2String(params.get("userid")));
            User user = new User(Integer.parseInt(userid));
            String type = "";//节点类型 1 com，2 subcom,  3 dept
            String tmpStr = id;
            if(id.length()>0) {
                if (id.startsWith("-")) {
                    tmpStr = id.replace("-", "");
                    type = tmpStr.substring(0, 1);
                    id = "-" + tmpStr.substring(1, tmpStr.length());
                } else {
                    type = tmpStr.substring(0, 1);
                    id = tmpStr.substring(1, tmpStr.length());
                }

                if (type.equals("1")) {
                    type = "com";
                    id="0";
                }else{
                    type = type.equals("2") ? "com" : "dept";
                }
            }
            RecordSet recordSet = new RecordSet();
            ArrayList<String> idlist = new ArrayList<>();
            Map<String,String> bmIdHrmMap = new HashMap<>();
            ArrayList<String> branchDeptidList = new ArrayList<>();
            //查询分部下
            if ("com".equals(type)) {
                recordSet.executeQuery("select BM,KJRY,FB from uf_txlbxsbm where fb = ?",id);
                while (recordSet.next()){
                    String bm = Util.null2String(recordSet.getString("BM"));
                    String kjry = Util.null2String(recordSet.getString("KJRY"));
                    // String fb = Util.null2String(recordSet.getString("FB"));
                    idlist.add(bm);
                    bmIdHrmMap.put(bm,kjry);
                }
            }
            //查询部门下
            if ("dept".equals(type)) {
                recordSet.executeQuery("select BM,KJRY,FB from uf_txlbxsbm where SJBM = ?",id);
                while (recordSet.next()){
                    String bm = Util.null2String(recordSet.getString("BM"));
                    String kjry = Util.null2String(recordSet.getString("KJRY"));
                    // String fb = Util.null2String(recordSet.getString("FB"));
                    idlist.add(bm);
                    bmIdHrmMap.put(bm,kjry);
                }

                recordSet.executeQuery("select ZBM ,kjry  from uf_branchdept t1 left join uf_branchdept_dt1 d1 on t1.id = d1.mainid " +
                                       " where t1.DEPT = ?",id);
                while (recordSet.next()){
                    String bm = Util.null2String(recordSet.getString("ZBM"));
                    String kjry = Util.null2String(recordSet.getString("KJRY"));
                    // String fb = Util.null2String(recordSet.getString("FB"));
                    idlist.add(bm);
                    bmIdHrmMap.put(bm,kjry);
                    branchDeptidList.add(bm);
                }
            }
            List<Map<String,Object>> departmentList = (List<Map<String, Object>>)(resultNew.get("department"));
            List<Map<String,Object>> departmentListNew = new ArrayList<>();
            //过滤建模表里的部门
            for (Map<String, Object> department : departmentList){
                String deptid = department.get("id").toString() ;
                deptid = deptid.substring(1, deptid.length());
                if (!idlist.contains(deptid)){
                    departmentListNew.add(department);
                }else {
                    String kjry = bmIdHrmMap.get(deptid);
                    List<String> kjrylist = Arrays.asList(kjry.split(","));
                    if (kjrylist.contains(userid)){
                     departmentListNew.add(department);
                    }
                }
            }

            resultNew.put("department",departmentListNew);
            //添加明细里部门的人员
            List<Map<String,Object>> userlist = (List<Map<String, Object>>)(resultNew.get("userlist"));
            // baseBean.writeLog("人员子部门====",branchDeptidList);
            for (String deptid : branchDeptidList) {
                List<Map<String,Object>> resourceList = this.getResourceList(deptid,user,params);
                // baseBean.writeLog("子部门人员列表====",resourceList);
                userlist.addAll(resourceList);
            }
            // 使用Comparator对List中的Map进行排序
            Collections.sort(userlist, Comparator.comparingDouble(m -> (Double)m.get("showorder")));



            resultNew.put("userlist",userlist);
            return resultNew;
        }catch (Exception e){
            new BaseBean().writeLog(e.getMessage());
            e.printStackTrace();
            return result;
        }
    }


    /***
     * 根据部门获取人员
     * @param departmentId
     * @return
     */
    private List<Map<String,Object>> getResourceList(String departmentId , User user , Map<String, Object> params){
        List<Map<String,Object>> resourceList = new ArrayList<>();
        Map<String,Object> resourceInfo = null;
        RecordSet rs = new RecordSet();
        String sql = "";
        try{
            DepartmentComInfo departmentComInfo = new DepartmentComInfo();
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo();
            boolean enable_main_account = "1".equals(Util.null2String(params.get("enable_main_account")).trim());
            departmentComInfo.setTofirstRow();
            AppDetachComInfo adci = new AppDetachComInfo(user);
            sql = " select hr.id, hr.lastname, hr.sex, hr.managerid, hr.jobtitle, hr.status, hr.dsporder, hr.messagerurl, hr.pinyinlastname, hr.accounttype, hr.belongto  "
                    + " from hrmresource hr, hrmdepartment t2 "
                    + " where hr.departmentid=t2.id and t2.id=?" ;
            String sqlwhere =" and hr.status in (0,1,2,3)";
            if(adci.isUseAppDetach()){
                String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID()+"",true,"resource_hr");
                String tempstr= (appdetawhere!=null&&!"".equals(appdetawhere)?(" and " + appdetawhere):"");
                sqlwhere+=tempstr;
            }
            if(sqlwhere.length()>0)sql+=sqlwhere;
            sql += " order by hr.dsporder ";
            rs.executeQuery(sql,departmentId);
            while (rs.next()) {
                String userid = rs.getString("id");
                String lastname = Util.formatMultiLang(rs.getString("lastname"),""+user.getLanguage());
                String accounttype = rs.getString("accounttype");
                String belongto = "1".equals(accounttype)?Util.null2String(rs.getString("belongto")):"";
                String belongto_name = Util.formatMultiLang(resourceComInfo.getLastname(belongto),""+user.getLanguage());
                String pinyinlastname = Util.null2String(rs.getString("pinyinlastname"));
                String sex = Util.null2String(rs.getString("sex"),"0");
                String managerid = rs.getString("managerid");
                String managername = Util.formatMultiLang(managerid.length() > 0 ? resourceComInfo.getResourcename(managerid) : "",""+user.getLanguage());
                String jobtitle = rs.getString("jobtitle");
                String jobtitlename = Util.formatMultiLang(jobTitlesComInfo.getJobTitlesname(jobtitle),""+user.getLanguage());
                String status = rs.getString("status");
                String showorder = Util.toDecimalDigits(rs.getString("dsporder"),2);
                String messagerurl = rs.getString("messagerurl");
                resourceInfo = new HashMap<>();

                resourceInfo.put("userid",userid);
                resourceInfo.put("name",lastname);
                if(enable_main_account){
                    resourceInfo.put("main_base_user_id",belongto );
                    resourceInfo.put("main_base_user_name",belongto_name);
                }
                resourceInfo.put("manager_id",managerid);
                resourceInfo.put("manager_name",managername);
                resourceInfo.put("position",jobtitlename);
                resourceInfo.put("status",status);
                resourceInfo.put("showorder",showorder);
                resourceInfo.put("gender",Util.getIntValue(sex));
                resourceInfo.put("base_user_id",userid);
                resourceInfo.put("base_user_name",lastname);
                resourceInfo.put("name_simple_pingyin",pinyinlastname);
                resourceInfo.put("name_full_pingyin",pinyinlastname);
                resourceInfo.put("guangliyuanxiashu",pinyinlastname);
                resourceInfo.put("base_name_simple_pingyin",pinyinlastname);
                resourceInfo.put("base_name_full_pingyin",pinyinlastname);
                Map<String,Object> avatar = new HashMap<>();//头像信息
                params.put("userId",userid);
                Map<String,Object> userIconInfo = ((HrmUserIconService) ServiceUtil.getService(HrmUserIconServiceImpl.class, user)).getUserIcon(params,user);
                String media_id = userIconInfo.get("messagerurl").toString();
                //这种格式得手机端显示不出来,取默认设置图片
                if(media_id.startsWith("/weaver/weaver.file.FileDownload")){
                    media_id = userIconInfo.get("defaultmessagerurl").toString();
                }else if(messagerurl.length()>0){
                    String filePath = GCONST.getRootPath() + media_id;
                    File file = new File(filePath);
                    if(!file.exists()){
                        media_id = userIconInfo.get("defaultmessagerurl").toString();
                    }
                }
                resourceInfo.put("avatar",avatar);
                avatar.put("default","");
                avatar.put("show_name", userIconInfo.get("shortname").toString());
                avatar.put("show_color",userIconInfo.get("background").toString());
                avatar.put("media_id",media_id);
                resourceList.add(resourceInfo);
            }
        }catch (Exception e){
            new BaseBean().writeLog(e);
        }
        // new BaseBean().writeLog("resourceList",resourceList);
        return resourceList;
    }
}
