package com.system.oauth.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.system.framework.core.config.MinioTemplate;
import com.system.framework.core.response.StarBosResult;
import com.system.oauth.system.entity.UserMessage;
import com.system.oauth.system.model.RegisterModel;
import com.system.oauth.system.service.IUserMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Objects;

@Slf4j
@RestController
@Api(tags = "用户信息管理")
@RequestMapping("/message")
//@CrossOrigin
public class UserMessageController {

    @Autowired
    private IUserMessageService userMessageService;

    @Autowired
    private MinioTemplate minioTemplate;

    @GetMapping("list")
    @ApiOperation(value = "用户信息管理-分页列表查询", httpMethod = "GET", produces = "", notes = "用户信息管理-分页列表查询")
    public StarBosResult<IPage<UserMessage>> list(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        StarBosResult<IPage<UserMessage>> result = new StarBosResult<IPage<UserMessage>>();
        Page<UserMessage> page = new Page<UserMessage>(pageNo, pageSize);
        IPage<UserMessage> pageList = userMessageService.page(page, null);
        result.setCode(200);
        result.setData(pageList);
        return result;
    }

    @ApiOperation(value = "用户信息管理-添加用户", httpMethod = "POST", produces = "", notes = "用户信息管理-添加用户")
    @PostMapping("/add")
    public StarBosResult<?> register(@Valid @RequestBody RegisterModel param) {
        log.info("\r\n" + param);
        // 1. 保存账户信息
        Long uid = userMessageService.save(param);

        return StarBosResult.ok(uid, "新增成功");
    }

    /**
     * 编辑
     *
     * @param userMessage
     * @return
     */
    @ApiOperation(value = "用户信息管理-编辑用户", httpMethod = "PUT", produces = "", notes = "用户信息管理-编辑用户")
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public StarBosResult<UserMessage> edit(@RequestBody UserMessage userMessage, @RequestParam(name = "file", required = false) MultipartFile file) {
        log.info("\r\n" + userMessage);
        StarBosResult<UserMessage> result = new StarBosResult<UserMessage>();
        try {
            UserMessage sysrole = userMessageService.getById(userMessage.getUserId());
            if (sysrole == null) {
                result.error500("未找到对应实体");
            } else {
                /**
                 *上传到sso文件服务器
                 *获取访问url
                 */
                if (!Objects.isNull(file)) {
                    String url = minioTemplate.uploadMultipartFileAndGetUrl(file);
                    userMessage.setAvatar(url);
                }
                userMessageService.editUserWithRole(userMessage);
                //TODO 返回false说明什么？
                result.success("修改成功!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param userId
     * @return
     */
    @DeleteMapping(value = "/delete")
    @ApiOperation(value = "删除用户", httpMethod = "DELETE", produces = "", notes = "删除用户")
    public StarBosResult<?> delete(@RequestParam(name = "userId", required = true) Long userId) {
        StarBosResult result = new StarBosResult<>();
        try {
            userMessageService.remove(userId);
//            return StarBosResult.ok("");
            result.success("删除角色成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    //    @RequestMapping("/parse")
    public Object parse(Authentication authentication) {  //解析jwt
        OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) authentication.getDetails();
        String token = oAuth2AuthenticationDetails.getTokenValue();
        System.out.println(token);
        Jwt jwt = JwtHelper.decode(token);
        String claims = jwt.getClaims();
        jwt.getClaims();
        String encoded = jwt.getEncoded();
        System.out.println("claims 原始信息：" + claims);       //获取原始信息json字符串
        System.out.println("access token编码信息：" + encoded); //获取编码后的字符串
        JSONObject fromObject = JSONObject.fromObject(claims);//转换数据类型
        Object authorities = fromObject.get("authorities");
        return fromObject;
    }

    /**
     * showMember
     *
     * @return
     */
//    @PreAuthorize("hasAuthority('showMember')")
//    @RequestMapping("/showMember")
    public String showMember() {
        //获取用户身份信息
        Object userDetails = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        JSONObject fromObject = JSONObject.fromObject(userDetails);//转换数据类型
        fromObject.get("id");
        return fromObject.get("id") + "";
    }
}