package com.horizon.org;

import com.horizon.common.collect.Lists;
import com.horizon.core.HorizonCore;
import com.horizon.db.Access;
import com.horizon.third.build.OrgBuilder;
import com.horizon.third.entity.OrgData;
import com.horizon.third.entity.User;

import java.util.*;

/**
 * @Author: yangff update  2024-03-21
 */
public class OrgBuilderImplSgiip extends OrgBuilder {

    @Override
    public List<OrgData> depts() {
        System.out.println("当前租户标识：" + HorizonCore.TENANT_CODE.value());
        String dbIdentifier = "sgiip";
        Map<String, List<User>> usersDept = getUsersAndDept(dbIdentifier);//获取部门与用户的对应关系
        // id：部门id； dept_code ：部门编号 ； dept_name：部门名称 ；parent_id：部门父节点id，必须存在 ； order_no 排序号，没有可默认
//        String deptsql = "select id,dept_code,dept_name,parent_id,order_no from to_horizon_dept where  id!='root_node_id' order by order_no";

        String deptsql = "";
        deptsql += " select d.id,d.dept_code,d.dept_name, ( select a.id from sgiip.sys_department a where a.dept_code = d.f_id ) as parent_id  ,";
        deptsql += " 'D' as type ,0 as order_no ";
        deptsql += " from sgiip.sys_department d where d.cancel_flag = '0' and  d.dept_code!='D' ";


        List<Map<String, Object>> deptmap = Access.getMultiMap(deptsql, null, dbIdentifier);
        //部门信息封装到datas对象中，作为返回值
        List<OrgData> datas = Lists.newArrayList();
        //处理根部门
        OrgData data_r = new OrgData();
        data_r.setId("1");
        data_r.setName("部门导航");
        data_r.setParentId("0");
        data_r.setType("D");
        datas.add(data_r);
        for (Map<String, Object> map : deptmap) {
            String id = map.get("id") == null ? "" : map.get("id").toString();
            String name = map.get("dept_name") == null ? "" : map.get("dept_name").toString();
            String bmbh = map.get("dept_code") == null ? "" : map.get("dept_code").toString();
            String parentId = map.get("parent_id") == null ? "" : map.get("parent_id").toString();
            String sort = map.get("order_no") == null ? "" : map.get("order_no").toString();

            if ("0".equals(parentId)) {
                parentId = "1"; //部门导航、最顶层
            }
            //一个data对象封装一个部门信息
            OrgData data_d = new OrgData();
            data_d.setId(id);
            data_d.setName(name);
            data_d.setParentId(parentId);
            data_d.setType("D");
            data_d.setOrderNo(Integer.parseInt(sort));
            data_d.setCode(bmbh);
            //usermap.get(id)根据部门ID获取此部门人员，并保存到data对象中
            if (usersDept.get(id) != null) {//判断通过id键获取的用户信息不为空，增加对应用户信息
                data_d.setUsers(usersDept.get(id));
            }
            //封装部门信息的实例增加到datas对象中
            datas.add(data_d);
        }
        return datas;
    }

    /**
     * 获取部门下人员信息，此方法是获取用户与部门关联的信息，部门ID作为键，User对象为值
     *
     * @return
     */
    private Map<String, List<User>> getUsersAndDept(String dbIdentifier) {
//        String usersql = "select u.id,u.login_name,u.name,tor.dept_id from to_horizon_user u,tor_horizon_user_dept tor where u.id = tor.user_id";
//        String usersql = "select u.id,u.user_name as login_name,u.user_desc,tor.dept_id from sgiip.sys_user u,sgiip.sys_user_department tor where u.id = tor.user_id";
        String usersql = "";
        usersql += "  SELECT u.id,u.user_name as LOGIN_NAME,u.user_desc as NAME,tor.DEPT_ID ,'' as type FROM sgiip.sys_user u,sgiip.sys_user_department tor WHERE u.ID = tor.USER_ID";
        usersql += "  union all";
        usersql += " select '1' as id ,'admin' as login_name  ,'超级管理员' as NAME ,'0' as DEPT_ID  ,'' as type from dual";


        List<Map<String, Object>> userMap = Access.getMultiMap(usersql, null, dbIdentifier);
        Map<String, List<User>> usersAndDept = new HashMap<String, List<User>>();
        for (Map<String, Object> map : userMap) {
            //部门ID
            String deptId = map.get("dept_id") == null ? "" : map.get("dept_id").toString();
            //用户名
            String userName = map.get("name") == null ? "" : map.get("name").toString();
            //用户ID
            String id = map.get("id") == null ? null : map.get("id").toString();
            //若存在ID为null的User对象，那么在获取用户信息时，会出现空指针错误
            if (id != null) {
                //用户信息存入user对象中
                User user = new User();
                user.setId(id);
                user.setUserName(userName);
                List<User> users = new ArrayList<User>();
                if (usersAndDept.get(deptId) == null) {//第一次存入部门与用户对应信息
                    users.add(user);
                    usersAndDept.put(deptId, users);
                } else {//已存在该部门与用户的对应信息
                    users = usersAndDept.get(deptId);
                    users.add(user);
                    usersAndDept.put(deptId, users);
                }
            }
        }
        return usersAndDept;
    }

