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.domain.User;
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.util.IdWorker;
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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
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 pageBean
     * @param id
     * @param pId
     * @param name
     * @return Result
     **/
    @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);
        }

    }
    /**
     * 加载ztree
     * @Author:cwd
     * @Description:加载ztree
     * @Date: 2019/03/04 22:53
     * @return Result
     **/
    @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 id
     * @param name
     * @param pId
     * @param department
     * @param position
     * @param type
     * @return Result
     **/
    @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 id
     * @return Result
     **/
    @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 name
     * @param abbreviationName
     * @param id
     * @return Result
     **/
    @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);
        }
    }

    /**
     * 删除组织及下级
     * @Author:cwd
     * @Date: 2019/03/04 22:53
     * @param id
     * @param pId
     * @return Result
     */
    @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);
        }
    }


    /**
     * 用户列表
     * @Description: 用户列表
     * @author: cwd
     * @param id
     * @param pageBean
     * @param userName
     * @return Result
     * @date: 2019/3/4
     * @time: 11:03
     */
    @Override
    public Result userList(Integer id, PageBean pageBean, String userName) {
        try{
            PageHelper.startPage(pageBean.getPageNum(), pageBean.getPageSize());
            List<User> list = userInfoMapper.userList(userName);
            PageInfo<User> pageInfo = new PageInfo<>(list);
            return ResultUtil.getResult(RespCode.Code.SUCCESS, pageInfo);
        }catch (Exception e){
            return ResultUtil.getResult(RespCode.Code.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 添加用户
     * @Author:cwd
     * @param user
     * @Date: 2019.4.4
     * @return Result
     */
    @Override
    public Result addUser(User user) {
        Result result=new Result();
        try{
            user.setUserUuid(IdWorker.nextId());
            String password = user.getPassword();
            //密码加密
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(4);
            String enPassword = encoder.encode(password);
            user.setPassword(enPassword);
            userInfoMapper.addUser(user);
            result.setSuccess(true);
            result.setCode("200");
            result.setMessage("添加用户成功");
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setCode("500");
            result.setMessage("添加用户失败");
            return result;
        }

    }
    /**
     * 删除用户
     * @Author:cwd
     * @Date: 2019.4.4
     * @return
     * @param user
     */
    @Override
    public Result deleteUser(User user) {
        Result result=new Result();
        try{
            userInfoMapper.deleteUser(user);
            result.setSuccess(true);
            result.setCode("200");
            result.setMessage("删除用户成功");
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setCode("500");
            result.setMessage("删除用户失败");
            return result;
        }
    }

    /**
     * 获取菜单树
     * @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;
    }


}
