package org.jeecg.modules.print.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.print.entity.PrintTemplate;
import org.jeecg.modules.print.service.IPrintTemplateService;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 打印模板维护（Hiprint）
 */
@Slf4j
@Tag(name = "打印模板")
@RestController
@RequestMapping("/print/template")
public class PrintTemplateController extends JeecgController<PrintTemplate, IPrintTemplateService> {

    /**
     * 分页列表
     */
    @Operation(summary = "打印模板-分页列表")
    @GetMapping(value = "/list")
    @RequiresPermissions("print:template:list")
    public Result<IPage<PrintTemplate>> list(PrintTemplate query,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                             HttpServletRequest req) {
        QueryWrapper<PrintTemplate> qw = QueryGenerator.initQueryWrapper(query, req.getParameterMap());
        qw.orderByDesc("create_time");
        Page<PrintTemplate> page = new Page<>(pageNo, pageSize);
        return Result.OK(service.page(page, qw));
    }

    /**
     * 添加
     */
    @AutoLog(value = "打印模板-添加")
    @Operation(summary = "打印模板-添加")
    @PostMapping(value = "/add")
    @RequiresPermissions("print:template:add")
    public Result<String> add(@RequestBody PrintTemplate entity) {
        if (StringUtils.isBlank(entity.getTemplateCode())) {
            return Result.error("模板编码不能为空");
        }
        if (service.getByCode(entity.getTemplateCode()) != null) {
            return Result.error("模板编码已存在");
        }
        if (StringUtils.isBlank(entity.getTemplateJson())) {
            entity.setTemplateJson("{}");
        }
        service.save(entity);
        return Result.OK("添加成功");
    }

    /**
     * 编辑（基础字段，不含大 JSON 时可单独调 saveJson）
     */
    @AutoLog(value = "打印模板-编辑")
    @Operation(summary = "打印模板-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    @RequiresPermissions("print:template:edit")
    public Result<String> edit(@RequestBody PrintTemplate entity) {
        PrintTemplate db = service.getById(entity.getId());
        if (db == null) {
            return Result.error("记录不存在");
        }
        if (StringUtils.isNotBlank(entity.getTemplateCode()) && !entity.getTemplateCode().equals(db.getTemplateCode())) {
            if (service.getByCode(entity.getTemplateCode()) != null) {
                return Result.error("模板编码已存在");
            }
        }
        service.updateById(entity);
        return Result.OK("修改成功");
    }

    /**
     * 仅保存 Hiprint 模板 JSON（设计器保存）
     */
    @AutoLog(value = "打印模板-保存JSON")
    @Operation(summary = "打印模板-保存模板JSON")
    @PostMapping(value = "/saveJson")
    @RequiresPermissions("print:template:edit")
    public Result<String> saveJson(@RequestBody Map<String, String> body) {
        String id = body.get("id");
        String templateJson = body.get("templateJson");
        if (StringUtils.isBlank(id)) {
            return Result.error("id 不能为空");
        }
        if (templateJson == null) {
            return Result.error("templateJson 不能为空");
        }
        PrintTemplate db = service.getById(id);
        if (db == null) {
            return Result.error("记录不存在");
        }
        db.setTemplateJson(templateJson);
        service.updateById(db);
        return Result.OK("保存成功");
    }

    /**
     * 通过 id 删除
     */
    @AutoLog(value = "打印模板-删除")
    @Operation(summary = "打印模板-删除")
    @DeleteMapping(value = "/delete")
    @RequiresPermissions("print:template:delete")
    public Result<String> delete(@RequestParam(name = "id") String id) {
        service.removeById(id);
        return Result.OK("删除成功");
    }

    /**
     * 批量删除
     */
    @AutoLog(value = "打印模板-批量删除")
    @Operation(summary = "打印模板-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @RequiresPermissions("print:template:delete")
    public Result<String> deleteBatch(@RequestParam(name = "ids") String ids) {
        if (StringUtils.isBlank(ids)) {
            return Result.error("参数 ids 不能为空");
        }
        service.removeByIds(java.util.Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功");
    }

    /**
     * 通过 id 查询
     */
    @Operation(summary = "打印模板-通过id查询")
    @GetMapping(value = "/queryById")
    @RequiresPermissions("print:template:list")
    public Result<PrintTemplate> queryById(@RequestParam(name = "id") String id) {
        return Result.OK(service.getById(id));
    }

    /**
     * 通过编码查询（业务单据打印时调用）
     */
    @Operation(summary = "打印模板-通过编码查询")
    @GetMapping(value = "/queryByCode")
    @RequiresPermissions("print:template:list")
    public Result<PrintTemplate> queryByCode(@RequestParam(name = "code") String code) {
        PrintTemplate t = service.getByCode(code);
        if (t == null) {
            return Result.error("未找到模板: " + code);
        }
        return Result.OK(t);
    }
}
