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.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.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

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

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

    @PreAuthorize("hasAuthority('sys:accessKey:list')")
    @OperationLog
    @ApiOperation("查询全部访问凭证管理")
    @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
    @ApiOperation("根据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
    @ApiOperation("添加访问凭证管理")
    @PostMapping()
    public ApiResult<?> save(@RequestBody AccessKey accessKey) {
      final int count = accessKeyService.count();
      if (count >= 5) {
        return fail("当前账号只能绑定 5 个 AccessKey");
      }
      accessKey.setAccessKey("AI" + CommonUtil.randomUUID16());
      accessKey.setAccessSecret(CommonUtil.randomUUID16().concat(CommonUtil.randomUUID16()));
      if (accessKeyService.save(accessKey)) {
          return success("创建成功");
      }
      return fail("创建失败");
    }

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

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

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

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

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

}
