package cn.qg.qaplatform.mock.controller;

import cn.qg.qaplatform.config.SwitchDataSource;
import cn.qg.qaplatform.mock.entity.Mock;
import cn.qg.qaplatform.mock.service.MockService;
import cn.qg.qaplatform.utils.JsonResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
public class MockController {

    @Autowired
    MockService mockService;

    @RequestMapping(value = "/mock/**", method = { RequestMethod.GET, RequestMethod.POST})
    public void mockMethod() {}

    @PostMapping("/add/mock")
    public JsonResult addMock(@RequestBody Mock mock) {
        SwitchDataSource.dataSourceSwitch("pre", "qa");
        return JsonResult.success(mockService.save(mock));
    }

    @GetMapping("/list/mock")
    public JsonResult getMockList(Integer pageNum, Integer pageSize) {
        SwitchDataSource.dataSourceSwitch("pre", "qa");
        IPage<Mock> page = new Page<>(pageNum, pageSize);
        IPage<Mock> pageEntity = mockService.page(page);
        Map<String, Object> map = new HashMap<>();
        map.put("list", pageEntity.getRecords());
        map.put("total", pageEntity.getTotal());
        return JsonResult.success(map);
    }

    @PostMapping("/edit/mock")
    public JsonResult modifyMock(@RequestBody Mock mock) {
        SwitchDataSource.dataSourceSwitch("pre", "qa");
        return JsonResult.success(mockService.saveOrUpdate(mock));
    }
}
