package org.matrix.autotest.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.database.vo.PageResult;
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;
    }

    @ApiOperation(value = "分页查询用例")
    @PostMapping("/page")
    public ResponseEntity<CommonResultObj<PageResult>> findAllPage(@RequestBody PageResult pageResult) {
        pageResult = moveService.pageAll(pageResult);
        if (pageResult.getRows() != null) {
            return CommonResult.success(pageResult, "查询成功");
        } else {
            return CommonResult.failed("查询失败或无数据");
        }
    }

    /**
     * 输入行为主键id,查询出行为以及行为下包含的所有动作
     *
     * @param moveId 行为id
     * @return {@link MoveAction}
     */
    @ApiOperation(value = "根据项目id查,行为以及,行为下的动作")
    @GetMapping("/{moveId}")
    public ResponseEntity<CommonResultObj<MoveAction>> findById(@PathVariable Long moveId) {
        // todo 关于空判断的后面可以再处理
        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 CommonResult.success(ma, "查询成功");
    }

    @ApiOperation(value = "根据项目id查行为")
    @GetMapping("project/{projectId}")
    public ResponseEntity<CommonResultObj<List<Move>>> findByProjectIdMove(@PathVariable Integer projectId) {
        QueryWrapper<Move> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", projectId);
        List<Move> list = moveService.list(queryWrapper);
        if (list.size() != 0) {
            return CommonResult.success(list, "查询成功");
        } else {
            return CommonResult.failed("查询失败或无数据");
        }
    }

    @ApiOperation(value = "添加行为和动作")
    @PostMapping
    public ResponseEntity<CommonResultObj<MoveAction>> insertMoveAction(@RequestBody MoveAction moveAction) {
        boolean save = moveService.save(moveAction.getMove());
        Integer id = Math.toIntExact(moveAction.getMove().getId());
        for (Action action : moveAction.getAction()) {
            action.setMoveId(id);
        }
        boolean saveBatch = actionService.saveBatch(moveAction.getAction());
        if (save && saveBatch) {
            return CommonResult.success(moveAction, "添加成功");
        } else {
            return CommonResult.failed("添加失败");
        }
    }

    /**
     * 修改行为,根据行为id修改动作
     *
     * @param moveAction
     * @return
     */
    @ApiOperation(value = "修改行为和动作")
    @PutMapping
    public ResponseEntity<CommonResultObj<MoveAction>> updateMoveAction(@RequestBody MoveAction moveAction) {
        Optional<Boolean> aBoolean = ofNullable(moveService.updateById(moveAction.getMove()));
//        Optional.ofNullable(actionService.update(Wrappers.))
        if (aBoolean.get()) {
            return CommonResult.success(moveAction, "修改成功");
        } else {
            return CommonResult.failed("修改失败");
        }
    }

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

}

