package com.mx.cneeds.server.datashow.web.system;

import com.mx.cneeds.common.UserUtils;
import com.mx.cneeds.common.converter.RequestParamterConverter;
import com.mx.cneeds.common.dto.*;
import com.mx.cneeds.common.generate.CascaderToolUtils;
import com.mx.cneeds.common.generate.TreeToolUtils;
import com.mx.cneeds.common.result.R;
import com.mx.cneeds.common.vo.*;
import com.mx.cneeds.server.datashow.client.UserClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SystemController
 * @Author zzrdark
 * @Date 2020-03-09 15:19
 * @Description TODO
 **/
@RestController
@Slf4j
@RequestMapping("/sys")
public class SystemController {

    @Autowired
    private UserClient userClient;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    /**
     * 模块查询
     * @param page
     * @param pageSize
     * @param sort
     * @return
     */
    @PreAuthorize("hasRole('sys:module:list') or hasRole('admin')")
    @PostMapping("/module/list")
    public R funcList(@RequestParam(required = false) Integer page,
                      @RequestParam(required = false) Integer pageSize,
                      @RequestParam(required = false) String sort){

        String orderField = null;
        String order = null;

        if (page==null || page==0){
            page = new Integer(1);
        }
        if (pageSize==null || pageSize==0){
            pageSize = new Integer(10);
        }

        if (StringUtils.isNotEmpty(sort) && StringUtils.isNotBlank(sort.trim())){
            if (sort.contains("+")){
                order = new String("asc");
            }
            if (sort.contains("-")){
                order = new String("desc");
            }
            orderField = sort.substring(1);
            orderField = RequestParamterConverter.toLine(orderField);
        }

        PageDto pageDto = userClient.funcList(page,pageSize,orderField,order);

        return new R().put("data",pageDto);
    }

    /**
     * 查询出角色关联的模块
     * @return
     */
    @PreAuthorize("hasRole('sys:module:list') or hasRole('admin')")
    @PostMapping("/func/listAll")
    public R selectTreeFunc(){
        List<FuncDto> dtos = userClient.funcListAll();
        List<TreeVo> rootList = new ArrayList<>();
        List<TreeVo> bodyList = new ArrayList<>();
        dtos.forEach(dto -> {
            TreeVo vo = new TreeVo(
                    dto.getFuncId(),
                    dto.getName(),
                    dto.getParentId());
            if (dto.getParentId() == 0L){
                rootList.add(vo);
            } else {
                bodyList.add(vo);
            }
        });
        TreeToolUtils utils =  new TreeToolUtils(rootList,bodyList);
        List<TreeVo> result =  utils.getTree();
        return new R().put("data",result);
    }


    /**
     * 查询出用户关联的模块
     * @return
     */
    @PreAuthorize("hasRole('sys:module:list') or hasRole('admin')")
    @PostMapping("/func/user/listAll")
    public R selectTreeFuncUser(){
        List<FuncDto> dtos = userClient.funcListAll();
        List<TreeVo> rootList = new ArrayList<>();
        List<TreeVo> bodyList = new ArrayList<>();
        dtos.forEach(dto -> {
            TreeVo vo = new TreeVo(
                    dto.getFuncId(),
                    dto.getName(),
                    dto.getParentId());
            if (dto.getParentId() == 0L){
                rootList.add(vo);
            } else {
                bodyList.add(vo);
            }
        });
        TreeToolUtils utils =  new TreeToolUtils(rootList,bodyList);
        List<TreeVo> result =  utils.getTree();
        return new R().put("data",result);
    }


    /**
     * 部门查询
     * @param page
     * @param pageSize
     * @param sort
     * @return
     */
    @PreAuthorize("hasRole('sys:dept:list') or hasRole('admin')")
    @PostMapping("/dept/list")
    public R deptList(@RequestParam(required = false) Integer page,
                      @RequestParam(required = false) Integer pageSize,
                      @RequestParam(required = false) String sort,
                      @RequestParam(required = false) String name){

        String orderField = null;
        String order = null;

        if (page==null || page==0){
            page = new Integer(1);
        }
        if (pageSize==null || pageSize==0){
            pageSize = new Integer(10);
        }

        if (StringUtils.isNotEmpty(sort) && StringUtils.isNotBlank(sort.trim())){
            if (sort.contains("+")){
                order = new String("asc");
            }
            if (sort.contains("-")){
                order = new String("desc");
            }
            orderField = sort.substring(1);
            orderField = RequestParamterConverter.toLine(orderField);
        }


        PageDto pageDto = userClient.deptList(page,pageSize,orderField,order,name);

        return new R().put("data",pageDto);
    }

    @PreAuthorize("hasRole('sys:dept:add') or hasRole('admin')")
    @PostMapping("/dept/add")
    public R addDept(DepartmentVo departmentVo){
        DepartmentDto departmentDto = new DepartmentDto();

        BeanUtils.copyProperties(departmentVo,departmentDto);
        userClient.addDept(departmentDto);
        return R.ok();

    }

