package com.tykj.dev.config.controller;

import com.tykj.dev.config.domin.SystemConfig;
import com.tykj.dev.config.repository.SystemConfigDao;
import com.tykj.dev.config.service.SystemConfigService;
import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.config.vo.ConfigUpdateVo;
import com.tykj.dev.config.vo.ConfigVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

import static java.util.stream.Collectors.groupingBy;

/**
 * @author dengdiyi
 */
@RestController
@RequestMapping(value = "/config")
@AutoDocument
@Api(tags = "系统配置模块", description = "配置接口")
@Slf4j
public class ConfigController {
    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private SystemConfigDao systemConfigDao;

    @ApiOperation(value = "添加系统配置变量值", notes = "添加系统配置变量值")
    @PostMapping(value = "/add")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity add(@RequestBody @Validated ConfigVo configVo) {
        return ResponseEntity.ok(systemConfigService.add(configVo.toDo()));
    }

    @ApiOperation(value = "更新系统配置变量值", notes = "更新系统配置变量值")
    @PostMapping(value = "/update")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity update(@RequestBody @Validated ConfigUpdateVo configUpdateVo) {
        SystemConfig systemConfig = systemConfigService.getOne(configUpdateVo.getId());
        systemConfig.setLabel(configUpdateVo.getLabel());
        return ResponseEntity.ok(systemConfigService.update(systemConfig));
    }

    @ApiOperation(value = "删除系统配置变量", notes = "删除系统配置变量值")
    @PostMapping(value = "/delete/{id}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity delete(@PathVariable("id") int id) {
        systemConfigService.delete(id);
        return ResponseEntity.ok("删除成功");
    }

    @ApiOperation(value = "查询系统配置变量", notes = "查询系统配置变量值")
    @GetMapping(value = "/select")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity select() {
        Map<String, List<SystemConfig>> map = systemConfigDao.findAllByDeleteTag(0).stream().sorted(Comparator.comparing(SystemConfig::getValue)).collect(groupingBy(SystemConfig::getChineseName));
//        Map<String,List<String>> resultMap = new HashMap<>();
//        for (String s:map.keySet()) {
//            resultMap.put(s,map.get(s).stream().map(SystemConfig::getLabel).collect(Collectors.toList()));
//        }
        return ResponseEntity.ok(map);
    }
}
