package com.gxwebsoft.open.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.utils.CacheClient;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.oa.entity.App;
import com.gxwebsoft.oa.entity.AppUser;
import com.gxwebsoft.oa.param.AppParam;
import com.gxwebsoft.oa.param.AppUserParam;
import com.gxwebsoft.oa.service.AppService;
import com.gxwebsoft.oa.service.AppUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

import static com.gxwebsoft.common.core.constants.RedisConstants.USER_RANKING_BY_APPS;

/**
 * 应用控制器
 *
 * @author WebSoft
 * @since 2022-11-18 13:55:29
 */
@Api(tags = "应用管理")
@RestController
@RequestMapping("/api/open/app")
public class OpenAppController extends BaseController {
    @Resource
    private AppService appService;
    @Resource
    private AppUserService appUserService;
    @Resource
    private CacheClient cacheClient;

    @ApiOperation("分页查询应用")
    @GetMapping("/page")
    public ApiResult<PageResult<App>> page(AppParam param) {
        // 验证签名
        isCheckSign();
        // 非管理员仅显示已加入成员管理的应用列表
        User loginUser = getLoginUser();
        if(!loginUser.getUsername().equals("admin")){
          param.setUserId(getLoginUserId());
        }
        param.setTenantId(getTenantId());
        // 使用关联查询
        return success(appService.pageRel(param));
    }

    @ApiOperation("查询全部应用")
    @GetMapping()
    public ApiResult<List<App>> list(AppParam param) {
        // 验证签名
        isCheckSign();
        param.setUserId(getLoginUserId());
        param.setTenantId(getTenantId());
        // 使用关联查询
        return success(appService.listRel(param));
    }

    @ApiOperation("根据id查询应用")
    @GetMapping("/{id}")
    public ApiResult<App> get(@PathVariable("id") Integer id) {
//        return success(appService.getById(id));
      // 验证签名
      isCheckSign();
      App app = appService.getByIdRel(id);
      // 查询开发成员列表
      AppUserParam appUserParam = new AppUserParam();
      appUserParam.setAppId(app.getAppId());
      List<AppUser> appUsers = appUserService.listRel(appUserParam);
//      List<User> list = userService.list(new LambdaQueryWrapper<User>().in(User::getUserId, appUsers.stream().map(AppUser::getUserId).collect(Collectors.toList())));
      app.setUsers(appUsers);
      return success(app);
    }

    @ApiOperation("创建应用")
    @Transactional(rollbackFor = {Exception.class}, isolation = Isolation.SERIALIZABLE)
    @PostMapping()
    public ApiResult<?> save(@RequestBody App app) {
        // 验证签名
        isCheckSign();
        if (app.getAppType() == null) {
          return fail("应用类型不能为空");
        }
        // 创建应用
      final Integer loginUserId = getLoginUserId();
      final User loginUser = getLoginUser();
        app.setUserId(loginUserId);
        app.setStatus(0);  // 需要审核1 不需要审核0
        app.setAppSecret(IdUtil.fastSimpleUUID());
        app.setTenantId(loginUser.getTenantId());
      System.out.println("app = " + app);
        if (appService.save(app)) {
          // 添加应用成员
          AppUser appUser = new AppUser();
          appUser.setAppId(app.getAppId());
          appUser.setRole(30);
          appUser.setUserId(loginUserId);
          appUser.setStatus(0);
          appUserService.save(appUser);
          // 更新缓存
          String key = "AppSecret:".concat(app.getAppId().toString());
          cacheClient.set(key,app.getAppSecret());
          // 更新用户的插件数量到排行榜
          int count = appService.count(new LambdaQueryWrapper<App>()
            .eq(App::getUserId, loginUserId));
          cacheClient.zAdd(USER_RANKING_BY_APPS, loginUserId,(double) count);
          return success("创建成功");
        }
        return fail("创建失败");
    }

    @ApiOperation("修改应用")
    @PutMapping()
    public ApiResult<?> update(@RequestBody App app) {
        // 验证签名
        isCheckSign();
        if (appService.updateById(app)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("删除应用")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        // 验证签名
        isCheckSign();
        if (appService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("查看秘钥")
    @PostMapping("/getAppSecret")
    public ApiResult<?> getAppSecret(@RequestBody App app) {
      App result = appService.getByIdRel(app.getAppId());
      String key = "AppSecret:".concat(app.getAppId().toString());
      result.setAppSecret(cacheClient.get(key));
      return success("操作成功",result);
    }

    @ApiOperation("重置秘钥")
    @PostMapping("/updateAppSecret")
    public ApiResult<?> updateAppSecret(@RequestBody App app) {
      // 验证签名
      isCheckSign();
      if (app.getAppId() == null) {
        return fail("请勿重复操作");
      }
      App result = appService.getByIdRel(app.getAppId());
      String key = cacheClient.key("AppSecret", app.getAppId());
      String appSecret = IdUtil.fastSimpleUUID();
      cacheClient.set(key,appSecret);
      result.setAppSecret(appSecret);
      return success("重置成功",result);
    }
}