    /**
     * 编辑部门
     * @param departmentVo
     * @return
     */
    @PreAuthorize("hasRole('sys:dept:edit') or hasRole('admin')")
    @PostMapping("/dept/edit")
    public R editDept(DepartmentVo departmentVo){

        DepartmentDto departmentDto = new DepartmentDto();

        BeanUtils.copyProperties(departmentVo,departmentDto);
        userClient.updateDept(departmentDto);
        return R.ok();

    }


    /**
     * 删除部门
     * @param ids
     * @return
     */
    @PreAuthorize("hasRole('sys:dept:delete') or hasRole('admin')")
    @PostMapping("/dept/delete")
    public R deleteDept(@RequestParam(value = "ids",required = false) List<Long> ids){
        userClient.deleteDept(ids);
        return R.ok();

    }

    /**
     * 获取部门下拉框列表
     * @return 返回树形的列表
     */
    @PreAuthorize("hasRole('sys:dept:list') or hasRole('admin')")
    @PostMapping("/dept/listAll")
    public R selectDeptParent(){
        UserDto userDto = userClient.userInfo(UserUtils.getUserName());
        List<DepartmentDto> dtos = userClient.deptListAll();
        List<CascaderVo> rootList = new ArrayList<>();
        List<CascaderVo> bodyList = new ArrayList<>();
        /*if (userDto.getDeptId()==0){
            CascaderVo voRoot = new CascaderVo(0L,"根",0L);
            rootList.add(voRoot);
        }*/
        dtos.forEach(dto -> {
            CascaderVo vo = new CascaderVo(
                    dto.getDeptId(),
                    dto.getName(),
                    dto.getParentId());
            if (dto.getParentId()==null){
                rootList.add(vo);
            }else if (rootList.size() == 0 && dto.getParentId().equals(userDto.getDeptId())){
                rootList.add(vo);
            } else {
                bodyList.add(vo);
            }
        });
        CascaderToolUtils utils =  new CascaderToolUtils(rootList,bodyList);
        List<CascaderVo> result =  utils.getTree();
        return new R().put("data",result);
    }

    /**
     * 获取部门下拉框列表
     * @return 返回树形的列表
     */
    @PreAuthorize("hasRole('sys:dept:list') or hasRole('admin')")
    @PostMapping("/dept/listAllTree")
    public R selectTreeDeptParent(){
        UserDto userDto = userClient.userInfo(UserUtils.getUserName());
        List<DepartmentDto> dtos = userClient.deptListAll();
        List<TreeVo> rootList = new ArrayList<>();
        List<TreeVo> bodyList = new ArrayList<>();
        dtos.forEach(dto -> {
            TreeVo vo = new TreeVo(
                    dto.getDeptId(),
                    dto.getName(),
                    dto.getParentId());
            if (dto.getParentId()==null){
                rootList.add(vo);
            }else if (rootList.size() == 0 && dto.getParentId().equals(userDto.getDeptId())){
                rootList.add(vo);
            } else {
                bodyList.add(vo);
            }

        });
        TreeToolUtils utils =  new TreeToolUtils(rootList,bodyList);
        List<TreeVo> result =  utils.getTree();
        return new R().put("data",result);
    }

    @PreAuthorize("hasRole('sys:user:list') or hasRole('admin')")
    @PostMapping("/dept/user/listAllTree")
    public R selectTreeDeptUserParent(){
        UserDto userDto = userClient.userInfo(UserUtils.getUserName());
        List<DepartmentDto> dtos = userClient.deptListAll();
        List<TreeVo> rootList = new ArrayList<>();
        List<TreeVo> bodyList = new ArrayList<>();
        dtos.forEach(dto -> {
            TreeVo vo = new TreeVo(
                    dto.getDeptId(),
                    dto.getName(),
                    dto.getParentId());
            if (dto.getParentId()==null){
                rootList.add(vo);
            }else if (rootList.size() == 0 && dto.getParentId().equals(userDto.getDeptId())){
                rootList.add(vo);
            } else {
                bodyList.add(vo);
            }

        });
        TreeToolUtils utils =  new TreeToolUtils(rootList,bodyList);
        List<TreeVo> result =  utils.getTree();
        return new R().put("data",result);
    }


    /**
     * 查询角色
     * @param page
     * @param pageSize
     * @param sort
     * @return
     */
    @PreAuthorize("hasRole('sys:role:list') or hasRole('admin')")
    @PostMapping("/role/list")
    public R roleList(@RequestParam(required = false) Integer page,
                      @RequestParam(required = false) Integer pageSize,
                      @RequestParam(required = false) String sort,
                      @RequestParam(required = false) String roleName){


        String orderField = null;
        String order = null;

        if (page==null || page==0){
            page = new Integer(1);
        }
        if (pageSize==null || pageSize==0){
            pageSize = new Integer(10);
        }

        if (StringUtils.isNotEmpty(sort) && StringUtils.isNotBlank(sort.trim())){
            if (sort.contains("+")){
                order = new String("asc");
            }
            if (sort.contains("-")){
                order = new String("desc");
            }
            orderField = sort.substring(1);
            orderField = RequestParamterConverter.toLine(orderField);
        }

        PageDto pageDto = userClient.roleList(page,pageSize,orderField,order,roleName);

        return new R().put("data",pageDto);
    }

