package com.bbd.bpm.serviceImpl;

import com.bbd.bpm.base.PageBean;
import com.bbd.bpm.dao.MemberMapper;
import com.bbd.bpm.dao.UserInfoMapper;
import com.bbd.bpm.domain.BpmCompany;
import com.bbd.bpm.domain.BpmEmployee;
import com.bbd.bpm.result.RespCode;
import com.bbd.bpm.result.Result;
import com.bbd.bpm.result.ResultUtil;
import com.bbd.bpm.service.UserInfoService;
import com.bbd.bpm.vo.BpmCompanyVo;
import com.bbd.bpm.vo.MenuVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.activiti.editor.language.json.converter.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserInfoServiceImpl implements UserInfoService{

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private MemberMapper memberMapper;
    /**
     * @Author:cwd
     * @Description:获取组织列表
     * @Date: 2019/03/04 22:53
     * @Param:
     * @return
     **/
    @Override
    public Result getOrganization(PageBean pageBean, Integer id, Integer pId, String name) {
        try{

            if(pId==null){
                PageHelper.startPage(pageBean.getPageNum(), pageBean.getPageSize());
                if(id==null){
                    id=1;
                }
                List<BpmCompanyVo> list = userInfoMapper.getOrganization(id,name);
                BpmCompanyVo bpmCompanyVo;
                for (int i=0;i<list.size();i++){
                    Integer pIds = list.get(i).getPId();
                    bpmCompanyVo=userInfoMapper.getParentName(pIds);
                    //根据pid获取上级组织名称
                    list.get(i).setParentName(bpmCompanyVo.getName());
                }
                PageInfo<BpmCompanyVo> pageInfo = new PageInfo<>(list);
                Map<String, Object> map = new HashMap<>(16);
                map.put("pageInfo", pageInfo);
                map.put("type", 1);
                return ResultUtil.getResult(RespCode.Code.SUCCESS, map);
            }else if(pId==1){
                PageHelper.startPage(pageBean.getPageNum(), pageBean.getPageSize());
                List<BpmCompanyVo> list = memberMapper.getAllMemberList(id,name);
                PageInfo<BpmCompanyVo> pageInfo = new PageInfo<>(list);
                Map<String, Object> map = new HashMap<>(16);
                map.put("pageInfo", pageInfo);
                map.put("type", 2);
                return ResultUtil.getResult(RespCode.Code.SUCCESS, map);
            }else{
                PageHelper.startPage(pageBean.getPageNum(), pageBean.getPageSize());
                List<BpmCompanyVo> list = memberMapper.getMemberList(id,name);
                PageInfo<BpmCompanyVo> pageInfo = new PageInfo<>(list);
                Map<String, Object> map = new HashMap<>(16);
                map.put("pageInfo", pageInfo);
                map.put("type", 2);
                return ResultUtil.getResult(RespCode.Code.SUCCESS, map);
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.getResult(RespCode.Code.INTERNAL_SERVER_ERROR);
        }

    }
    /**
     * @Author:cwd
     * @Description:加载ztree
     * @Date: 2019/03/04 22:53
     * @Param:
     * @return
     **/
    @Override
    public Result getOrganizationList() {
        try {
            List<Map<String,Object>> organizations = userInfoMapper.getOrganizationList();
            return ResultUtil.getResult(RespCode.Code.SUCCESS,organizations);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.getResult(RespCode.Code.INTERNAL_SERVER_ERROR);
        }
    }
    /**
     * @Author:cwd
     * @Description:添加组织
     * @Date: 2019/03/04 22:53
     * @Param:
     * @return
     **/
    @Override
    public Result addOrganization(String name, String abbreviationName, Long pId, Integer id) {
        try{
            BpmCompany bpmCompany=new BpmCompany();
            //组织编号
            StringBuilder str=new StringBuilder();//定义变长字符串
            Random random=new Random();
            //随机生成数字，并添加到字符串
            for(int i=0;i<8;i++){
                str.append(random.nextInt(6));
            }
            String number = "zz"+str.toString();
            //通过pid获取上一级的组织关系
            String relation=userInfoMapper.getOrganizationRelation(id);
            //拼接
            String a=relation+"/"+number;

            bpmCompany.setName(name);
            bpmCompany.setCreateTime(new Date());
            bpmCompany.setUpdateTime(new Date());
            bpmCompany.setAbbreviationName(abbreviationName);
            bpmCompany.setCode(number);
            bpmCompany.setOrganizationRelation(a);
            if(pId==null){
                pId=1L;
            }
            bpmCompany.setPId(id);
            bpmCompany.setStatus(0);
            userInfoMapper.insertSelective(bpmCompany);
            return ResultUtil.getResult(RespCode.Code.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.getResult(RespCode.Code.INTERNAL_SERVER_ERROR);
        }
    }
    /**
     * @Author:cwd
     * @Description:部门下添加人员信息
     * @Date: 2019/03/04 22:53
     * @Param:
     * @return
     **/
    @Override
    public Result addOrganizationMember(String name, String position, Long pId, Integer id, Integer department, Integer type) {
        try {
            BpmEmployee bpmEmployee=new BpmEmployee();
            bpmEmployee.setCreateTime(new Date());
            bpmEmployee.setUpdateTime(new Date());
            bpmEmployee.setName(name);
            if(type!=null){
                bpmEmployee.setDepartment(department);
                bpmEmployee.setCodeId(id);
            }else {
                bpmEmployee.setDepartment(id);
                bpmEmployee.setCodeId(pId.intValue());

            }
            bpmEmployee.setPosition(position);
            bpmEmployee.setStatus(0);
            memberMapper.insert(bpmEmployee);
            return ResultUtil.getResult(RespCode.Code.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.getResult(RespCode.Code.INTERNAL_SERVER_ERROR);
        }

    }
    /**
     * @Author:cwd
     * @Description:获取组织详情
     * @Date: 2019/03/04 22:53
     * @Param:
     * @return
     **/
    @Override
    public Result getOrganizationInfo(Integer id) {
        try {
            Map<String,Object> map = userInfoMapper.getOrganizationInfo(id);
            return ResultUtil.getResult(RespCode.Code.SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.getResult(RespCode.Code.INTERNAL_SERVER_ERROR);
        }
    }
    /**
     * @Author:cwd
     * @Description:修改组织信息
     * @Date: 2019/03/04 22:53
     * @Param:
     * @return
     **/
    @Override
    public Result editOrganization(String name, String abbreviationName, Integer id) {
        try {
            BpmCompany bpmCompany=new BpmCompany();
            bpmCompany.setName(name);
            bpmCompany.setAbbreviationName(abbreviationName);
            bpmCompany.setId(id.longValue());
            userInfoMapper.updateByPrimaryKeySelective(bpmCompany);
            return ResultUtil.getResult(RespCode.Code.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.getResult(RespCode.Code.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 删除组织及下级
     * @param id
     * @param pId
     * @return
     */
    @Override
    public Result deleteOrganization(Long id, Integer pId) {
        try{
            //pId为0删除的是组织,部门,人员 为1删除的是部门和人员
            if(pId==0){
                //通过id删除组织,下级部门,人员
                BpmCompany bpmCompany=new BpmCompany();
                bpmCompany.setId(id);
                bpmCompany.setStatus(2);
                //删除当前组织
                userInfoMapper.updateByPrimaryKeySelective(bpmCompany);
                //删除组织下的部门
                userInfoMapper.deleteDepartment(id);
                //删除人员（人员所属组织编码id 放的组织的id可以直接删除 status为2）
                memberMapper.deletedMember(id);
            }else if(pId==1){
                //删除部门
                userInfoMapper.deleteDepartments(id);
                //删除部门人员
                memberMapper.deletedMembers(id);
            }
            return ResultUtil.getResult(RespCode.Code.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.getResult(RespCode.Code.INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    public Result getAreaAll(Integer id) {
        try {
            List<Map<String,Object>> list=this.memberMapper.getAreaAll(id);
            return ResultUtil.getResult(RespCode.Code.SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.getResult(RespCode.Code.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * @Author:cwd
     * 获取左侧树
     * @Date: 2019.3.7
     * @return
     */
    @Override
    public Result getMenuList() {
        try {
            List<MenuVO> list = memberMapper.selectMenuList();
            return ResultUtil.returnSuccess("菜单返回成功",getMenuTree(list));
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.getResult(RespCode.Code.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取菜单树
     * @param menuVos
     * @return
     */
    public static List<MenuVO> getMenuTree(List<MenuVO> menuVos) {
        List<MenuVO> treeList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(menuVos)) {
            for (MenuVO vo : menuVos) {
                if (null != vo.getParentId() && Long.valueOf(0).equals(vo.getParentId())) {
                    vo = getChildMenu(vo,menuVos);
                    treeList.add(vo);
                }
            }
        }
        return treeList;
    }


    private static MenuVO getChildMenu(MenuVO parent, List<MenuVO> menuVos) {
        List<MenuVO> child = null;
        for (MenuVO vo : menuVos) {
            if (parent.getId().equals(vo.getParentId())) {
                vo = getChildMenu(vo, menuVos);
                if (child == null) {
                    child = new ArrayList<>();
                }
                child.add(vo);
            }
        }
        parent.setChild(child);
        return parent;
    }
}
