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.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;

    @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
     */
    @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
     */
    @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);
    }

    @PostMapping("/dept/list")
    public R deptList(@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.deptList(page,pageSize,orderField,order);

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

    @PostMapping("/dept/add")
    public R addDept(DepartmentVo departmentVo){
        DepartmentDto departmentDto = new DepartmentDto();

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

    }

    @PostMapping("/dept/edit")
    public R editDept(DepartmentVo departmentVo){

        DepartmentDto departmentDto = new DepartmentDto();

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

    }

    @PostMapping("/dept/delete")
    public R deleteDept(@RequestParam(value = "ids",required = false) List<Long> ids){
        userClient.deleteDept(ids);
        return R.ok();

    }

    @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);
    }

    @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);
    }

    @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);
    }


    @PostMapping("/role/list")
    public R roleList(@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.roleList(page,pageSize,orderField,order);

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

    @RequestMapping("/role/info")
    public R infoRole(Long roleId){
        RoleDto dto = userClient.infoRole(roleId);

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

    @PostMapping("/role/add")
    public R roleAdd(RoleVo vo){
        RoleDto dto = new RoleDto();
        BeanUtils.copyProperties(vo,dto);
        userClient.addRole(dto);
        return R.ok();
    }

    @PostMapping("/role/edit")
    public R editRole(RoleVo vo){

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

    @PostMapping("/role/delete")
    public R deleteRole(@RequestParam(value = "ids",required = false) List<Long> ids){
        userClient.deleteRole(ids);
        return R.ok();
    }

    @PostMapping("/role/listAll")
    public R selectRole(){
        List<RoleDto> roleDtos = userClient.roleListAll();

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

    @PostMapping("/user/list")
    public R userList(@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.userList(page,pageSize,orderField,order);
        return new R().put("data",pageDto);
    }

    @RequestMapping("/user/info")
    public R infoRole(String username){
        UserDto dto = userClient.userInfo(username);
        return R.ok().put("data",dto);
    }

    @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();
    }

    @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();
    }

    @PostMapping("/user/delete")
    public R deleteUser(@RequestParam(value = "ids",required = false) List<Long> ids){
        userClient.deleteUser(ids);
        return R.ok();
    }

}
