package com.zcxk.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcxk.common.FileUploadUtil;
import com.zcxk.dto.MaintainerCountDto;
import com.zcxk.dto.UserListDto;
import com.zcxk.entity.MenuEntity;
import com.zcxk.logAdvice.LogAnnotation;
import com.zcxk.model.AjaxMessage;
import com.zcxk.model.LoginUser;
import com.zcxk.model.Pagination;
import com.zcxk.model.ResultStatus;
import com.zcxk.service.MenuService;
import com.zcxk.util.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.*;
import java.io.IOException;

import org.springframework.web.bind.annotation.*;
import com.zcxk.entity.UserEntity;
import com.zcxk.service.UserService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户页面控制器
 * @author WYY
 * @date 2020-10-22 17:35
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    @Value("${UMIS.sys_config_path}")
    private String baseDir;

    @ApiOperation(value = "分页查询用户信息(按参数)")
    @RequestMapping(value = "/selectPageByParm", method = RequestMethod.POST)
    public AjaxMessage<Pagination<UserEntity>> list(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam(value = "contion", required = false) String contion, @RequestParam(value = "deptId", required = false) Long deptId) {
        IPage<UserEntity> iPage = new Page<>(pageNum, pageSize);
        UserEntity userEntity = new UserEntity();
        if (contion != null && contion != "") {
            userEntity.setUsername(contion.trim());
            userEntity.setPhone(contion.trim());
        }
        userEntity.setCompanyOrgId(deptId);
        userEntity.setDeptOrgId(deptId);
        iPage = userService.findPage(iPage, userEntity);

        Pagination<UserEntity> pages = new Pagination<>(iPage);
        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    @ApiOperation(value = "分页查询用户信息")
    @RequestMapping(value = "/selectPage", method = RequestMethod.POST)
    public AjaxMessage<Pagination<UserEntity>> selectPageByParm(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @ApiParam(value = "", required = false) @RequestBody UserEntity userEntity) {
        IPage<UserEntity> iPage = new Page<>(pageNum, pageSize);
        iPage = userService.findPage(iPage, userEntity);
        Pagination<UserEntity> pages = new Pagination<>(iPage);
        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    /**
     * 查询
     */
    @ApiOperation(value = "获取当前登录用户信息")
    @RequestMapping(value = "/findLoginUserById", method = RequestMethod.POST)
    public AjaxMessage<UserEntity> findLoginUserById() {
        LoginUser currentUser = UserUtil.getCurrentUser();
        UserEntity userEntity = userService.findUserById(Long.valueOf(currentUser.getId()));
        return new AjaxMessage<>(ResultStatus.OK, userEntity);
    }

    /**
     * 查询
     */
    @ApiOperation(value = "按ID查询用户信息")
    @RequestMapping(value = "/findUserById", method = RequestMethod.POST)
    public AjaxMessage<UserEntity> findUserById(@ApiParam(value = "用户ID", required = true) @RequestParam Long id) {
        UserEntity userEntity = userService.findUserById(id);
        return new AjaxMessage<>(ResultStatus.OK, userEntity);
    }

    /**
     * 按用户查询一级菜单信息(入口菜单)
     */
    @ApiOperation(value = "查询用户一级菜单信息(入口菜单-用户)")
    @RequestMapping(value = "/findUserFirstMenu", method = RequestMethod.GET)
    public AjaxMessage<List<MenuEntity>> findUserFirstMenu() {

        List<MenuEntity> menuEntityList = menuService.findUserFirstMenu();
        return new AjaxMessage<>(ResultStatus.OK, menuEntityList);
    }

    /**
     * 按应用查询菜单信息(系统菜单-用户)
     */
    @ApiOperation(value = "查询应用菜单信息")
    @RequestMapping(value = "/findUserMenu", method = RequestMethod.GET)
    public AjaxMessage<List<MenuEntity>> findUserMenu(@ApiParam(value = "应用ID", required = true) @RequestParam String appId) {
        List<MenuEntity> menuEntityList = menuService.findUserMenu(appId);
        return new AjaxMessage<>(ResultStatus.OK, menuEntityList);
    }

    /**
     * 按应用查询菜单信息(所有租户菜单：isTenant=1)
     */
    @ApiOperation(value = "查询所有菜单信息")
    @RequestMapping(value = "/findTenantMenu", method = RequestMethod.GET)
    public AjaxMessage<List<MenuEntity>> findTenantMenu() {
        List<MenuEntity> menuEntityList = menuService.findTenantMenu();
        return new AjaxMessage<>(ResultStatus.OK, menuEntityList);
    }

    /**
     * 新增
     */
    @ApiOperation(value = "用户头像")
    @RequestMapping(value = "addUserPhoto", method = RequestMethod.POST)
    public AjaxMessage<String> addUserPhoto(@ApiParam(value = "用户头像", required = true) @RequestParam("avatarfile") MultipartFile file) {
        String avatar = "";
        if (!file.isEmpty()) {
            try {
                avatar = FileUploadUtil.uploadWeb(baseDir, file);
            } catch (IOException e) {
                return new AjaxMessage<>(ResultStatus.ERROR, e.getMessage());
            }
        }
        return new AjaxMessage<>(ResultStatus.OK, avatar);
    }

    /**
     * 新增
     */
    @LogAnnotation(module = "【用户管理】新增")
    @ApiOperation(value = "新增用户信息")
    @RequestMapping(value = "addUser", method = RequestMethod.POST)
    public AjaxMessage<Integer> addUser(@ApiParam(value = "用户信息", required = true) @RequestBody UserEntity user) {
        if (user.getPhone() != null) {
            boolean isExsit = userService.checkMobileUnique(user.getPhone());
            if (isExsit) {
                return new AjaxMessage<>(ResultStatus.MEMBER_TELPHONE_ALREADY_EXISTS, 0);
            }
        }
        LoginUser currentUser = UserUtil.getCurrentUser();
        if (currentUser != null) {
            user.setUpdateBy(currentUser.getUsername());
            user.setCreateBy(currentUser.getUsername());
            user.setDateCreate(new Date());
            user.setDateUpdate(new Date());
            user.setTenantId(currentUser.getTenantId());
        }
        user.setStatus(1);
        if (user.getDeptOrgId() != null && user.getDeptOrgId() == 0) {
            user.setDeptOrgId(null);
        }
        int result = userService.addUser(user) ? 1 : 0;
        return new AjaxMessage<>(ResultStatus.OK, result);
    }

    /**
     * 修改保存用户
     */
    @LogAnnotation(module = "【用户管理】修改")
    @ApiOperation(value = "更新用户信息")
    @RequestMapping(value = "/updateUserById", method = RequestMethod.POST)
    public AjaxMessage<Integer> editUser(@ApiParam(value = "用户信息", required = true) @RequestBody UserEntity user) {
        if (user.getPhone() != null) {
            boolean isExsit = userService.checkMobileUnique(user);
            if (isExsit) {
                return new AjaxMessage<>(ResultStatus.MEMBER_TELPHONE_ALREADY_EXISTS, 0);
            }
        }
        LoginUser currentUser = UserUtil.getCurrentUser();
        if (currentUser != null) {
            user.setUpdateBy(currentUser.getUsername());
            user.setDateUpdate(new Date());
            user.setTenantId(currentUser.getTenantId());
        }
        int result = userService.updateUserById(user) ? 1 : 0;
        return new AjaxMessage<>(ResultStatus.OK, result);
    }

    /**
     * 删除
     */
    @LogAnnotation(module = "【用户管理】批量删除")
    @ApiOperation(value = "按ID进行批量删除")
    @RequestMapping(value = "/deleteUserByIds", method = RequestMethod.POST)
    public AjaxMessage<Integer> deleteUserByIds(@ApiParam(value = "用户ID", required = true) @RequestBody Long[] ids) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        Integer userId = currentUser.getId();
        boolean isOk = true;
        for (Long id : ids) {
            if (userId.toString().equals(id.toString())) {
                isOk = false;
            }
        }
        //租户管理员不能删除限制
//        boolean isDelete = true;
//        for (Long id : ids) {
//            UserEntity userEntity = userService.findUserById(id);
//            if (userEntity.getUserType().equals("-999")) {
//                isDelete = false;
//            }
//        }
        if (!isOk) {
            return new AjaxMessage<>(ResultStatus.EXSIT_IS_ACCOUNT_ERROR, 0);
        }
//        if (!isDelete) {
//            return new AjaxMessage<>(ResultStatus.DELETE_IS_ACCOUNT_ERROR, 0);
//        }
        int result = userService.delUserByIds(ids) ? 1 : 0;
        return new AjaxMessage<>(ResultStatus.OK, result);
    }

    /**
     * 删除
     */
    @LogAnnotation(module = "【用户管理】单条删除")
    @ApiOperation(value = "按ID进行单个删除")
    @RequestMapping(value = "/deleteUserById", method = RequestMethod.POST)
    public AjaxMessage<Integer> deleteUserById(@ApiParam(value = "用户ID", required = true) @RequestParam Long id) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        Integer userId = currentUser.getId();
        System.out.println("userId" + userId);
        if (userId.toString().equals(id.toString())) {
            return new AjaxMessage<>(ResultStatus.EXSIT_IS_ACCOUNT_ERROR, 0);
        }
        //租户管理员不能删除限制
//        UserEntity userEntity = userService.findUserById(id);
//        if (userEntity.getUserType().equals("-999")) {
//            return new AjaxMessage<>(ResultStatus.DELETE_IS_ACCOUNT_ERROR, 0);
//        }
        int result = userService.delUserById(id) ? 1 : 0;
        return new AjaxMessage<>(ResultStatus.OK, result);
    }
    @RequestMapping(value = "/getUserIdsByOrgId", method = RequestMethod.POST)
    public List<Integer>getUserIdsByOrgId(String ids) {
        List list = JSONObject.parseObject(ids, List.class);
        List<Integer> result = userService.getUserIdsByOrgId(list);
        return result;
    }

    @RequestMapping(value = "/findUserIdsByOrgId", method = RequestMethod.GET)
    public AjaxMessage<List<UserEntity>> findUserIdsByOrgId(String ids) {
        List list = JSONObject.parseObject(ids, List.class);
        List<UserEntity> result = userService.findUserIdsByOrgId(list);
        return new AjaxMessage<>(ResultStatus.OK,result);
    }

    /**
     * 查询运维人员
     * @param ids
     * @return
     */
    @RequestMapping(value = "/findUserIdsByOrgIdAndType", method = RequestMethod.GET)
    public AjaxMessage<List<UserEntity>> findUserIdsByOrgIdAndType(String ids) {
        List list = JSONObject.parseObject(ids, List.class);
        List<UserEntity> result = userService.findUserIdsByOrgIdAndType(list);
        return new AjaxMessage<>(ResultStatus.OK,result);
    }

    @RequestMapping(value = "/findUserList", method = RequestMethod.GET)
    public AjaxMessage<List<UserListDto>> findUserList(Integer type) {
        List<UserListDto> userList = userService.findUserList(type);
        return new AjaxMessage<>(ResultStatus.OK,userList);
    }

    /**
     * 查询运维人员信息
     * @return
     */
    @RequestMapping(value = "/findUserListByType", method = RequestMethod.GET)
    public AjaxMessage<List<UserEntity>> findUserListByType() {
        List<UserEntity> userList = userService.findUserListBytype(3);
        return new AjaxMessage<>(ResultStatus.OK, userList);
    }


    @ApiOperation(value = "按公司 租户及用户类型查询所有用户信息")
    @RequestMapping(value = "/findAllUserList", method = RequestMethod.GET)
    public List<UserEntity> findAllUserList(
            @RequestParam(value = "companyOrgId", required = false) Integer companyOrgId,
            @RequestParam(value = "tenantId", required = false)String tenantId,
            @RequestParam(value = "type", required = false)Integer type){
        return userService.findAllUserList(companyOrgId, tenantId, type);
    }

    @RequestMapping(value = "/findUserIdsByUserIds", method = RequestMethod.POST)
    public List<UserEntity> findUserIdsByUserIds(Long[] ids) {
        List list = Arrays.asList(ids.clone());
        List<UserEntity> result = userService.findUserIdsByUserIds(list);
        return  result;
    }
    @ApiOperation(value = "获取登录用户所属机构及其上级机构用户信息")
    @RequestMapping(value = "/findUserIdsForOrg", method = RequestMethod.GET)
    public List<Long> findUserIdsForOrg() {
        List<Long> ids = new ArrayList<>();
        List<UserEntity> result = userService.findUserIdsForOrg();
        for (UserEntity item : result) {
            ids.add(item.getId());
        }
        return ids;
    }

    @ApiOperation(value = "查询拥有此机构权限的用户")
    @RequestMapping(value = "/findUserIdsByPermissonOrg", method = RequestMethod.POST)
    public List<Integer> findUserIdsByPermissonOrg(
            @RequestParam(value = "tenantId", required = false) String tenantId,
            @RequestParam(value = "companyOrgId", required = false)Integer companyOrgId,
            @RequestParam(value = "deptOrgId", required = false)Integer deptOrgId){
        return userService.findUserIdsByPermissonOrg(tenantId,companyOrgId,deptOrgId);
    }

    @ApiOperation(value = "查询运维人员数量情况")
    @RequestMapping(value = "/findMaintainer", method = RequestMethod.GET)
    public AjaxMessage<MaintainerCountDto> findMaintainer(
            @ApiParam(value = "开始时间", required = true) @RequestParam String startDate,
            @ApiParam(value = "结束时间", required = false) @RequestParam(required = false) String endDate,
            @ApiParam(value = "统计类型0按月、1按年、2自定义", required = true)@RequestParam Integer statsType) {
        MaintainerCountDto maintainerCountDto = userService.findMaintainer(startDate,endDate,statsType);
        return new AjaxMessage<>(ResultStatus.OK, maintainerCountDto);
    }

    @ApiOperation(value = "查询运维人员数量")
    @RequestMapping(value = "/findMaintainerCount", method = RequestMethod.GET)
    public Integer findMaintainerCount(
            @ApiParam(value = "结束时间(YYYY-MM)", required = true) @RequestParam String endDate) {
        return userService.findMaintainerCount(endDate);
    }

}
