package com.fizz.business.controller;

import com.fizz.business.domain.BizSendTemplate;
import com.fizz.business.domain.BizSendTemplateItem;
import com.fizz.business.domain.dto.SendTemplateItemsBatchSaveDTO;
import com.fizz.business.domain.vo.BizSendTemplateVO;
import com.fizz.business.service.IBizSendTemplateItemService;
import com.fizz.business.service.IBizSendTemplateService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 发送模板配置 Controller
 */
@RestController
@RequestMapping("/business/sendTemplate")
public class BizSendTemplateController extends BaseController {

    @Autowired
    private IBizSendTemplateService templateService;

    @Autowired
    private IBizSendTemplateItemService templateItemService;

    /**
     * 按模板编码获取模板（含明细）
     */
    @GetMapping("/{templateCode}")
    public AjaxResult getByCode(@PathVariable String templateCode) {
        BizSendTemplateVO vo = templateService.getTemplateWithItems(templateCode);
        if (vo == null) {
            return AjaxResult.error("Template not found");
        }
        return AjaxResult.success(vo);
    }

    /**
     * 更新模板主表（如 deviceName）
     */
    @PutMapping
    public AjaxResult updateTemplate(@RequestBody BizSendTemplate template) {
        if (template == null || template.getTemplateId() == null) {
            return AjaxResult.error("templateId is required");
        }
        template.setUpdateBy(SecurityUtils.getUsername());
        template.setUpdateTime(new Date());
        return toAjax(templateService.updateById(template));
    }

    /**
     * 批量更新模板明细（address/defaultValueRaw/enabled等）
     */
    @PutMapping("/items")
    public AjaxResult updateTemplateItems(@RequestBody List<BizSendTemplateItem> items) {
        if (items == null || items.isEmpty()) {
            return AjaxResult.success();
        }
        Date now = new Date();
        String username = SecurityUtils.getUsername();
        for (BizSendTemplateItem it : items) {
            it.setUpdateBy(username);
            it.setUpdateTime(now);
        }
        return toAjax(templateItemService.updateItemsBatch(items));
    }

    /**
     * 模板明细批量保存（新增/更新/删除）
     */
    @PutMapping("/items/batchSave")
    public AjaxResult batchSaveItems(@RequestBody SendTemplateItemsBatchSaveDTO dto) {
        if (dto == null || dto.getTemplateId() == null) {
            return AjaxResult.error("templateId is required");
        }
        try {
            Boolean ok = templateItemService.batchSave(
                    dto.getTemplateId(),
                    dto.getItems(),
                    dto.getDeleteIds(),
                    SecurityUtils.getUsername()
            );
            return toAjax(ok);
        } catch (IllegalArgumentException e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
