package org.jk.rag.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jk.common.core.domain.R;
import org.jk.common.core.domain.model.LoginUser;
import org.jk.common.idempotent.annotation.RepeatSubmit;
import org.jk.common.mybatis.core.page.PageQuery;
import org.jk.common.mybatis.core.page.TableDataInfo;
import org.jk.common.satoken.utils.LoginHelper;
import org.jk.common.web.core.BaseController;
import org.jk.rag.domain.entity.*;
import org.jk.rag.service.IJkRagService;
import org.jk.system.domain.SysUser;
import org.jk.system.service.ISysPermissionService;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/deepseek/api")
public class JkRagApplicationController extends BaseController {


    private final IJkRagService iJkRagService;

    private final ISysPermissionService permissionService;


    /**
     * 应用列表
     *
     * @param params
     * @return
     */
    @PostMapping("/getApplicationList")
    public TableDataInfo<JkApplicationResult> getApplicationList(@RequestBody JkPageParams params, @RequestBody PageQuery pageQuery) {
        JkApplication vo = setFlagParams(params.getUserId(), params.getTypeId(), params.getProjectId(), 1);
        vo.setIsCollect(params.getIsCollect());

        Page<JkApplicationResult> list = iJkRagService.getApplicationPageList(vo,pageQuery);
        return TableDataInfo.build(list);
    }

    /**
     * 应用列表
     *
     * @param params
     * @return
     */
    @PostMapping("/getMyApplicationList")
    public TableDataInfo<JkApplicationResult> getMyApplicationList(@RequestBody JkPageParams params, @RequestBody PageQuery pageQuery) {
        JkApplication vo = JkApplication.builder().name(params.getName()).build();
        Page<JkApplicationResult> list = iJkRagService.getMyApplicationPageList(vo,pageQuery);
        return TableDataInfo.build(list);
    }

    /**
     * 创建应用
     *
     * @param params
     * @return
     */
    @SaCheckPermission("appCenter:questionAnswer:add")
    @PostMapping("/createApplication")
    @RepeatSubmit
    public R<Integer> addApplication(@RequestBody JkApplicationParams params) {
        SysUser user = new SysUser();
        user.setUserId(Long.parseLong(params.getUserId()));
        int i = 0;
        if (LoginHelper.isTenantAdmin() || LoginHelper.isSuperAdmin()) {
            i = iJkRagService.createApplication(params, true);
        }else{
            i = iJkRagService.createApplication(params, false);
        }
        return R.ok(i);
    }

    /**
     * 查询应用详情
     *
     * @param appId
     * @return
     */
    @GetMapping("/selectApplication/{appId}")
    public R<JSONObject> selectApplication(@PathVariable String appId) {
        JSONObject application = iJkRagService.selectApplication(appId);
        return R.ok(application);
    }

    /**
     * 修改应用
     *
     * @param params
     * @param appId
     * @return
     */
    //@SaCheckPermission("appCenter:questionAnswer:edit")
    @PutMapping("/updateApplication/{appId}")
    @RepeatSubmit
    public R<Integer> updateApplication(@RequestBody JkApplicationParams params, @PathVariable String appId) {
        SysUser user = new SysUser();
        user.setUserId(Long.parseLong(params.getUserId()));
        Set<String> permissions = permissionService.getMenuPermission(user.getUserId());
        int application = 0;
        if (permissions != null && permissions.size() > 0 && (permissions.contains("deepseek:application:role") || permissions.contains("*:*:*"))) {
            application = iJkRagService.updateApplication(params, appId, true);
        }else{
            application = iJkRagService.updateApplication(params, appId, false);
        }
        return R.ok(application);
    }

    /**
     * 删除应用
     *
     * @param appId
     * @return
     */
    //@SaCheckPermission("appCenter:questionAnswer:del")
    @DeleteMapping("/delApplication/{appId}")
    public R<Integer> delApplication(@PathVariable String appId) {
        int application = iJkRagService.delApplication(appId);
        return R.ok(application);
    }

