package com.agileboot.codegen.controller;

import com.agileboot.codegen.dto.UserTemplateDTO;
import com.agileboot.codegen.entity.UserTemplate;
import com.agileboot.codegen.service.IUserTemplateService;
import com.agileboot.codegen.vo.UserTemplateVO;
import com.agileboot.common.core.core.R;
import com.agileboot.common.satoken.utils.LoginHelper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户模板管理 Controller
 *
 * @author system
 * @date 2025-09-26
 */
@RestController
@RequestMapping("/codegen/user-template")
@Slf4j
@RequiredArgsConstructor
public class UserTemplateController {

    private final IUserTemplateService userTemplateService;

    /**
     * 分页查询用户模板列表
     */
    @GetMapping("/list")
    public R<Page<UserTemplateVO>> list(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "templateGroup", required = false) String templateGroup,
            @RequestParam(value = "isPublic", required = false) Integer isPublic) {
        
        Long userId = LoginHelper.getUserId();
        Page<UserTemplate> page = new Page<>(pageNum, pageSize);
        Page<UserTemplateVO> result = userTemplateService.selectUserTemplateList(page, userId, templateGroup, isPublic);
        
        return R.ok(result);
    }

    /**
     * 查询公开模板列表
     */
    @GetMapping("/public")
    public R<List<UserTemplateVO>> getPublicTemplates(
            @RequestParam(value = "templateGroup", required = false) String templateGroup) {

        Long currentUserId = LoginHelper.getUserId();
        List<UserTemplateVO> result = userTemplateService.selectPublicTemplates(templateGroup, currentUserId);

        return R.ok(result);
    }

    /**
     * 根据ID查询用户模板详情
     */
    @GetMapping("/{id}")
    public R<UserTemplateVO> getById(@PathVariable Long id) {
        UserTemplateVO template = userTemplateService.selectUserTemplateById(id);
        if (template == null) {
            return R.fail("模板不存在");
        }

        // 检查权限：只能查看公开模板或自己的模板
        Long currentUserId = LoginHelper.getUserId();
        if (template.getIsPublic() != 1 && !currentUserId.equals(template.getUserId())) {
            return R.fail("无权限查看此模板");
        }

        return R.ok(template);
    }

    /**
     * 新增用户模板
     */
    @PostMapping
    public R<Void> add(@Validated @RequestBody UserTemplateDTO dto) {
        try {
            boolean success = userTemplateService.insertUserTemplate(dto);
            return success ? R.ok() : R.fail("新增模板失败");
        } catch (Exception e) {
            log.error("新增用户模板失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 修改用户模板
     */
    @PostMapping("/update")
    public R<Void> update(@Validated @RequestBody UserTemplateDTO dto) {
        try {
            boolean success = userTemplateService.updateUserTemplate(dto);
            return success ? R.ok() : R.fail("修改模板失败");
        } catch (Exception e) {
            log.error("修改用户模板失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 删除用户模板
     */
    @PostMapping("/delete")
    public R<Void> remove(@RequestBody Map<String, Object> params) {
        try {
            Long id = Long.parseLong(params.get("id").toString());
            boolean success = userTemplateService.deleteUserTemplateById(id);
            return success ? R.ok() : R.fail("删除模板失败");
        } catch (Exception e) {
            log.error("删除用户模板失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 批量删除用户模板
     */
    @PostMapping("/delete/batch")
    public R<Void> removeBatch(@RequestBody Map<String, Object> params) {
        try {
            @SuppressWarnings("unchecked")
            List<Object> idsObj = (List<Object>) params.get("ids");
            Long[] ids = idsObj.stream()
                    .map(obj -> {
                        if (obj instanceof Integer) {
                            return ((Integer) obj).longValue();
                        } else if (obj instanceof Long) {
                            return (Long) obj;
                        } else if (obj instanceof String) {
                            return Long.parseLong((String) obj);
                        } else {
                            throw new RuntimeException("不支持的ID类型: " + obj.getClass());
                        }
                    })
                    .toArray(Long[]::new);
            boolean success = userTemplateService.deleteUserTemplateByIds(ids);
            return success ? R.ok() : R.fail("批量删除模板失败");
        } catch (Exception e) {
            log.error("批量删除用户模板失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 复制模板
     */
    @PostMapping("/copy")
    public R<Void> copyTemplate(@RequestBody Map<String, Object> params) {
        try {
            Long templateId = Long.parseLong(params.get("templateId").toString());
            String newName = params.get("newName").toString();
            boolean success = userTemplateService.copyTemplate(templateId, newName);
            return success ? R.ok() : R.fail("复制模板失败");
        } catch (Exception e) {
            log.error("复制模板失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 验证模板语法
     */
    @PostMapping("/validate")
    public R<String> validateTemplate(@RequestBody String templateContent) {
        String result = userTemplateService.validateTemplate(templateContent);
        return R.ok(result);
    }

    /**
     * 检查模板名称是否存在
     */
    @GetMapping("/check-name")
    public R<Boolean> checkTemplateName(@RequestParam(value = "templateName") String templateName,
                                       @RequestParam(value = "excludeId", required = false) Long excludeId) {
        Long userId = LoginHelper.getUserId();
        boolean exists = userTemplateService.checkTemplateNameExists(userId, templateName, excludeId);
        return R.ok(exists);
    }

    /**
     * 切换用户模板显示状态
     */
    @PostMapping("/toggle-visibility")
    public R<Void> toggleTemplateVisibility(@RequestBody Map<String, Object> params) {
        try {
            Long id = Long.parseLong(params.get("id").toString());
            Integer isEnabled = Integer.parseInt(params.get("isEnabled").toString());
            boolean success = userTemplateService.toggleTemplateVisibility(id, isEnabled);
            return success ? R.ok() : R.fail("切换显示状态失败");
        } catch (Exception e) {
            log.error("切换用户模板显示状态失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取模板内容
     */
    @GetMapping("/content/{id}")
    public R<String> getTemplateContent(@PathVariable("id") Long id) {
        try {
            String content = userTemplateService.getTemplateContent(id);
            return R.ok("获取成功", content);
        } catch (Exception e) {
            log.error("获取模板内容失败", e);
            return R.fail(e.getMessage());
        }
    }
}

