package com.gxwebsoft.common.system.controller;

import cn.hutool.core.util.StrUtil;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.utils.CacheClient;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.AccessKey;
import com.gxwebsoft.common.system.param.AccessKeyParam;
import com.gxwebsoft.common.system.service.AccessKeyService;
import io.swagger.v3.oas.annotations.tags.Tag;

import java.util.concurrent.TimeUnit;

import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

import static com.gxwebsoft.common.core.constants.WebsiteConstants.CACHE_KEY_VERIFICATION_CODE_BY_DEV_SMS;

/**
 * 访问凭证管理控制器
 *
 * @author 科技小王子
 * @since 2023-05-16 19:19:55
 */
@Tag(name = "安全访问凭证")
@RestController
@RequestMapping("/api/system/access-key")
public class AccessKeyController extends BaseController {
  @Resource
  private AccessKeyService accessKeyService;
  @Resource
  private CacheClient cacheClient;
  @Resource
  private RedisUtil redisUtil;

  @PreAuthorize("hasAuthority('sys:accessKey:list')")
  @OperationLog
  @Operation(summary = "分页查询访问凭证")
  @GetMapping("/page")
  public ApiResult<PageResult<AccessKey>> page(AccessKeyParam param) {
    // 使用关联查询
    final PageResult<AccessKey> accessKeyPageResult = accessKeyService.pageRel(param);
    if (param.getCode() != null) {
      // 短信验证码校验
      final String code = param.getCode();
      // 验证码校验
      String key = "code:" + param.getPhone();
      if (!code.equals(redisUtil.get(key)) && !redisUtil.get(CACHE_KEY_VERIFICATION_CODE_BY_DEV_SMS).equals(code)) {
        String message = "验证码不正确";
        return fail(message, null);
      }
      return success(accessKeyPageResult);
    }
    // 默认不给查看AccessSecret
    accessKeyPageResult.getList().forEach(d -> {
      d.setAccessSecret(null);
    });
    return success(accessKeyPageResult);
  }

  @PreAuthorize("hasAuthority('sys:accessKey:list')")
  @OperationLog
  @Operation(summary = "查询全部访问凭证管理")
  @GetMapping()
  public ApiResult<List<AccessKey>> list(AccessKeyParam param) {
    PageParam<AccessKey, AccessKeyParam> page = new PageParam<>(param);
    page.setDefaultOrder("create_time desc");
    return success(accessKeyService.list(page.getOrderWrapper()));
    // 使用关联查询
    //return success(accessKeyService.listRel(param));
  }

  @PreAuthorize("hasAuthority('sys:accessKey:list')")
  @OperationLog
  @Operation(summary = "根据id查询访问凭证管理")
  @GetMapping("/{id}")
  public ApiResult<AccessKey> get(@PathVariable("id") Integer id) {
    return success(accessKeyService.getById(id));
    // 使用关联查询
    //return success(accessKeyService.getByIdRel(id));
  }

  @PreAuthorize("hasAuthority('sys:accessKey:list')")
  @OperationLog
  @Operation(summary = "添加访问凭证管理")
  @PostMapping()
  public ApiResult<?> save(@RequestBody AccessKey accessKey) {
    final int count = accessKeyService.count();
    if (count >= 5) {
      return fail("当前账号只能绑定 5 个 AccessKey");
    }
    if(accessKey.getAccessKey() == null){
      accessKey.setAccessKey(CommonUtil.randomUUID16());
    }
    accessKey.setAccessSecret("sk-" + CommonUtil.randomUUID16().concat(CommonUtil.randomUUID16()));
    if (accessKeyService.save(accessKey)) {
      return success("创建成功", accessKey);
    }
    return fail("创建失败");
  }

  @PreAuthorize("hasAuthority('sys:accessKey:update')")
  @OperationLog
  @Operation(summary = "修改访问凭证管理")
  @PutMapping()
  public ApiResult<?> update(@RequestBody AccessKey accessKey) {
    if (accessKeyService.updateById(accessKey)) {
      return success("修改成功");
    }
    return fail("修改失败");
  }

  @PreAuthorize("hasAuthority('sys:accessKey:remove')")
  @OperationLog
  @Operation(summary = "删除访问凭证管理")
  @DeleteMapping("/{id}")
  public ApiResult<?> remove(@PathVariable("id") Integer id) {
    if (accessKeyService.removeById(id)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }

  @PreAuthorize("hasAuthority('sys:accessKey:save')")
  @OperationLog
  @Operation(summary = "批量添加访问凭证管理")
  @PostMapping("/batch")
  public ApiResult<?> saveBatch(@RequestBody List<AccessKey> list) {
    if (accessKeyService.saveBatch(list)) {
      return success("添加成功");
    }
    return fail("添加失败");
  }

  @PreAuthorize("hasAuthority('sys:accessKey:update')")
  @OperationLog
  @Operation(summary = "批量修改访问凭证管理")
  @PutMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody BatchParam<AccessKey> batchParam) {
    if (batchParam.update(accessKeyService, "id")) {
      return success("修改成功");
    }
    return fail("修改失败");
  }

  @PreAuthorize("hasAuthority('sys:accessKey:remove')")
  @OperationLog
  @Operation(summary = "批量删除访问凭证管理")
  @DeleteMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
    if (accessKeyService.removeByIds(ids)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }

  @PreAuthorize("hasAuthority('sys:accessKey:resetSMSCode')")
  @OperationLog
  @Operation(summary = "重置万能短信验证码")
  @PostMapping("/resetSMSCode")
  public ApiResult<?> resetSMSCode() {
    // 生成短信验证码
    Random randObj = new Random();
    String code = Integer.toString(100000 + randObj.nextInt(900000));
    redisUtil.set(CACHE_KEY_VERIFICATION_CODE_BY_DEV_SMS, code, 5L, TimeUnit.MINUTES);
    return success("新验证码：".concat(code));
  }


}