    /**
     * 应用列表
     *
     * @return
     */
    @GetMapping("/application/list")
    public R<List<JkApplicationResult>> applicationList() {
        LoginUser loginUser = null;
        if(StpUtil.isLogin()) {
            loginUser = LoginHelper.getLoginUser();
        }

        if(loginUser != null){
            JkApplication vo = setFlagParams(String.valueOf(loginUser.getUserId()), null, null, 3);
            List<JkApplicationResult> appList = iJkRagService.getApplicationList(vo);
            return R.ok(appList);
        }else{
            JkApplication vo = setFlagParams(null, null, null, 3);
            List<JkApplicationResult> appList = iJkRagService.getApplicationList(vo);
            return R.ok(appList);
        }
    }

    /**
     * 管理后台应用列表
     * @return
     */
    @GetMapping("/application/list/{userId}")
    public R<List<JkApplicationResult>> adminApp(@PathVariable String userId) {
        JkApplication vo = setFlagParams(userId, null, null, 3);
        List<JkApplicationResult> appList = iJkRagService.getApplicationList(vo);
        return R.ok(appList);
    }



    /**
     * 根据登录用户获取项目下的应用列表
     * @return
     */
    @GetMapping("/project/app")//@RequestBody JkPageParams params
    public R<List<JkApplicationResult>> appFlag() {
//        JkApplication vo = setFlagParams(params.getUserId());
//        vo.setApprover(params.getUserId());
        LoginUser loginUser = LoginHelper.getLoginUser();
        if(loginUser != null){
            JkApplication vo = setFlagParams(String.valueOf(loginUser.getUserId()), null, null, 1);
            List<JkApplicationResult> s = iJkRagService.getApplicationList(vo);
            return R.ok(iJkRagService.getChatAppList(s, String.valueOf(loginUser.getUserId())));
        }else{
            return R.ok(null);
        }
    }

    /**
     * 收藏列表
     * @param userId
     * @return
     */
    @GetMapping("/app/collect/list/{userId}")
    public R<List<String>> appCollectList(@PathVariable String userId) {
        List<String> list = iJkRagService.selectAppCollectList(userId);
        return R.ok(list);
    }

    /**
     * 收藏
     * @param appCollect
     * @return
     */
    @PostMapping("/app/collect")
    public R<Integer> appCollect(@RequestBody AppCollect appCollect) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if(loginUser != null){
            appCollect.setUserId(String.valueOf(loginUser.getUserId()));
            return R.ok(iJkRagService.insertAppCollect(appCollect));
        }else {
            return R.ok(null);
        }
    }

    /**
     * 取消收藏
     * @param appId
     * @return
     */
    @DeleteMapping("/app/collect/{appId}")
    public R<Integer> appCollectDel(@PathVariable String appId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if(loginUser != null){
            return R.ok(iJkRagService.deleteAppCollect(String.valueOf(loginUser.getUserId()), appId));
        }else{
            return R.ok(null);
        }
    }



    private JkApplication setFlagParams(String userId, String typeId, String projectId, int i) {
        if(i == 3){
            return returnParams(userId, typeId, projectId, "0");
        }else{
            Set<String> permissions = permissionService.getMenuPermission(Long.parseLong(userId));
            if (permissions.contains("deepseek:application:create") || permissions.contains("deepseek:application:update")) {
                return returnParams(userId, typeId, projectId, "1");
            }else{
                return returnParams(userId, typeId, projectId, "0");
            }
        }
    }

    private JkApplication returnParams(String userId, String typeId, String projectId, String flag) {
        return JkApplication.builder().approver(userId == null ? null : userId)
                .typeId(typeId == null ? null : Long.valueOf(typeId))
                .projectId(projectId == null ? null : projectId)
                .flag(flag).build();
    }


//    @GetMapping("/download/{fileName}")
//    public void downloadFile(@PathVariable String fileName) {
//        try {
////            InputStream stream = minioUtil.download(bucketName, fileName);
//            // 这里简化处理，实际应该设置正确的Content-Type和Content-Disposition
////            return ResponseEntity.ok()
////                    .header("Content-Type", "application/octet-stream")
////                    .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
////                    .body(stream);
//        } catch (Exception e) {
//            logger.error("文件下载失败: " + e.getMessage());
//        }
//    }

//    @DeleteMapping("/delete/{fileName}")
//    public void deleteFile(@PathVariable String fileName) {
//        try {
////            minioUtil.remove(bucketName, fileName);
//        } catch (Exception e) {
//            logger.error("文件删除失败: " + e.getMessage());
//        }
//    }

}
