package com.gxwebsoft.pwl.controller;

import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.pwl.service.PwlProjectLibraryService;

import cn.hutool.core.util.StrUtil;

import com.gxwebsoft.pwl.entity.PwlProjectLibrary;
import com.gxwebsoft.pwl.param.PwlProjectLibraryParam;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.ai.service.KnowledgeBaseService;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.system.entity.User;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 材料库资料库表控制器
 *
 * @author 科技小王子
 * @since 2025-09-28 09:38:17
 */
@Tag(name = "材料库资料库表管理")
@RestController
@RequestMapping("/api/pwl/pwl-project-library")
public class PwlProjectLibraryController extends BaseController {
    @Resource
    private PwlProjectLibraryService pwlProjectLibraryService;
    
    @Resource
    private KnowledgeBaseService knowledgeBaseService;

    @PreAuthorize("hasAuthority('pwl:pwlProjectLibrary:list')")
    @Operation(summary = "分页查询材料库资料库表")
    @GetMapping("/page")
    public ApiResult<PageResult<PwlProjectLibrary>> page(PwlProjectLibraryParam param) {
        // 使用关联查询
        return success(pwlProjectLibraryService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('pwl:pwlProjectLibrary:list')")
    @Operation(summary = "查询全部材料库资料库表")
    @GetMapping()
    public ApiResult<List<PwlProjectLibrary>> list(PwlProjectLibraryParam param) {
//    	User loginUser = getLoginUser();
//    	if(!loginUser.getIsAdmin()) {
//    		param.setUserId(loginUser.getUserId());
//    	}
        // 使用关联查询
        return success(pwlProjectLibraryService.listRel(param));
    }

    @PreAuthorize("hasAuthority('pwl:pwlProjectLibrary:list')")
    @Operation(summary = "根据id查询材料库资料库表")
    @GetMapping("/{id}")
    public ApiResult<PwlProjectLibrary> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(pwlProjectLibraryService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('pwl:pwlProjectLibrary:list')")
    @Operation(summary = "根据ids查询材料库资料库表")
    @GetMapping("/byIds/{ids}")
    public ApiResult<List<PwlProjectLibrary>> getByIds(@PathVariable("ids") String ids) {
    	List<String> idList = StrUtil.split(ids, ',');
    	List<PwlProjectLibrary> ret = pwlProjectLibraryService.list(new LambdaQueryWrapper<PwlProjectLibrary>().in(PwlProjectLibrary::getId, idList));
        return success(ret);
    }

    @PreAuthorize("hasAuthority('pwl:pwlProjectLibrary:save')")
    @Operation(summary = "添加材料库资料库表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody PwlProjectLibrary pwlProjectLibrary) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
         pwlProjectLibrary.setUserId(loginUser.getUserId());
        }
        if (pwlProjectLibraryService.save(pwlProjectLibrary)) {
            try {
            	//kbName = biz00000000001
            	String kbName = pwlProjectLibrary.getType() + StrUtil.padPre(pwlProjectLibrary.getId().toString(), 11, '0');
            	String kbId = knowledgeBaseService.createKnowledgeBase(pwlProjectLibrary.getName(),kbName);
            	//绑定知识库
            	pwlProjectLibrary.setKbId(kbId);
            	pwlProjectLibraryService.updateById(pwlProjectLibrary);
            } catch (Exception e) {
            	return fail("未绑定知识库："+e.getMessage());
            }
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('pwl:pwlProjectLibrary:update')")
    @Operation(summary = "修改材料库资料库表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody PwlProjectLibrary pwlProjectLibrary) {
		if(StrUtil.isEmpty(pwlProjectLibrary.getKbId())) {
        	//kbName = biz00000000001
        	String kbName = pwlProjectLibrary.getType() + StrUtil.padPre(pwlProjectLibrary.getId().toString(), 11, '0');
        	String kbId = knowledgeBaseService.createKnowledgeBase(pwlProjectLibrary.getName(),kbName);
			//绑定知识库
			pwlProjectLibrary.setKbId(kbId);
		}
        if (pwlProjectLibraryService.updateById(pwlProjectLibrary)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('pwl:pwlProjectLibrary:remove')")
    @Operation(summary = "删除材料库资料库表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (pwlProjectLibraryService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('pwl:pwlProjectLibrary:save')")
    @Operation(summary = "批量添加材料库资料库表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<PwlProjectLibrary> list) {
        if (pwlProjectLibraryService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('pwl:pwlProjectLibrary:update')")
    @Operation(summary = "批量修改材料库资料库表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<PwlProjectLibrary> batchParam) {
        if (batchParam.update(pwlProjectLibraryService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('pwl:pwlProjectLibrary:remove')")
    @Operation(summary = "批量删除材料库资料库表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (pwlProjectLibraryService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
