package com.gxwebsoft.oa.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
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.BatchParam;
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.service.AppService;
import com.gxwebsoft.oa.service.AppUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 应用管理记录表控制器
 *
 * @author 科技小王子
 * @since 2023-03-28 10:45:39
 */
@Api(tags = "应用管理记录表管理")
@RestController
@RequestMapping("/api/oa/app")
public class AppController extends BaseController {
    @Resource
    private AppService appService;
    @Resource
    private CacheClient cacheClient;
    @Resource
    private AppUserService appUserService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PreAuthorize("hasAuthority('oa:app:list')")
    @OperationLog
    @ApiOperation("分页查询应用管理记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<App>> page(AppParam param) {
      final User loginUser = getLoginUser();
      final Integer userId = loginUser.getUserId();
      loginUser.getRoles().forEach(d -> {
        if(!StrUtil.equals(d.getRoleCode(),"superAdmin") && !StrUtil.equals(d.getRoleCode(),"admin")){
          // 非管理员按项目成员权限显示
          final List<AppUser> list = appUserService.list(new LambdaQueryWrapper<AppUser>().eq(AppUser::getUserId, userId));
          final Set<Integer> collect = list.stream().map(AppUser::getAppId).collect(Collectors.toSet());
          param.setAppIds(collect);
        }
      });
      // 使用关联查询
      return success(appService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('oa:app:list')")
    @OperationLog
    @ApiOperation("查询全部应用管理记录表")
    @GetMapping()
    public ApiResult<List<App>> list(AppParam param) {
        // 使用关联查询
        return success(appService.listRel(param));
    }

    @PreAuthorize("hasAuthority('oa:app:list')")
    @OperationLog
    @ApiOperation("根据id查询应用管理记录表")
    @GetMapping("/{id}")
    public ApiResult<App> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(appService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('oa:app:save')")
    @OperationLog
    @ApiOperation("添加应用管理记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody App app) {
        // 记录当前登录用户id、租户id、商户编号
        User loginUser = getLoginUser();
        if (loginUser != null) {
          app.setUserId(loginUser.getUserId());
          app.setTenantId(loginUser.getTenantId());
        }
        if (appService.count(new LambdaQueryWrapper<App>()
          .eq(App::getAppCode, app.getAppCode())) > 0) {
          return fail("应用标识已存在");
        }
        if (appService.save(app)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('oa:app:update')")
    @OperationLog
    @ApiOperation("修改应用管理记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody App app) {
        if (appService.updateById(app)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('oa:app:remove')")
    @OperationLog
    @ApiOperation("删除应用管理记录表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (appService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('oa:app:save')")
    @OperationLog
    @ApiOperation("批量添加应用管理记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<App> list) {
        if (appService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('oa:app:update')")
    @OperationLog
    @ApiOperation("批量修改应用管理记录表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<App> batchParam) {
        if (batchParam.update(appService, "app_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('oa:app:remove')")
    @OperationLog
    @ApiOperation("批量删除应用管理记录表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (appService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('oa:app:update')")
    @ApiOperation("重置秘钥")
    @PostMapping("/updateAppSecret")
    public ApiResult<?> updateAppSecret(@RequestBody App app) {
      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);
    }

    @ApiOperation("APP应用授权身份效验")
    @GetMapping("/authentication/{appid}")
    public ApiResult<?> authentication(@PathVariable("appid") String appid) {
      final App appInfo = appService.getById(appid);
      if(appInfo == null){
        return fail("应用不存在:".concat(appid));
      }
      return success("应用信息",appInfo);
    }

}
