package com.storlead.centre.app;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.centre.entity.SysAppPageInfoEntity;
import com.storlead.centre.pojo.dto.SysAppInfoQuery;
import com.storlead.centre.pojo.entity.SysAppInfoEntity;
import com.storlead.centre.pojo.vo.SysAppPageVO;
import com.storlead.centre.pojo.vo.SysAppVO;
import com.storlead.centre.service.SysAppInfoService;
import com.storlead.centre.service.SysAppPageInfoService;
import com.storlead.centre.util.CryptoZipUtil;
import com.storlead.centre.util.HttpSecurityCheckUtil;
import com.storlead.framework.auth.vo.LoginUser;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.MD5Util;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.web.assemble.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: storlead-centre-platform
 * @description:
 * @author: chenkq
 * @create: 2025-11-21 12:06
 */
@RestController
@RequestMapping("/app-centre/manage")
@Api(tags = "1.应用管理")
public class AppManageApiController {

    @Resource
    private SysAppInfoService sysAppInfoService;

    @Resource
    private SysAppPageInfoService sysAppPageInfoService;

    private static final String SALT_KEY = "G4YfTqX6Kh8cHQy5";

    @PostMapping(value = "/save")
    @ApiOperation(value = "应用管理--新增/编辑", notes = "应用管理-新增/编辑")
    @Transactional(rollbackFor = Throwable.class)
    public Result<?> save(@RequestBody SysAppInfoEntity info) {
        sysAppInfoService.saveOrUpdate(info);
        return Result.ok();
    }

    @PostMapping(value = "/editeIcon")
    @ApiOperation(value = "编辑图标", notes = "编辑图标")
    @Transactional(rollbackFor = Throwable.class)
    public Result<?> editeIcon(Long id,String iconName) {

        LambdaUpdateWrapper<SysAppPageInfoEntity> update = new LambdaUpdateWrapper<>();
        update.set(SysAppPageInfoEntity::getPageIcon,iconName);
        update.eq(SysAppPageInfoEntity::getId,id);
        sysAppPageInfoService.update(update);

        return Result.ok();
    }


    @PostMapping(value = "/pagelist")
    @ApiOperation(value = "应用管理-分页查询", notes = "应用管理-分页查询")
    @Transactional(rollbackFor = Throwable.class)
    public Result<?> pagelist(@RequestBody SysAppInfoQuery query) {

        IPage<SysAppInfoEntity> page = new Page<>(query.getPageIndex(),query.getPageSize());
        IPage<SysAppInfoEntity> infos = sysAppInfoService.page(page);
        return Result.result(infos);
    }

    @ApiOperation("启用禁用部门")
    @PostMapping("enable")
    public Result setEnable(Long id,Boolean enable) {
        if (enable) {
            sysAppInfoService.enable(id);
        } else {
            sysAppInfoService.disable(id);
        }
        return Result.ok();
    }