    /**
     * 查询角色信息
     * @param roleId
     * @return
     */
    @PreAuthorize("hasRole('sys:role:list') or hasRole('admin')")
    @RequestMapping("/role/info")
    public R infoRole(Long roleId){
        RoleDto dto = userClient.infoRole(roleId);

        return R.ok().put("data",dto);
    }

    /**
     * 增加角色
     * @param vo
     * @return
     */
    @PreAuthorize("hasRole('sys:role:add') or hasRole('admin')")
    @PostMapping("/role/add")
    public R roleAdd(RoleVo vo){
        RoleDto dto = new RoleDto();
        BeanUtils.copyProperties(vo,dto);
        userClient.addRole(dto);
        return R.ok();
    }


    /**
     * 编辑角色
     * @param vo
     * @return
     */
    @PreAuthorize("hasRole('sys:role:edit') or hasRole('admin')")
    @PostMapping("/role/edit")
    public R editRole(RoleVo vo){

        RoleDto dto = new RoleDto();
        BeanUtils.copyProperties(vo,dto);
        userClient.updateRole(dto);
        return R.ok();
    }

    /**
     * 删除角色
     * @param ids
     * @return
     */
    @PreAuthorize("hasRole('sys:role:delete') or hasRole('admin')")
    @PostMapping("/role/delete")
    public R deleteRole(@RequestParam(value = "ids",required = false) List<Long> ids){
        userClient.deleteRole(ids);
        return R.ok();
    }


    /**
     * 查询出角色的下拉框
     * @return
     */
    @PostMapping("/role/listAll")
    public R selectRole(){
        List<RoleDto> roleDtos = userClient.roleListAll();

        return new R().put("data",roleDtos);
    }

    /**
     * 查询用户
     * @param page
     * @param pageSize
     * @param sort
     * @return
     */

    @PreAuthorize("hasRole('sys:user:list') or hasRole('admin')")
    @PostMapping("/user/list")
    public R userList(@RequestParam(required = false) Integer page,
                      @RequestParam(required = false) Integer pageSize,
                      @RequestParam(required = false) String sort,
                      @RequestParam(required = false) String username){

        String orderField = null;
        String order = null;

        if (page==null || page==0){
            page = new Integer(1);
        }
        if (pageSize==null || pageSize==0){
            pageSize = new Integer(10);
        }

        if (StringUtils.isNotEmpty(sort) && StringUtils.isNotBlank(sort.trim())){
            if (sort.contains("+")){
                order = new String("asc");
            }
            if (sort.contains("-")){
                order = new String("desc");
            }
            orderField = sort.substring(1);
            orderField = RequestParamterConverter.toLine(orderField);
        }

        PageDto pageDto = userClient.userList(page,pageSize,orderField,order,username);
        return new R().put("data",pageDto);
    }

    /**
     * 查询用户信息
     * @param username
     * @return
     */
    @PreAuthorize("hasRole('sys:user:list') or hasRole('admin')")
    @RequestMapping("/user/info")
    public R infoRole(String username){
        UserDto dto = userClient.userInfo(username);
        return R.ok().put("data",dto);
    }

    /**
     * 增加用户
     * @param vo
     * @return
     */
    @PreAuthorize("hasRole('sys:user:add') or hasRole('admin')")
    @RequestMapping("/user/add")
    public R addUser(UserVo vo){
        UserDto dto = new UserDto();
        vo.setPassword(bCryptPasswordEncoder.encode(vo.getPassword()));
        BeanUtils.copyProperties(vo,dto);
        userClient.addUser(dto);
        return R.ok();
    }

    /**
     * 编辑用户
     * @param vo
     * @return
     */
    @PreAuthorize("hasRole('sys:user:edit') or hasRole('admin')")
    @PostMapping("/user/update")
    public R editUser(UserVo vo){
        UserDto dto = new UserDto();
        if (StringUtils.isNotEmpty(vo.getPassword())
                && StringUtils.isNotBlank(vo.getPassword().trim())) {
            vo.setPassword(bCryptPasswordEncoder.encode(vo.getPassword()));
        }
        BeanUtils.copyProperties(vo,dto);
        userClient.updateUser(dto);
        return R.ok();
    }

    /**
     * 删除用户
     * @param ids
     * @return
     */
    @PreAuthorize("hasRole('sys:user:delete') or hasRole('admin')")
    @PostMapping("/user/delete")
    public R deleteUser(@RequestParam(value = "ids",required = false) List<Long> ids){
        userClient.deleteUser(ids);
        return R.ok();
    }

}