    @Override
    public List<OrgData> groups() {

        return null;

//        String dbIdentifier = "sgiip";
//        Map<String,List<User>> usersAndGroup = getUsersAndGroup(dbIdentifier);
//        // code是编号；  群组跟部门一样，支持树形结构
//        String usersql = "select id,group_name,group_code,parent_id from to_horizon_group WHERE ID!='root_node_id'";
//        List<Map<String,Object>> userMap = Access.getMultiMap(usersql, null, dbIdentifier);
//        //群组信息封装到datas对象中，作为返回值
//        List<OrgData> datas = Lists.newArrayList();
//        OrgData data_r = new OrgData();//群组根数据，根数据的parentid需要为null
//        data_r.setId("group_root");
//        data_r.setName("角色导航");
//        data_r.setParentId(null);
//        data_r.setType("G");
//        datas.add(data_r);
//        for (Map<String, Object> map : userMap) {
//            String id = map.get("id")==null?"":map.get("id").toString();
//            String name = map.get("group_name")==null?"":map.get("group_name").toString();
//            String code = map.get("group_code")==null?"":map.get("group_code").toString();
//            String parentid = map.get("parent_id")==null?"":map.get("parent_id").toString();
//
//            //如果是一级群组，需要转换下根部门，根据实际情况修改名称
//            if("root_node_id".equals(parentid)){
//                parentid="group_root";
//            }
//            OrgData data_g = new OrgData();
//            data_g.setId(id);
//            data_g.setName(name);
//            data_g.setCode(code);
//            data_g.setParentId(parentid);
//            if (usersAndGroup.get(id) != null){//判断通过id键获取的用户信息不为空，增加对应用户信息
//                data_g.setUsers(usersAndGroup.get(id));
//            }
//            //必须固定
//            data_g.setType("G");
//            datas.add(data_g);
//        }
//         return datas;

    }

    @Override
    public List<OrgData> positions() {
        System.out.println("当前租户标识：" + HorizonCore.TENANT_CODE.value());
        String dbIdentifier = "sgiip";
        Map<String, List<User>> usersDept = getUsersAndPost(dbIdentifier);//获取部门与用户的对应关系
        // id：部门id； dept_code ：部门编号 ； dept_name：部门名称 ；parent_id：部门父节点id，必须存在 ； order_no 排序号，没有可默认
//        String deptsql = "select id,dept_code,dept_name,parent_id,order_no from to_horizon_dept where  id!='root_node_id' order by order_no";

        String deptsql = "";
        deptsql += " select d.id,d.post_code,d.post_name, 'position_root' as parent_id,";
        deptsql += " 'P' as type ,0 as order_no";
        deptsql += " from sgiip.sys_post d where d.cancel_flag = '0'";


        List<Map<String, Object>> deptmap = Access.getMultiMap(deptsql, null, dbIdentifier);
        //部门信息封装到datas对象中，作为返回值
        List<OrgData> datas = Lists.newArrayList();
        //处理根部门
        OrgData data_r = new OrgData();
        data_r.setId("position_root");
        data_r.setName("岗位导航");
        data_r.setParentId("0");
        data_r.setType("P");
        datas.add(data_r);
        for (Map<String, Object> map : deptmap) {
            String id = map.get("id") == null ? "" : map.get("id").toString();
            String name = map.get("post_name") == null ? "" : map.get("post_name").toString();
            String bmbh = map.get("post_code") == null ? "" : map.get("post_code").toString();
            String parentId = map.get("parent_id") == null ? "" : map.get("parent_id").toString();
            String sort = map.get("order_no") == null ? "" : map.get("order_no").toString();

            if ("0".equals(parentId)) {
                parentId = "1"; //部门导航、最顶层
            }
            //一个data对象封装一个部门信息
            OrgData data_d = new OrgData();
            data_d.setId(id);
            data_d.setName(name);
            data_d.setParentId(parentId);
            data_d.setType("P");
            data_d.setOrderNo(Integer.parseInt(sort));
            data_d.setCode(bmbh);
            //usermap.get(id)根据部门ID获取此部门人员，并保存到data对象中
            if (usersDept.get(id) != null) {//判断通过id键获取的用户信息不为空，增加对应用户信息
                data_d.setUsers(usersDept.get(id));
            }
            //封装部门信息的实例增加到datas对象中
            datas.add(data_d);
        }
        return datas;
    }


