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.utils.PageTools;
import org.matrix.database.entity.TestCase;
import org.matrix.database.entity.TestData;
import org.matrix.database.service.ITestCaseService;
import org.matrix.database.service.ITestDataService;
import org.matrix.database.vo.CommonResult;
import org.matrix.database.vo.CommonResultObj;
import org.matrix.database.vo.MoveAction;
import org.matrix.database.vo.TestCaseData;
import org.matrix.exception.GlobalException;
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.transaction.annotation.Transactional;
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.concurrent.ThreadPoolExecutor;

import static java.util.Optional.ofNullable;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mry
 * @since 2022-01-07
 */
@CrossOrigin
@RestController
@RequestMapping("/testCases")
@Api(tags = "对用例test_case的基本操作")
public class TestCaseController {

    private final ITestDataService testDataService;

    private final ITestCaseService testCaseService;

    public TestCaseController(ITestCaseService testCaseService, ITestDataService testDataService) {
        this.testCaseService = testCaseService;
        this.testDataService = testDataService;
    }

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

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

    /**
     * 输入用例主键id,查询出用例以及用例下包含的所有数据组
     *
     * @param testCaseId 用例id
     * @return {@link TestCaseData}
     */
    @GetMapping("/{testCaseId}")
    @ApiOperation(value = "根据用例id查,用例以及,用例下的数据组")
    @Cacheable(cacheNames = "caseCache",
            key = "#testCaseId", condition = "#p0 !=null",
            unless = "#result.statusCodeValue != 200")
    public ResponseEntity<CommonResultObj<TestCaseData>> findByIdTestCaseData(@PathVariable Long testCaseId) {
        TestCase byId = testCaseService.getById(testCaseId);
        if (byId == null) {
            throw new GlobalException("不存在用例");
        }
        TestCase testCase = ofNullable(testCaseService.getById(testCaseId))
                .orElseThrow(() -> new GlobalException(String.format("没有查到指定的用例，你提供的行为id是%d", testCaseId)));
        List<TestData> testDataList = ofNullable(testDataService.list(Wrappers.lambdaQuery(TestData.class)
                .eq(TestData::getTestCaseId, testCaseId)))
                .orElse(new ArrayList<>());
        TestCaseData testCaseData = new TestCaseData(testCase, testDataList);
        return CommonResult.success(testCaseData, "查询成功");
    }

    /**
     * 添加用例和数据组(可以单独添加用例)
     *
     * @param testCaseData 用例以及用例下的数据组
     * @return 添加的用例和数据组, 以及是否添加成功的提示信息
     */
    @PostMapping
    @ApiOperation(value = "添加用例和数据组")
    @Caching(
            put = {@CachePut(cacheNames = "caseCache", key = "#result.body.data.testCase.id",
                    condition = "#p0 !=null", unless = "#result.statusCodeValue != 200")
            },
            evict = {
                    @CacheEvict(cacheNames = "casePageCache", allEntries = true, condition = "#p0 != null "),
                    @CacheEvict(cacheNames = "caseCache", key = "#p0.testCase.id", condition = "#p0 != null ")})
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<CommonResultObj<TestCaseData>> insertTestCaseData(@RequestBody TestCaseData testCaseData) {
        Boolean testCaseBoolean = Optional.of(testCaseService.saveOrUpdate(testCaseData.getTestCase()))
                .orElseThrow(GlobalException::new);
        Long id = testCaseData.getTestCase().getId();
        boolean testDataBoolean = false;
        if (testCaseData.getTestData().size() != 0) {
            for (TestData testData : testCaseData.getTestData()) {
                testData.setTestCaseId(id);
            }
            testDataBoolean = testDataService.saveOrUpdateBatch(testCaseData.getTestData());
        }
        if (testCaseData.getTestData().size() == 0) {
            testDataBoolean = true;
        }
        return testCaseBoolean && testDataBoolean
                ? CommonResult.success(testCaseData, "添加成功")
                : CommonResult.failed("添加失败");
    }

    /**
     * 修改用例,根据用例id修改数据组
     *
     * @param testCaseData 用例以及用例下的数据组
     * @return {@link TestCaseData}
     */
    @PutMapping
    @ApiOperation(value = "修改用例以及数据组")
    @Transactional(rollbackFor = Exception.class)
    @Caching(
            put = {@CachePut(cacheNames = "caseCache", key = "#result.body.data.testCase.id",
                    condition = "#p0 !=null", unless = "#result.statusCodeValue != 200"),
            },
            evict = {
                    @CacheEvict(cacheNames = "casePageCache", allEntries = true, condition = "#p0 != null "),
                    @CacheEvict(cacheNames = "caseCache", key = "#p0.testCase.id", condition = "#p0 != null ")})
    public ResponseEntity<CommonResultObj<TestCaseData>> updateTestCaseData(@RequestBody TestCaseData testCaseData) {
        Boolean update = Optional.of(testCaseService.updateById(testCaseData.getTestCase()))
                .orElseThrow(GlobalException::new);
        Long id = testCaseData.getTestCase().getId();
        testCaseData.getTestData().forEach(
                action -> action.setTestCaseId(id)
        );
        Boolean delete = Optional.of(testDataService.remove(Wrappers.lambdaQuery(TestData.class)
                        .eq(TestData::getTestCaseId, testCaseData.getTestCase().getId())))
                .orElseThrow(GlobalException::new);
        Boolean saveOrUpdate = Optional.of(testDataService.saveOrUpdateBatch(testCaseData.getTestData()))
                .orElseThrow(() -> new GlobalException("失败"));
        return update
                ? CommonResult.success(testCaseData, "修改成功")
                : CommonResult.failed(testCaseData, "修改失败");
    }

    /**
     * 删除用例和数据组
     *
     * @param testCaseId 用例id
     * @return 是否删除成功
     */
    @DeleteMapping("/{testCaseId}")
    @ApiOperation(value = "删除行用例和数据组")
    @Transactional(rollbackFor = Exception.class)
    @Caching(evict = {
            @CacheEvict(cacheNames = "casePageCache", allEntries = true, condition = "#p0 != null "),
            @CacheEvict(cacheNames = "caseCache", key = "#testCaseId", condition = "#p0 != null")})
    public ResponseEntity<CommonResultObj<MoveAction>> deleteTestCaseData(@PathVariable Long testCaseId) {
        Boolean testCaseBoolean = Optional.of(testCaseService.removeById(testCaseId))
                .orElseThrow(() -> new GlobalException(String.format("没有查到指定的用例，你提供的用例id是%d", testCaseId)));
        Boolean testDataBoolean = Optional.of(testDataService.remove(Wrappers.lambdaQuery(TestData.class)
                        .eq(TestData::getTestCaseId, testCaseId)))
                .orElseThrow(() -> new GlobalException(String.format("没有查到指定的数据组，你提供的数据组id是%d", testCaseId)));
        return testCaseBoolean
                ? CommonResult.success("删除成功")
                : CommonResult.failed("删除失败或不存在");
    }

}
