package org.matrix.autotest.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.matrix.database.entity.Action;
import org.matrix.database.entity.Move;
import org.matrix.database.service.IActionService;
import org.matrix.database.service.IMoveService;
import org.matrix.database.vo.CommonResult;
import org.matrix.database.vo.CommonResultObj;
import org.matrix.database.vo.MoveAction;
import org.matrix.exception.GlobalException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

import static java.util.Optional.ofNullable;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mry
 * @since 2022-01-07
 */
@CrossOrigin
@RestController
@RequestMapping("/moves")
@Api(tags = "对行为move的基本操作")
public class MoveController {

    private final IActionService actionService;

    private final IMoveService moveService;

    public MoveController(IMoveService moveService, IActionService actionService) {
        this.moveService = moveService;
        this.actionService = actionService;
    }

    /**
     * 输入行为主键id,查询出行为以及行为下包含的所有动作
     *
     * @param moveId 行为id
     * @return {@link MoveAction}
     */
    @ApiOperation(value = "根据行为id查,行为以及,行为下的动作")
    @GetMapping("/{moveId}")
    public ResponseEntity<CommonResultObj<MoveAction>> findById(@PathVariable Long moveId) {
        Move byId = moveService.getById(moveId);
        if (byId == null) {
            throw new GlobalException("不存在行为");
        }
        Move move = ofNullable(moveService.getById(moveId))
                .orElseThrow(() -> new GlobalException(String.format("没有查到指定的行为,你提供的行为id是%d", moveId)));
        List<Action> actionList = ofNullable(actionService.list(Wrappers.lambdaQuery(Action.class)
                .eq(Action::getMoveId, moveId)))
                .orElse(new ArrayList<>());
        MoveAction ma = new MoveAction(move, actionList);
        return ma != null
                ? CommonResult.success(ma, "查询成功")
                : CommonResult.failed(ma, "查询失败或无数据");
    }

    /**
     * 根据项目id查询行为
     *
     * @param projectId 项目id
     * @return 查询到的行为, 以及是否查询成功的提示信息
     */
    @ApiOperation(value = "根据项目id查行为")
    @GetMapping("project/{projectId}")
    public ResponseEntity<CommonResultObj<List<Move>>> findByProjectIdMove(@PathVariable Integer projectId) {
        List<Move> results = ofNullable(moveService.list(Wrappers.lambdaQuery(Move.class)
                .eq(Move::getProjectId, projectId)))
                .orElse(new ArrayList<>());
        return results.size() != 0
                ? CommonResult.success(results, "查询成功")
                : CommonResult.failed(results, "查询失败或无数据");
    }

    /**
     * 添加行为和动作(可以单独添加行为)
     *
     * @param moveAction 行为以及行为下的动作
     * @return 添加的行为和动作, 以及是否添加成功的提示信息
     */
    @ApiOperation(value = "添加行为和动作")
    @PostMapping
    public ResponseEntity<CommonResultObj<MoveAction>> insertMoveAction(@RequestBody MoveAction moveAction) {
        Boolean moveBoolean = Optional.of(moveService.save(moveAction.getMove()))
                .orElseThrow(GlobalException::new);
        Integer id = Math.toIntExact(moveAction.getMove().getId());
        if (moveAction.getAction().size() != 0) {
            for (Action action : moveAction.getAction()) {
                action.setMoveId(id);
            }
        }
        boolean actionBoolean = actionService.saveBatch(moveAction.getAction());
        if (moveAction.getAction().size() == 0) {
            actionBoolean = true;
        }
        return moveBoolean && actionBoolean
                ? CommonResult.success(moveAction, "添加成功")
                : CommonResult.failed("添加失败");
    }

    /**
     * 修改行为,根据行为id修改动作
     *
     * @param moveAction 行为以及行为下的动作
     * @return {@link MoveAction}
     */
    @ApiOperation(value = "修改行为,修改动作,添加动作")
    @PutMapping
    public ResponseEntity<CommonResultObj<MoveAction>> updateMoveAction(@RequestBody MoveAction moveAction) {
        Boolean moveBoolean = Optional.of(moveService.updateById(moveAction.getMove()))
                .orElseThrow(() -> new GlobalException("修改失败"));
        Boolean actionBoolean = Optional.of(actionService.updateBatchById(moveAction.getAction()))
                .orElseThrow(() -> new GlobalException("修改失败"));
        return moveBoolean || actionBoolean
                ? CommonResult.success(moveAction, "修改成功")
                : CommonResult.failed(moveAction, "修改失败");
    }

    @ApiOperation(value = "删除行为和动作")
    @DeleteMapping("/{moveId}")
    public ResponseEntity<CommonResultObj<MoveAction>> deleteMoveAction(@PathVariable Long moveId) {
        Boolean moveBoolean = Optional.of(moveService.removeById(moveId))
                .orElseThrow(() -> new GlobalException(String.format("没有查到指定的行为,你提供的行为id是%d", moveId)));
        Boolean actionBoolean = Optional.of(actionService.remove(Wrappers.lambdaQuery(Action.class)
                        .eq(Action::getMoveId, moveId)))
                .orElseThrow(() -> new GlobalException(String.format("没有查到指定的行为,你提供的行为id是%d", moveId)));
        return moveBoolean && actionBoolean
                ? CommonResult.success("删除成功")
                : CommonResult.failed("删除失败或不存在");
    }

}