    @PostMapping(value = "/getHomeApp")
    @ApiOperation(value = "应用管理--新增/编辑", notes = "应用管理-新增/编辑")
    public Result<?> getHomeApp() {

        LambdaQueryWrapper<SysAppInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysAppInfoEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        List<SysAppInfoEntity> apps = sysAppInfoService.list(queryWrapper);
        List<SysAppVO> appTree = SysAppVO.appInfoListToAppTreeVoList(apps);

        if (CollectionUtils.isEmpty(appTree)) {
            return Result.result(appTree);
        }
        LambdaQueryWrapper<SysAppPageInfoEntity> queryWra1 = new LambdaQueryWrapper<>();
        queryWra1.eq(SysAppPageInfoEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        List<SysAppPageInfoEntity> appPages = sysAppPageInfoService.list(queryWra1);
        if (CollectionUtils.isEmpty(appPages)) {
            return Result.result(appTree);
        }

        appTree.forEach(e -> {
           List<SysAppPageInfoEntity> appPagels = appPages.stream().filter(p ->p.getAppId().equals(e.getAppId())).collect(Collectors.toList());
           List<SysAppPageVO> pageTree =  SysAppPageVO.appPageInfoListToAppPageTreeVoList(appPagels);
           e.setAppPages(pageTree);
        });

        return Result.result(appTree);
    }


    @PostMapping(value = "/jumpToPage")
    @ApiOperation(value = "应用管理-跳转子页", notes = "应用管理-跳转子页")
    public Result<?> jumpToPage(Long pageId) {

        String token = LoginUserUtil.getLoginToken();
        if (StrUtil.isBlank(token)) {
            return Result.error("未登录!");
        }
        SysAppPageInfoEntity page = sysAppPageInfoService.getById(pageId);
        if (Objects.isNull(page)) {
            return Result.error("无权限");
        }
        if (StrUtil.isBlank(page.getRedirectUri())) {
            return Result.error("该应用功能未开放！");
        }
        SysAppInfoEntity info = sysAppInfoService.getById(page.getAppId());
        LoginUserUtil.getLoginUser();
        Map<String,String> argMap = new HashMap<>();
        Long dt = System.currentTimeMillis() / 1000 % HttpSecurityCheckUtil.divisor;
        argMap.put("dt",dt.toString());
        argMap.put("redirect",page.getRedirectUri());
        argMap.put("appSecret",info.getAppSecret());
        argMap.put("token",token);
        argMap.put("account","admin");
        String sign = MD5Util.MD5Encode(HttpSecurityCheckUtil.makeSign(argMap),"UTF-8").toLowerCase();
        argMap.put("sign",sign);
        argMap.remove("appSecret");
//        String urlParam =  HttpSecurityCheckUtil.buildUrlParams(argMap);
        String encrypted = CryptoZipUtil.encryptParams(argMap,SALT_KEY);
        String requestUrl = info.getHomepageUrl()+"/ssoredirect?ticket="+encrypted;
        return Result.result(requestUrl);
    }

    @PostMapping(value = "/jumpToHome")
    @ApiOperation(value = "应用管理-跳转主页", notes = "应用管理-跳转主页")
    public Result<?> jumpToHome(Long appId) {
        SysAppInfoEntity info = sysAppInfoService.getById(appId);
        LoginUser loginUser = LoginUserUtil.getLoginUser();

        String token = LoginUserUtil.getLoginToken();
        if (StrUtil.isBlank(token) || Objects.isNull(loginUser)) {
            return Result.error("未登录!");
        }
        Map<String,String> argMap = new HashMap<>();
        Long dt = System.currentTimeMillis() / 1000 % HttpSecurityCheckUtil.divisor;
        argMap.put("dt",dt.toString());
        argMap.put("redirect",info.getRedirectUri());
        argMap.put("appSecret",info.getAppSecret());
        argMap.put("token",token);
        argMap.put("account",loginUser.getMobile());
        String sign = MD5Util.MD5Encode(HttpSecurityCheckUtil.makeSign(argMap),"UTF-8");

        argMap.put("sign",sign);
        String urlParam =  HttpSecurityCheckUtil.buildUrlParams(argMap);
        String requestUrl = info.getHomepageUrl()+"/ssoredirect?ticket="+urlParam;
        return Result.result(requestUrl);
    }

    public static void main(String[] args) {

        Map<String,String> argMap = new HashMap<>();
        Long dt = System.currentTimeMillis() / 1000 % HttpSecurityCheckUtil.divisor;
        argMap.put("dt",dt.toString());
        argMap.put("redirect","/home");
        argMap.put("appSecret","ddddddd");
        argMap.put("account","18118724055");
        argMap.put("token","ouunwqlkeklnkljm23jk3nywwqk");
        String sign = MD5Util.MD5Encode(HttpSecurityCheckUtil.makeSign(argMap),"UTF-8").toLowerCase();
        argMap.put("sign",sign);
        String urlParam =  HttpSecurityCheckUtil.buildUrlParams(argMap);
        String requestUrl = "http://127.0.0.1:8080/ssoredirect?ticket="+urlParam;

        System.out.println("urlParam = "+urlParam);
        System.out.println("requestUrl = "+requestUrl);
        String encrypted = CryptoZipUtil.encryptParams(argMap,SALT_KEY);
        System.out.println("加密后的 URL 参数：" + encrypted);
        System.out.println("加密后的 URL  http://127.0.0.1:8080/ssoredirect?ticket="+encrypted);

        Map<String, String> map = CryptoZipUtil.decryptParams(encrypted, SALT_KEY);

        System.out.println("解密后的 参数:" + map);

    }
}