    private Map<String, List<User>> getUsersAndPost(String dbIdentifier) {
        String usersql = " SELECT u.id,u.user_name as LOGIN_NAME,u.user_desc as NAME,tor.post_ID ,'' as type FROM sgiip.sys_user u,sgiip.sys_user_post tor WHERE u.ID = tor.USER_ID ";
        List<Map<String, Object>> userMap = Access.getMultiMap(usersql, null, dbIdentifier);
        Map<String, List<User>> usersAndDept = new HashMap<String, List<User>>();
        for (Map<String, Object> map : userMap) {
            //部门ID
            String deptId = map.get("post_id") == null ? "" : map.get("post_id").toString();
            //用户名
            String userName = map.get("name") == null ? "" : map.get("name").toString();
            //用户ID
            String id = map.get("id") == null ? null : map.get("id").toString();
            //若存在ID为null的User对象，那么在获取用户信息时，会出现空指针错误
            if (id != null) {
                //用户信息存入user对象中
                User user = new User();
                user.setId(id);
                user.setUserName(userName);
                List<User> users = new ArrayList<User>();
                if (usersAndDept.get(deptId) == null) {//第一次存入部门与用户对应信息
                    users.add(user);
                    usersAndDept.put(deptId, users);
                } else {//已存在该部门与用户的对应信息
                    users = usersAndDept.get(deptId);
                    users.add(user);
                    usersAndDept.put(deptId, users);
                }
            }
        }
        return usersAndDept;
    }


    @Override
    public List<OrgData> roles() {
        return null;
    }

    //获取工作群组人员
    private Map<String, List<User>> getUsersAndGroup(String dbIdentifier) {
        // 需要群组id，用户id，用户name
        String userSql = "select tor.workgroup_id,u.id,u.name from tor_horizon_user_group tor , to_horizon_user u where tor.user_id= u.id";
        List<Map<String, Object>> userMap = Access.getMultiMap(userSql, null, dbIdentifier);
        Map<String, List<User>> usersAndGroup = new HashMap<String, List<User>>();
        for (Map<String, Object> map : userMap) {
            List<User> users = new ArrayList<User>();
            String id = map.get("id") == null ? "" : map.get("id").toString();
            String userName = map.get("name") == null ? "" : map.get("name").toString();
            String workGroupId = map.get("workgroup_id") == null ? "" : map.get("workgroup_id").toString();
            if (id != null) {//避免出现空指针错误,如此处ID与users方法中的userid不一致也会出现空指针错误
                if (usersAndGroup.get(workGroupId) == null) {//第一次操作岗位信息
                    User user = new User();
                    user.setId(id);
                    user.setUserName(userName);
                    users.add(user);
                    usersAndGroup.put(workGroupId, users);
                } else {//已有岗位信息，进行从新编辑
                    users = usersAndGroup.get(workGroupId);
                    User user = new User();
                    user.setId(id);
                    user.setUserName(userName);
                    users.add(user);
                    usersAndGroup.put(workGroupId, users);
                }
            }
        }
        return usersAndGroup;
    }


    @Override
    public List<User> users() {
        String dbIdentifier = "sgiip";
        //id，用户唯一id；  login_name,用户登录名；   name，用户姓名；  dept_id，用户所属部门id ；
//        String sql="SELECT u.id,u.LOGIN_NAME,'F;D' as type,u.NAME,tor.DEPT_ID FROM TO_HORIZON_USER u,TOR_HORIZON_USER_DEPT tor WHERE u.ID = tor.USER_ID";

        String sql = "";
        sql += "  SELECT u.id,u.user_name as LOGIN_NAME,u.user_desc as NAME,tor.DEPT_ID ,'' as type FROM sgiip.sys_user u,sgiip.sys_user_department tor WHERE u.ID = tor.USER_ID";
        sql += "  union all";
        sql += " select '1' as id ,'admin' as login_name  ,'超级管理员' as NAME ,'0' as DEPT_ID  ,'' as type from dual";

        //从数据库获取用户信息
        List<Map<String, Object>> usermap = Access.getMultiMap(sql, null, dbIdentifier);
        //用户信息保存到datas集合对象中返回
        List<User> datas = Lists.newArrayList();
        for (Map<String, Object> map : usermap) {
            String id = map.get("id") == null ? "" : map.get("id").toString();
            String name = map.get("name") == null ? "" : map.get("name").toString();
            String loginName = map.get("login_name") == null ? "" : map.get("login_name").toString();
            String deptid = map.get("dept_id") == null ? "" : map.get("dept_id").toString();

            //处理用户所属部门，可以所属多个部门
            List<String> listDept = Lists.newArrayList(deptid);
//            listDept.add(deptid);
            //用户信息保存到User类的对象中
            User u = new User();
            u.setId(id);
            u.setUserName(name);
            u.setLoginName(loginName);
            u.setPasswd("1234");//密码，一般设置默认统一的密码
            u.setDepartment(listDept);
            u.setOrderNo(1);//用户排序，可选

            if(Objects.equals(id, "24F955A08CD8CDECE063040011AC9F7F") && listDept.contains("25855EBF0D906250E063040011ACA98F")){
                u.setOperType("F");//用户类型（F：直接部门领导，C：上级主管领导，I：部门管理员，空：一般用户，可传多值，多值用;隔开）
            }else {
                u.setOperType("");//用户类型（F：直接部门领导，C：上级主管领导，I：部门管理员，空：一般用户，可传多值，多值用;隔开）
            }
            datas.add(u);
        }
        return datas;
    }
}
