package tech.easyflow.admin.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.table.TableInfo;
import com.mybatisflex.core.table.TableInfoFactory;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.easyflow.ai.service.KnowledgeSharePermissionService;
import tech.easyflow.ai.service.WorkflowApiPermissionService;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.entity.LoginAccount;
import tech.easyflow.common.satoken.util.SaTokenUtil;
import tech.easyflow.common.util.IdUtil;
import tech.easyflow.common.vo.PkVo;
import tech.easyflow.common.web.controller.BaseCurdController;
import tech.easyflow.system.entity.SysApiKey;
import tech.easyflow.system.entity.SysApiKeyResourceMapping;
import tech.easyflow.system.service.SysApiKeyResourceMappingService;
import tech.easyflow.system.service.SysApiKeyService;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 *  控制层。
 *
 * @author wangGangQiang
 * @since 2025-04-18
 */
@RestController
@RequestMapping("/api/v1/sysApiKey")
public class SysApiKeyController extends BaseCurdController<SysApiKeyService, SysApiKey> {
    public SysApiKeyController(SysApiKeyService service) {
        super(service);
    }

    @Resource
    private SysApiKeyResourceMappingService sysApiKeyResourceMappingService;
    @Resource
    private KnowledgeSharePermissionService knowledgeSharePermissionService;
    @Resource
    private WorkflowApiPermissionService workflowApiPermissionService;
    /**
     * 添加（保存）数据
     *
     * @return {@code Result.errorCode == 0} 添加成功，否则添加失败
     */
    @PostMapping("/key/save")
    @SaCheckPermission("/api/v1/sysApiKey/save")
    public Result<PkVo> save() {
        String apiKey = IdUtil.generateUUID();
        SysApiKey entity = new SysApiKey();
        entity.setApiKey(apiKey);
        entity.setCreated(new Date());
        entity.setStatus(1);
        // 将Date转换为LocalDate
        LocalDate localDate = new Date().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        // 添加30天
        LocalDate newLocalDate = localDate.plusDays(30);
        // 转换回Date
        Date expireDate =  Date.from(newLocalDate.atStartOfDay()
                .atZone(ZoneId.systemDefault())
                .toInstant());
        entity.setExpiredAt(expireDate);
        LoginAccount loginAccount = SaTokenUtil.getLoginAccount();
        commonFiled(entity,loginAccount.getId(),loginAccount.getTenantId(),loginAccount.getDeptId());
        service.save(entity);
        onSaveOrUpdateAfter(entity, true);
        TableInfo tableInfo = TableInfoFactory.ofEntityClass(entity.getClass());
        Object[] pkArgs = tableInfo.buildPkSqlArgs(entity);
        return Result.ok(new PkVo(pkArgs));
    }

    @Override
    protected void onSaveOrUpdateAfter(SysApiKey entity, boolean isSave) {
        if (entity.getPermissionIds() != null) {
            sysApiKeyResourceMappingService.authInterface(entity);
        }
        if (entity.getKnowledgeShareEnabled() != null) {
            knowledgeSharePermissionService.replaceApiShareEnabled(entity.getId(), entity.getKnowledgeShareEnabled());
        }
        if (entity.getWorkflowApiEnabled() != null) {
            workflowApiPermissionService.replaceWorkflowApiEnabled(entity.getId(), entity.getWorkflowApiEnabled());
        }
    }

    @Override
    @GetMapping("/detail")
    public Result<SysApiKey> detail(String id) {
        Result<SysApiKey> result = super.detail(id);
        fillApiKeyPermissions(result.getData());
        return result;
    }

    @Override
    @GetMapping("/page")
    public Result<Page<SysApiKey>> page(HttpServletRequest request, String sortKey, String sortType, Long pageNumber, Long pageSize) {
        Result<Page<SysApiKey>> pageResult = (Result<Page<SysApiKey>>) super.page(request, sortKey, sortType, pageNumber, pageSize);
        Page<SysApiKey> data = pageResult.getData();
        List<SysApiKey> records = data.getRecords();
        records.forEach(this::fillApiKeyPermissions);
        return pageResult;
    }

    /**
     * 回填访问令牌的接口与知识库授权。
     *
     * @param entity 访问令牌
     */
    private void fillApiKeyPermissions(SysApiKey entity) {
        if (entity == null || entity.getId() == null) {
            return;
        }
        QueryWrapper interfaceWrapper = QueryWrapper.create()
            .select(SysApiKeyResourceMapping::getApiKeyResourceId)
            .eq(SysApiKeyResourceMapping::getApiKeyId, entity.getId())
            .isNull(SysApiKeyResourceMapping::getResourceType);
        List<BigInteger> resourceIds = sysApiKeyResourceMappingService.listAs(interfaceWrapper, BigInteger.class);
        entity.setPermissionIds(resourceIds);

        QueryWrapper knowledgeWrapper = QueryWrapper.create()
            .select(SysApiKeyResourceMapping::getId)
            .eq(SysApiKeyResourceMapping::getApiKeyId, entity.getId())
            .eq(SysApiKeyResourceMapping::getResourceType, "KNOWLEDGE");
        entity.setKnowledgeShareEnabled(sysApiKeyResourceMappingService.count(knowledgeWrapper) > 0);

        QueryWrapper workflowWrapper = QueryWrapper.create()
            .select(SysApiKeyResourceMapping::getId)
            .eq(SysApiKeyResourceMapping::getApiKeyId, entity.getId())
            .eq(SysApiKeyResourceMapping::getResourceType, WorkflowApiPermissionService.RESOURCE_TYPE_WORKFLOW);
        entity.setWorkflowApiEnabled(sysApiKeyResourceMappingService.count(workflowWrapper) > 0);
    }
}
