/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.platform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.vo.UserPointsVO;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.R;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.security.comment.constants.SecurityConstants;
import com.yami.shop.security.comment.enums.App;
import com.yami.shop.security.comment.service.AppConnectService;
import com.yami.shop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;


/**
 * 用户信息管理实现
 *
 * @author lgh
 * @version 1.0.0
 * @since 2018-10-16
 */
@RestController
@RequestMapping("/admin/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AppConnectService appConnectService;

    @Autowired
    private TokenStore tokenStore;

    @GetMapping("/userList")
    public R<IPage<User>> userList(User user,PageParam<User> page) {
        return R.SUCCESS(userService.userList(page,user));
    }

    /**
     * 分页获取
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('plateform:user:page')")
    public R<IPage<User>> page(User user,PageParam<User> page) {
//        IPage<User> userPage = userService.page(page, new LambdaQueryWrapper<User>()
//                .like(StrUtil.isNotBlank(user.getNickName()), User::getNickName, user.getNickName())
//                .eq(user.getStatus() != null, User::getStatus, user.getStatus())
//                .isNotNull(User::getNickName)
//                .orderByDesc(User::getUserRegtime));
        IPage<User> userPage =  userService.getUserPage(page,user);
//        for (User userResult : userPage.getRecords()) {
//            userResult.setNickName(userResult.getNickName());
//        }
        return R.SUCCESS(userPage);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{userId}")
    @PreAuthorize("@pms.hasPermission('plateform:user:info')")
    public R<User> info(@PathVariable("userId") String userId) {
        User user = userService.getById(userId);
        user.setNickName(user.getNickName());
        return R.SUCCESS(user);
    }

    /**
     * 修改
     */
    @PutMapping
    @PreAuthorize("@pms.hasPermission('plateform:user:update')")
    public R<Void> update(@RequestBody User user) {
        user.setModifyTime(new Date());
        user.setNickName(user.getNickName());
        userService.updateById(user);
        List<Integer> appTypes = App.listAppType();
        for (Integer appType : appTypes) {
            Collection<OAuth2AccessToken> tokensByClientIdAndUserName = tokenStore.findTokensByClientIdAndUserName(String.valueOf(appType),user.getUserId());
            Map<String, String> values = new LinkedHashMap<>();
            values.put("username", user.getUserId());
            values.put("client_id", String.valueOf(appType));
            values.put("scope", "");
            String key = SecurityConstants.YAMI_OAUTH_PREFIX + "auth_to_access:" + generateKey(values);
            RedisUtil.del(key);
            for (OAuth2AccessToken oAuth2AccessToken : tokensByClientIdAndUserName) {
                RedisUtil.del(SecurityConstants.YAMI_OAUTH_PREFIX + "access:" + oAuth2AccessToken.getValue());
            }
        }
        return R.SUCCESS();
    }



    private String generateKey(Map<String, String> values) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
            byte[] bytes = digest.digest(values.toString().getBytes(StandardCharsets.UTF_8));
            return String.format("%032x", new BigInteger(1, bytes));
        } catch (NoSuchAlgorithmException nsae) {
            throw new IllegalStateException("MD5 algorithm not available.  Fatal (should be in the JDK).", nsae);
        }
    }


    /**
     * 员工列表-积分统计
     */
    @GetMapping("/statisticsList")
    public R<IPage<UserPointsVO>> statisticsList(PageParam<User> pageParam, User user) {
        IPage<UserPointsVO> page = userService.statisticsList(pageParam, user);
        return R.SUCCESS(page);
    }
}
