package org.matrix.autotest.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.matrix.autotest.entity.EnvStaticNameTips;
import org.matrix.autotest.utils.PageTools;
import org.matrix.database.entity.Environment;
import org.matrix.database.service.IEnvironmentService;
import org.matrix.database.vo.CommonResult;
import org.matrix.database.vo.CommonResultObj;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * <p>
 * 实例表，项目对应的环境实例，例如：实验室环境，开发环境等 前端控制器
 * </p>
 *
 * @author mry
 * @since 2022-01-07
 */
@CrossOrigin
@RestController
@RequestMapping("/environments")
@Api(tags = "对环境environment的基本操作")
public class EnvironmentController {

    private final IEnvironmentService environmentService;

    public EnvironmentController(IEnvironmentService environmentService) {
        this.environmentService = environmentService;
    }

    /**
     * 分页查询所有环境
     *
     * @param pageSize  每页多少条数据
     * @param pageNum   当前第几页
     * @param projectId 项目id
     * @return 分页查询的结果, 环境
     */
    @ApiOperation(value = "分页查询环境")
    @GetMapping("/page")
    @Cacheable(cacheNames = "environmentPageCache",
            key = "#pageSize + '_' + #pageNum + '_' + #projectId",
            condition = "#pageNum != null && #pageSize != null",
            unless = "#result.statusCodeValue != 200")
    public ResponseEntity<CommonResultObj<Page<Environment>>> findPageEnvironment(
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam Long projectId) {
        Page<Environment> results = Optional.ofNullable(environmentService.page(Page.of(pageNum, pageSize), Wrappers.lambdaQuery(Environment.class)
                        .eq(Environment::getProjectId, projectId)))
                .orElse(new Page<>());
        PageTools.pageTool(pageSize, pageNum, results);
        return CommonResult.success(results, "查询成功");
    }

    /**
     * 条件查询环境
     *
     * @param pageSize  每页多少条数据
     * @param pageNum   当前第几页
     * @param name      环境名称
     * @param projectId 项目id
     * @return 分页查询的结果, 环境
     */
    @ApiOperation(value = "条件查询环境")
    @GetMapping("/condition")
    public ResponseEntity<CommonResultObj<Page<Environment>>> findConditionEnvironment(
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(required = false, defaultValue = "") String name,
            @RequestParam Long projectId) {
        Page<Environment> results = Optional.ofNullable(environmentService.page(Page.of(pageNum, pageSize), Wrappers.lambdaQuery(Environment.class)
                        .eq(Environment::getProjectId, projectId)
                        .like(StringUtils.hasLength(name), Environment::getName, name)))
                .orElse(new Page<>());
        PageTools.pageTool(pageSize, pageNum, results);
        return CommonResult.success(results, "查询成功");
    }

    /**
     * 添加环境
     *
     * @param environment 环境对象
     * @return 添加的环境, 以及是否添加成功的提示信息
     */
    @ApiOperation(value = "添加环境")
    @PostMapping
    @Caching(
            put = {@CachePut(cacheNames = "environmentPageCache", key = "#result.body.data.id",
                    condition = "#p0 != null", unless = "#result.statusCodeValue != 200")
            },
            evict = {@CacheEvict(cacheNames = "environmentPageCache", allEntries = true)}
    )
    public ResponseEntity<CommonResultObj<Environment>> insertEnvironment(@RequestBody Environment environment) {
        return CommonResult.pred(environmentService::save, environment, "添加成功", "添加失败");
    }

    /**
     * 修改环境
     *
     * @param environment 环境对象
     * @return 修改后的环境, 以及是否修改成功的提示信息
     */
    @ApiOperation(value = "修改环境")
    @PutMapping
    @Caching(
            put = {@CachePut(cacheNames = "environmentPageCache", key = "#result.body.data.id",
                    condition = "#p0 != null", unless = "#result.statusCodeValue != 200")
            },
            evict = {@CacheEvict(cacheNames = "environmentPageCache", allEntries = true)}
    )
    public ResponseEntity<CommonResultObj<Environment>> updateEnvironment(@RequestBody Environment environment) {
        return CommonResult.pred(environmentService::updateById, environment, "修改成功", "修改失败");
    }

    /**
     * 删除环境
     *
     * @param id 环境id
     * @return 删除的环境id, 以及是否删除成功的提示信息
     */
    @ApiOperation(value = "根据主键id删除环境")
    @DeleteMapping("/{id}")
    @CacheEvict(cacheNames = "environmentPageCache", allEntries = true, condition = "#p0 != null")
    public ResponseEntity<CommonResultObj<Long>> deleteEnvironment(@PathVariable Long id) {
        return CommonResult.pred(environmentService::removeById, id, "删除成功", "删除失败或id不存在");
    }

    /**
     * 环境静态变量语法提示
     *
     * @param projectId 项目id
     * @return 该项目下的环境名称，以及静态变量k-v
     */
    @ApiOperation(value = "环境静态变量语法提示")
    @GetMapping("/staticName")
    public ResponseEntity<List<EnvStaticNameTips>> getStaticNameTips(@RequestParam Long projectId) {
        List<EnvStaticNameTips> list = new ArrayList<>();
        List<Environment> results = Optional.ofNullable(environmentService.list(Wrappers.lambdaQuery(Environment.class)
                        .eq(Environment::getProjectId, projectId)))
                .orElse(new ArrayList<>());
        for (Environment result : results) {
            Set<String> staNames = result.getVariable().keySet();
            for (String staName : staNames) {
                EnvStaticNameTips envStaticNameTips = new EnvStaticNameTips();
                envStaticNameTips.setStaName(staName);
                envStaticNameTips.setEnvName(result.getName());
                String value = result.getVariable().get(staName);
                envStaticNameTips.setStaValue(value);
                list.add(envStaticNameTips);
            }
        }
        return ResponseEntity.ok(list);
    }
}
