package com.jd.lightapplication.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jd.lightapplication.common.dto.PassDto;
import com.jd.lightapplication.common.lang.Const;
import com.jd.lightapplication.common.lang.R;
import com.jd.lightapplication.easemob.EasemobComtroller;
import com.jd.lightapplication.easemob.dto.SetUserAttributeDto;
import com.jd.lightapplication.model.SysRole;
import com.jd.lightapplication.model.SysUser;
import com.jd.lightapplication.model.SysUserRole;
import com.jd.lightapplication.model.dto.SysUserQueryDto;
import com.jd.lightapplication.model.dto.SysUserUpdateDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author WaiterXiaoYY
 * @since 2022-01-13
 */
@RestController
@RequestMapping("/sys/user")
@Slf4j
public class SysUserController extends BaseController {

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Autowired
    EasemobComtroller easemobComtroller;

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public R info(@PathVariable("id") Long id) {

        SysUser sysUser = sysUserService.getById(id);
        Assert.notNull(sysUser, "找不到该管理员");

        List<SysRole> roles = sysRoleService.listRolesByUserId(id);

        sysUser.setSysRoles(roles);
        return R.success(sysUser);
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public R list(Page page, String username) {

        Page<SysUser> pageData = sysUserService.page(page, new QueryWrapper<SysUser>()
                .like(StrUtil.isNotBlank(username), "username", username));

        pageData.getRecords().forEach(u -> {

            u.setSysRoles(sysRoleService.listRolesByUserId(u.getId()));
        });

        return R.success(pageData);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:user:save')")
    public R save(@Validated @RequestBody SysUser sysUser) {

        sysUser.setCreated(DateUtil.now());
        //sysUser.setStatu(Const.STATUS_ON);

        // 默认密码
        String password = passwordEncoder.encode(Const.DEFULT_PASSWORD);
        sysUser.setPassword(password);

        // 默认头像
        sysUser.setAvatar(Const.DEFULT_AVATAR);

        sysUserService.save(sysUser);
        return R.success(sysUser);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public R update(@Validated @RequestBody SysUser sysUser) {

        sysUser.setUpdated(DateUtil.now());

        sysUserService.updateById(sysUser);
        return R.success(sysUser);
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public R delete(@RequestBody Long[] ids) {

        sysUserService.removeByIds(Arrays.asList(ids));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id", ids));

        return R.success("");
    }

    @Transactional
    @PostMapping("/role/{userId}")
    @PreAuthorize("hasAuthority('sys:user:role')")
    public R rolePerm(@PathVariable("userId") Long userId, @RequestBody Long[] roleIds) {

        List<SysUserRole> userRoles = new ArrayList<>();

        Arrays.stream(roleIds).forEach(r -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(r);
            sysUserRole.setUserId(userId);

            userRoles.add(sysUserRole);
        });

        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        sysUserRoleService.saveBatch(userRoles);

        // 删除缓存
        SysUser sysUser = sysUserService.getById(userId);
        sysUserService.clearUserAuthorityInfo(sysUser.getUsername());

        return R.success("");
    }

    @PostMapping("/repass")
    @PreAuthorize("hasAuthority('sys:user:repass')")
    public R repass(@RequestBody Long userId) {

        SysUser sysUser = sysUserService.getById(userId);

        sysUser.setPassword(passwordEncoder.encode(Const.DEFULT_PASSWORD));
        sysUser.setUpdated(DateUtil.now());

        sysUserService.updateById(sysUser);
        return R.success("");
    }

    @PostMapping("/updatePass")
    public R updatePass(@Validated @RequestBody PassDto passDto, Principal principal) {

        SysUser sysUser = sysUserService.getByUsername(principal.getName());

        boolean matches = passwordEncoder.matches(passDto.getCurrentPass(), sysUser.getPassword());
        if (!matches) {
            return R.fail("旧密码不正确");
        }

        sysUser.setPassword(passwordEncoder.encode(passDto.getPassword()));
        sysUser.setUpdated(DateUtil.now());

        sysUserService.updateById(sysUser);
        return R.success("");
    }

    /**
     * 查询所有来宾用户
     *
     * @return
     */
    @GetMapping("/queryGuest")
    public R queryGuest(Page page, SysUserQueryDto sysUserQueryDto) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(sysUserQueryDto.getUsernameShow())) {
            wrapper.like(SysUser::getUsernameShow, sysUserQueryDto.getUsernameShow());
        }
        if (StrUtil.isNotBlank(sysUserQueryDto.getPhone())) {
            wrapper.like(SysUser::getPhone, sysUserQueryDto.getPhone());
        }
        wrapper.isNull(SysUser::getPassword);
        return R.success(sysUserService.page(page, wrapper));
    }

    @PostMapping("/updateNoAuth")
    public R updateNoAuth(@RequestBody SysUserUpdateDto sysUserUpdateDto) {
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(sysUserUpdateDto, sysUser);
        sysUser.setUpdated(DateUtil.now());
        sysUserService.updateById(sysUser);
        //先查出用户数据，再设置环信用户属性
        sysUser = sysUserService.getById(sysUserUpdateDto.getId());
        SetUserAttributeDto setUserAttributeDto = new SetUserAttributeDto()
                .setUsername(sysUser.getPhone())
                .setNickname(sysUser.getNickName())
                .setPhone(sysUser.getPhone())
                .setAvatarurl(sysUser.getHeadImgUrl());
        JSONObject jsonObject = (JSONObject) easemobComtroller.setUpUserAttribute(setUserAttributeDto).getData();
        String data = jsonObject.getStr("data");
        log.debug("设置环信用户属性(data为空表示设置失败)data=" + data);
        return R.success(sysUser);
    }

}
