package com.platform.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.platform.annotation.SysLog;
import com.platform.entity.SysDeptEntity;
import com.platform.entity.SysRoleEntity;
import com.platform.entity.SysUserEntity;
import com.platform.enums.SysRoleEnum;
import com.platform.service.SysRoleService;
import com.platform.service.SysUserRoleService;
import com.platform.service.SysUserService;
import com.platform.service.custom.MySysUserBrandService;
import com.platform.service.impl.SysDeptServiceImpl;
import com.platform.utils.*;
import com.platform.validator.Assert;
import com.platform.validator.ValidatorUtils;
import com.platform.validator.group.AddGroup;
import com.platform.validator.group.UpdateGroup;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统用户
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2016年10月31日 上午10:40:10
 */
@RestController
@RequestMapping("/sys/user")
@Slf4j
public class SysUserController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleService sysRoleService;


    @Autowired
    private MySysUserBrandService mySysUserBrandService;

    @Autowired
    private SysDeptServiceImpl sysDeptService;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${scenePath}")
    private String scenePath;


    /**
     * 店铺绑定的用户列表
     */
    @GetMapping("/bindList")
    @RequiresPermissions("sys:user:list")
    public R userBindList(@RequestParam(name = "deptId") long deptId,
                          String key,
                          @RequestParam(name = "brandId") long brandId,
                          @RequestParam(name = "pageNum") long pageNum,
                          @RequestParam(name = "pageSize") long pageSize) {

        IPage<SysUserEntity> resultPage = sysUserService.getSysUserList(sysDeptService.getSubDeptIdLongList(deptId), key,
                brandId , pageNum, pageSize);
        if (null == resultPage) {
            return R.error("获取用户列表失败");
        }
        resultPage.getRecords().parallelStream().forEach(user->{
            if (!ObjectUtils.isEmpty(user.getIsPlatformStreamer()) && user.getIsPlatformStreamer()) {
                user.setRoleName("平台主持人");
            }
        });
        return R.ok(CommonDataUtils.assembleResult(resultPage.getTotal(), resultPage.getPages()
                , resultPage.getCurrent(), resultPage.getRecords()));
    }

    /**
     * 所有管理员列表
     */
    @GetMapping("/list")
    @RequiresPermissions("sys:user:list")
    public R list(@RequestParam Map<String, Object> params) {
        //只有超级管理员，才能查看所有管理员列表
        if (getUserId() != Constant.SUPER_ADMIN) {
            params.put("deptIdList", sysDeptService.getSubDeptIdList(getDeptId()));
        }
        //查询列表数据
        Query query = new Query(params);
        List<SysUserEntity> userList = sysUserService.queryList(query);
        int total = sysUserService.queryTotal(query);
        userList.parallelStream().forEach(userEntity -> {
                    List<SysRoleEntity> curRoleList = new ArrayList<>();
                    if (!ObjectUtils.isEmpty(userEntity.getIsPlatformStreamer()) && userEntity.getIsPlatformStreamer()) {
                        SysRoleEntity sysRoleEntity = new SysRoleEntity();
                        sysRoleEntity.setRoleName("平台主持人");
                        curRoleList.add(sysRoleEntity);
                    } else {
                        curRoleList = sysRoleService.queryListByUserId(userEntity.getUserId());
                    }
                    userEntity.setRoleList(curRoleList);
                }
        );
        PageUtils pageUtil = new PageUtils(userList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 员工列表
     */
    @ApiOperation("员工列表")
    @GetMapping("/staffList")
    @RequiresPermissions("sys:user:list")
    public R staffList(String staffName,
                       @RequestParam(name = "pageNum") long pageNum,
                       @RequestParam(name = "pageSize") long pageSize,
                       @RequestParam(name = "deptName",required = false) String deptName,
                       @RequestParam(name = "deptId") long deptId) {

        IPage<SysUserEntity> resultPage = null;

        if (getUserId() != Constant.SUPER_ADMIN) {
            //非系统管理员，需要踢掉超级管理员
            resultPage = sysUserService.getCompanyStaffList(staffName, deptName,
                    pageNum, pageSize , deptId , true);
        }else{
            //只有超级管理员才有权限查看自己的数据
            resultPage = sysUserService.getCompanyStaffList(staffName, deptName,
                    pageNum, pageSize , null , false);
        }

        if (null == resultPage) {
            return R.error("获取员工列表失败");
        }
        return R.ok(CommonDataUtils.assembleResult(resultPage.getTotal(), resultPage.getPages()
                , resultPage.getCurrent(), resultPage.getRecords()));
    }

    @ApiOperation("检验用户是否是四维看看的用户")
    @ResponseBody
    @GetMapping(value = "/checkUser")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNum", value = "手机号码", dataType = "String"),
    })
    public R getBrandCommentList(@RequestParam(name = "phoneNum") String phoneNum) {

        if (StringUtils.isNullOrEmpty(phoneNum)) {
            return R.error("缺少手机号码");
        }
        Map<String, Object> mp = new HashMap<>();
        mp.put("phone", phoneNum);
        String url = scenePath + "user/checkUserExists";
        ResponseEntity<String> kankanResult = restTemplate.postForEntity(url, mp,String.class);
        //解析返回结果
        JSONObject res = JSONObject.parseObject(kankanResult.getBody());
        log.info("四维看看返回登录数据:{}", res.toJSONString());
        if (!res.containsKey("code")) {
            return R.error("系统故障，请稍后重试");
        }
        Boolean exist = res.getBoolean("message");
        if (!exist) {
            return R.error("用户不存在!");
        }
        return R.ok();
    }

    /**
     * 获取登录的用户信息
     */
    @GetMapping("/info")
    public R info() {
        return R.ok().put("user", getUser());
    }

    /**
     * 修改登录用户密码
     */
    @SysLog("修改密码")
    @PostMapping("/bind4dkkUser")
    public R password(String fdkkPassword, String fdkkUser) {
        Assert.isBlank(fdkkUser, "手机号不为能空");
        Assert.isBlank(fdkkPassword, "4d看看密码不为能空");
        //更新密码
        sysUserService.updatePassword(getUser().getMobile(), null, fdkkPassword, fdkkUser);
        return R.ok();
    }

    /**
     * 修改登录用户密码
     */
    @SysLog("修改密码")
    @PostMapping("/unBind4dkkUser")
    public R unBind4dkkUser(String fdkkUser) {
        Assert.isBlank(fdkkUser, "手机号不为能空");
        //更新密码
        sysUserService.updatePassword(getUser().getMobile(), null, null, fdkkUser);
        return R.ok();
    }

    /**
     * 用户信息
     */
    @GetMapping("/info/{userId}")
    @RequiresPermissions("sys:user:info")
    public R info(@PathVariable("userId") Long userId) {
        SysUserEntity user = sysUserService.queryObject(userId);

        //获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        user.setRoleIdList(roleIdList);

        return R.ok().put("user", user);
    }

    @GetMapping("/infoAnon/{userId}")
    @ResponseBody
    public R infoAnon(@PathVariable("userId") Long userId) {
        SysUserEntity user = sysUserService.queryObject(userId);
        user.setPassword(null);
        //获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        if (null != roleIdList) {
            user.setRoleIdList(roleIdList);
        }

        return R.ok().put("user", user);
    }

    /**
     * 保存用户
     */
    @SysLog("保存用户")
    @PostMapping("/save")
    @RequiresPermissions("sys:user:save")
    public R save(@ApiParam(name = "SysUserEntity对象", value = "传入json格式", required = true) @RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, AddGroup.class);

        SysUserEntity sysUserEntity = sysUserService.queryByUserMobile(user.getMobile());
        if(null != sysUserEntity){
            return R.error("员工已经存在，请勿重复添加");
        }

        user.setCreateUserId(getUserId());

        // 如果是平台主持人，则设置为公司员工
        if(user.getRoleIdList().contains(SysRoleEnum.PLATFORM_STREAMER.getCode())){
            user.setIsPlatformStreamer(true);
            user.setRoleIdList(Collections.singletonList(8L));
        }
        sysUserService.save(user);
        return R.ok();
    }



    @ApiOperation(value = "新增员工接口")
    @SysLog("新增员工接口")
    @PostMapping("/staffSave")
    @RequiresPermissions("sys:user:save")
    @Transactional(rollbackFor = Exception.class)
    public R staffSave(@ApiParam(name = "SysUserEntity对象", value = "传入json格式", required = true) @RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, AddGroup.class);
        if(null == user.getDeptId()){
            return R.error("缺失公司数据！");
        }
        if(ObjectUtils.isEmpty(user.getRoleId())){
            return R.error("角色为空！");
        }

        //TODO:这里需要改成select for update
        SysDeptEntity sysDeptEntity = sysDeptService.queryObject(user.getDeptId());
        if(null == sysDeptEntity){
            return R.error("公司不存在！");
        }
        int curStaffNum = null != sysDeptEntity.getCurStaffNum() ? sysDeptEntity.getCurStaffNum() : 0;
        int maxStaffNum = null != sysDeptEntity.getStaffNum() ? sysDeptEntity.getStaffNum() : 0;
        if((curStaffNum + 1) > maxStaffNum){
            return R.error("公司员工已经达到上限！");
        }

        user.setCreateUserId(getUserId());

        SysUserEntity sysUserEntity = sysUserService.queryByUserMobile(user.getMobile());
        if(null != sysUserEntity){
            return R.error("员工已经存在，请勿重复添加！");
        }
        //创建用户，并且创建用户和角色的关联关系
        sysUserService.save(user);

        //给相应的部门增加相应的员工数
        if(null == sysDeptEntity.getCurStaffNum()){
            sysDeptEntity.setCurStaffNum(1);
        }else{
            sysDeptEntity.setCurStaffNum(curStaffNum + 1);
        }

        sysDeptService.update(sysDeptEntity);

        return R.ok();
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @PostMapping("/update")
    @RequiresPermissions("sys:user:update")
    public R update(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);
        sysUserService.update(user);
        return R.ok();
    }

    @ApiOperation(value = "删除员工")
    @SysLog("删除员工")
    @PostMapping("/preDeleteStaff")
    @RequiresPermissions("sys:user:delete")
    @Transactional(rollbackFor = Exception.class)
    public R preDeleteStaff(@RequestBody Map<String,Long> params) {
        Long userId = params.get("userId");
        if(ObjectUtils.isEmpty(userId)){
            return R.error("参数有误！");
        }
        if (userId.equals(-1L)) {
            return R.error("不能删除平台管理员");
        }
        if (getUserId().equals(userId)) {
            return R.error("当前用户不能删除");
        }

        SysUserEntity sysUserEntity = sysUserService.queryObject(userId);
        if(ObjectUtils.isEmpty(sysUserEntity)){
            return R.error("获取用户信息失败！");
        }

        List<Long> roleList = sysUserRoleService.queryRoleIdList(userId);
        if(!CollectionUtils.isEmpty(roleList) && (roleList.contains(6) || roleList.contains(5))){
            return R.error("不能删除平台管理员或者普通管理员");
        }

        Long deptId = sysUserEntity.getDeptId();
        if(!ObjectUtils.isEmpty(deptId)){
            // 更新企业员工信息
            long num = sysUserService.getUserNumOfDept(deptId);
            if(num <= 1){
                return R.error("删除失败，公司仅剩一个账号");
            }
            // 获取直播间绑定信息
            List<Long> bindUsers = mySysUserBrandService.queryBrandIdList(userId);
            if (!ObjectUtils.isEmpty(bindUsers)) {
                // 获取该公司下管理员手机号
                List<SysUserEntity> userEntities = sysUserService.getSysUserListByDeptIds(Arrays.asList(deptId));
                List<String> phones = userEntities.stream().filter(user -> !user.getUserId().equals(userId))
                        .map(SysUserEntity::getMobile).collect(Collectors.toList());
                if(ObjectUtils.isEmpty(phones)){
                    return R.error("删除失败，公司仅剩一名员工，不可进行删除！");
                }
                return R.ok().put("list", phones);
            }
        }
        return R.ok();
    }

    @ApiOperation(value = "删除员工")
    @SysLog("删除员工")
    @PostMapping("/deleteStaff")
    @RequiresPermissions("sys:user:delete")
    @Transactional(rollbackFor = Exception.class)
    public R deleteStaff(@RequestBody Map<String,String> params) {
        Long userId = Long.parseLong(params.get("userId"));
        String toUser = params.get("toUser");
        if(ObjectUtils.isEmpty(userId)){
            return R.error("参数有误！");
        }
        if (userId.equals(-1L)) {
            return R.error("不能删除平台管理员");
        }
        if (getUserId().equals(userId)) {
            return R.error("当前用户不能删除");
        }

        SysUserEntity sysUserEntity = sysUserService.queryObject(userId);
        if(ObjectUtils.isEmpty(sysUserEntity)){
            return R.error("获取用户信息失败！");
        }

        List<Long> roleList = sysUserRoleService.queryRoleIdList(userId);
        if (!CollectionUtils.isEmpty(roleList) && roleList.contains(5)) {
            return R.error("不能删除平台管理员");
        }

        // 获取情景信息
        List<Long> bindUsers = mySysUserBrandService.queryBrandIdList(userId);
        SysUserEntity toUserEntity = null;

        if (!ObjectUtils.isEmpty(bindUsers)) {
            if (ObjectUtils.isEmpty(toUser)) {
                return R.error("没有配置分配用户信息！");
            }
            toUserEntity = sysUserService.queryByUserMobile(toUser);
            if (ObjectUtils.isEmpty(toUserEntity)) {
                return R.error("分配用户有误！");
            }
        }

        // 更新企业员工信息
        Long deptId = sysUserEntity.getDeptId();
        if(!ObjectUtils.isEmpty(deptId)){
           long num = sysUserService.getUserNumOfDept(deptId);
           if(num <= 1){
               return R.error("删除失败，公司仅剩一名员工，不可进行删除");
           }
           SysDeptEntity sysDeptEntity = sysDeptService.queryObject(deptId);
           if(!ObjectUtils.isEmpty(sysDeptEntity)){
               sysDeptEntity.setCurStaffNum(Long.valueOf(num - 1).intValue());
               sysDeptService.update(sysDeptEntity);
           }
        }

        // 重新绑定直播间
        if(!ObjectUtils.isEmpty(toUserEntity)){
            mySysUserBrandService.reBindUser(userId,toUserEntity);
        }

        // 删除用户信息
        sysUserService.deleteBatch(new Long[]{userId});
        return R.ok();
    }
}
