package com.muyu.enterprise.controller;

import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.domain.MessageTemplate;
import com.muyu.domain.req.MessageTemplateAddReq;
import com.muyu.domain.resp.MessageTemplateListResp;
import com.muyu.enterprise.cache.MessageTemplateCacheService;
import com.muyu.enterprise.service.MessageTemplateService;
import com.muyu.common.core.domain.Result;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: LiDongJia
 * @Package: com.muyu.car.controller
 * @Project: 2112-car-cloud-server
 * @name: MessageTypeController
 * @Date: 2024/9/18  20:18
 * @Description: 报文模版控制层
 */
@Log4j2
@RestController
@RequestMapping("messageTemplate")
@Tag(name = "报文模版控制层", description = "进行报文模版操作")
public class MessageTemplateController {

    @Autowired
    private MessageTemplateService messageTemplateService;

    //缓存
    @Autowired
    private MessageTemplateCacheService templateCacheService;


    /**
     * 报文模版列表查询
     *1
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Result<List<MessageTemplateListResp>> findAll() {
        List<MessageTemplate> list = messageTemplateService.list();
        List<MessageTemplateListResp> messageTemplateListRespList = list.stream()
                .map(template -> MessageTemplateListResp.messageTemplateBuild(
                                template
                        )
                ).collect(Collectors.toList());
//                ).toList();
        return Result.success(messageTemplateListRespList);
    }

    /**
     * 新增报文模版
     *
     * @param messageTemplateAddReq
     * @return
     */
    @PostMapping("/")
    public Result<String> save(@RequestBody MessageTemplateAddReq messageTemplateAddReq) {
        boolean save = messageTemplateService.save(MessageTemplate.addBuild(messageTemplateAddReq));
        //获取用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //获取租户唯一标识
        String databaseName = loginUser.getSysUser().getDatabaseName();
        //添加到缓存
        templateCacheService.put(databaseName+messageTemplateAddReq.getMessageTemplateName(), MessageTemplate.addBuild(messageTemplateAddReq));
        return Result.success(save? "新增成功" : "新增失败");
    }

    /**
     * 删除报文模版
     * @param messageTemplateId
     * @return
     */
    @DeleteMapping("/{messageTemplateId}")
    public Result<String> delete(@PathVariable("messageTemplateId") Long messageTemplateId) {
        messageTemplateService.removeById(messageTemplateId);
        return Result.success("删除成功");
    }

}
