package com.gxwebsoft.oa.controller;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.net.url.UrlQuery;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.security.JwtUtil;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.utils.RedisUtil;
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.FileRecord;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.FileRecordService;
import com.gxwebsoft.oa.entity.App;
import com.gxwebsoft.oa.entity.AppUrl;
import com.gxwebsoft.oa.entity.AppUser;
import com.gxwebsoft.oa.param.AppParam;
import com.gxwebsoft.oa.service.AppService;
import com.gxwebsoft.oa.service.AppUrlService;
import com.gxwebsoft.oa.service.AppUserService;
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 javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static com.gxwebsoft.common.core.constants.AppUserConstants.ADMINISTRATOR;

/**
 * 应用管理记录表控制器
 *
 * @author 科技小王子
 * @since 2023-10-26 22:06:23
 */
@Api(tags = "应用管理记录表管理")
@RestController
@RequestMapping("/api/oa/app")
public class AppController extends BaseController {
    @Resource
    private AppService appService;
    @Resource
    private AppUserService appUserService;
    @Resource
    private AppUrlService appUrlService;
    @Resource
    private FileRecordService fileRecordService;
    @Resource
    private RedisUtil redisUtil;

    @ApiOperation("统计信息")
    @GetMapping("/data")
    public ApiResult<Map<String, Integer>> data() {
      Map<String, Integer> data = new HashMap<>();
      Integer totalNum = appService.count(
        new LambdaQueryWrapper<>()
      );
      Integer totalNum2 = appService.count(
        new LambdaQueryWrapper<App>()
          .eq(App::getAppStatus, "开发中")
      );
      Integer totalNum3 = appService.count(
        new LambdaQueryWrapper<App>()
          .eq(App::getAppStatus, "已上架")
      );
      Integer totalNum4 = appService.count(
        new LambdaQueryWrapper<App>()
          .eq(App::getAppStatus, "已上架")
          .eq(App::getShowExpiration,false)
      );
      Integer totalNum5 = appService.count(
        new LambdaQueryWrapper<App>()
          .eq(App::getAppStatus, "已下架")
      );
      Integer totalNum6 = appService.count(
        new LambdaQueryWrapper<App>()
          .eq(App::getShowCase,true)
      );
      Integer totalNum7 = appService.count(
        new LambdaQueryWrapper<App>()
          .eq(App::getShowIndex, true)
      );

      data.put("totalNum", totalNum);
      data.put("totalNum2", totalNum2);
      data.put("totalNum3", totalNum3);
      data.put("totalNum4", totalNum4);
      data.put("totalNum5", totalNum5);
      data.put("totalNum6", totalNum6);
      data.put("totalNum7", totalNum7);
      return success(data);
    }

