package com.izouma.nineth.web;

import com.alibaba.fastjson.JSONObject;
import com.izouma.nineth.config.EventNames;
import com.izouma.nineth.config.GeneralProperties;
import com.izouma.nineth.domain.SysConfig;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.SysConfigRepo;
import com.izouma.nineth.service.CacheService;
import com.izouma.nineth.service.SysConfigService;
import com.izouma.nineth.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sysConfig")
@AllArgsConstructor
public class SysConfigController extends BaseController {
    private SysConfigService  sysConfigService;
    private SysConfigRepo     sysConfigRepo;
    private RocketMQTemplate  rocketMQTemplate;
    private GeneralProperties generalProperties;
    private CacheService      cacheService;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public SysConfig save(@RequestBody SysConfig record) {
        record = sysConfigRepo.save(record);
        cacheService.clearSysConfigGet();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", EventNames.CONFIG_CHANGE);
        JSONObject data = new JSONObject();
        data.put("name", record.getName());
        data.put("value", record.getValue());
        jsonObject.put("data", data);
        rocketMQTemplate.convertAndSend(generalProperties.getBroadcastEventTopic(), jsonObject);

        return record;
    }


    @PostMapping("/all")
    public Page<SysConfig> all(@RequestBody PageQuery pageQuery) {
        return sysConfigService.all(pageQuery);
    }

    @GetMapping("/get/{id}")
    @Cacheable("sysConfigGet")
    public Object get(@PathVariable String id) {
        if (id.contains(",")) {
            Map<String, SysConfig> map = new HashMap<>();
            for (String name : id.split(",")) {
                map.put(name, sysConfigRepo.findByName(name).orElseThrow(null));
            }
            return map;
        } else {
            return sysConfigRepo.findByName(id).orElseThrow(new BusinessException("无记录"));
        }
    }

    @GetMapping("/getValue/{id}")
    public String getValue(@PathVariable String id) {
        return sysConfigRepo.findByName(id).map(SysConfig::getValue).orElse(null);
    }

    @GetMapping("/getDecimal/{id}")
    public BigDecimal getDecimal(@PathVariable String id) {
        return sysConfigService.getBigDecimal(id);
    }

    @PostMapping("/del/{id}")
    public void del(@PathVariable String id) {
        sysConfigRepo.deleteById(id);
    }

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<SysConfig> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }
}