    @ApiOperation("分页查询应用管理记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<App>> page(AppParam param, HttpServletRequest request) {
        final User loginUser = getLoginUser();
        // 未登录情况
        if(loginUser == null){
          String access_token = JwtUtil.getAccessToken(request);
          param.setToken(access_token);
          return success("案例列表",caseList(param));
        }
        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));
              System.out.println("list = " + list);
                final Set<Integer> collect = list.stream().map(AppUser::getAppId).collect(Collectors.toSet());
                param.setAppIds(collect);
            }
        });
        // 过滤续费提醒参数
        if (param.getAppStatus() != null && param.getAppStatus().equals("续费中")) {
          param.setAppStatus(null);
        }
        // 使用关联查询
        return success(appService.pageRel(param));
    }

    // 读取案例列表
    private PageResult<App> caseList(AppParam param){
      param.setShowCase(true);
      final PageResult<App> appPageResult = appService.pageRel(param);
      appPageResult.getList().forEach(d -> {
        d.setContent(null);
        // 读取账号列表
        d.setAppUrlList(appUrlService.list(new LambdaQueryWrapper<AppUrl>().eq(AppUrl::getAppId,d.getAppId())));
        // 读取项目附件（链式构建GET请求）
        HashMap<String, Object> map = new HashMap<>();
        map.put("appId", d.getAppId());
        final String build = UrlBuilder.of("https://server.gxwebsoft.com/api/file/page").setQuery(new UrlQuery(map)).build();
        String response = HttpRequest.get(build)
          .header("Authorization", param.getToken())
          .header("Tenantid", d.getTenantId().toString())
          .body(JSONObject.toJSONString(map))//表单内容
          .timeout(20000)//超时，毫秒
          .execute().body();

        final ApiResult<PageResult<FileRecord>> userResult = JSONObject.parseObject(response, new TypeReference<ApiResult<PageResult<FileRecord>>>() {
        });
        d.setAppFiles(userResult.getData().getList());
      });
      return appPageResult;
    }

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

    @ApiOperation("根据id查询应用管理记录表")
    @GetMapping("/{id}")
    public ApiResult<App> get(@PathVariable("id") Integer id) {
        final User loginUser = getLoginUser();
        // 未登录情况
        if(loginUser == null){
          return success("案例详情",getDesensitizedApp(id));
        }
        if (!CommonUtil.hasRole(loginUser.getRoles(),"superAdmin") && !CommonUtil.hasRole(loginUser.getRoles(),"admin")) {
          // 查询权限
          if (appUserService.count(new LambdaQueryWrapper<AppUser>().eq(AppUser::getUserId, getLoginUserId()).eq(AppUser::getAppId,id)) == 0) {
            return fail("无查看权限",null);
          }
        }
        // 使用关联查询
        return success(appService.getByIdRel(id));
    }

  private App getDesensitizedApp(Integer id) {
    final App app = appService.getByIdRel(id);
    app.setPhone(DesensitizedUtil.mobilePhone(app.getPhone()));
    app.setCompanyName(
      StrUtil.hide(app.getCompanyName(), 2, app.getCompanyName().length() - 2));
    app.setRequirement(DesensitizedUtil.chineseName(app.getCompanyName()));
    return app;
  }

  @ApiOperation("添加应用管理记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody App app) {
        // 记录当前登录用户id、租户id、商户编号
        User loginUser = getLoginUser();
        AppUser appUser = new AppUser();
        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)) {
            // 添加应用管理员
            if (loginUser != null) {
              appUser.setUserId(loginUser.getUserId());
              appUser.setNickname(loginUser.getNickname());
              appUser.setAppId(app.getAppId());
              appUser.setRole(ADMINISTRATOR);
              appUserService.save(appUser);
            }
            return success("添加成功");
        }
        return fail("添加失败");
    }

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

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

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

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

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

    @ApiOperation("重置秘钥")
    @PostMapping("/updateAppSecret")
    public ApiResult<?> updateAppSecret(@RequestBody App app) {
        String key = "code:" + app.getPhone();
        final String code = redisUtil.get(key);
        if (app.getAppId() == null) {
            return fail("appId不合法");
        }
        if(app.getAppSecret() == null){
          return fail("appSecret不合法");
        }
        if(app.getAppCode() == null){
          return fail("短信验证码不正确");
        }
//         && !app.getAppCode().equals("170083")
        if(!app.getAppCode().equals(code)){
          return fail("短信验证码不正确");
        }
        appService.updateById(app);
        // 保存到redis
        redisUtil.set("AppSecret:" + app.getAppId(),app.getAppSecret());
        redisUtil.delete(key);
        return success("重置成功",app.getAppSecret());
    }

    @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);
    }

  @ApiOperation("查询我的项目信息")
  @GetMapping("/getMyApp")
  public ApiResult<App> getMyApp() {
    final User loginUser = getLoginUser();
    // 未登录情况
    if(loginUser == null){
      return fail("请先登录",null);
    }
    appService.list();

    // 使用关联查询
    return success("查询成功",null);
  }

}
