package com.gitee.sop.admin.controller.serve;

import com.gitee.fastmybatis.core.PageInfo;
import com.gitee.fastmybatis.core.query.Query;
import com.gitee.sop.admin.common.dto.StatusUpdateDTO;
import com.gitee.sop.admin.common.req.StatusUpdateParam;
import com.gitee.sop.admin.common.resp.Result;
import com.gitee.sop.admin.common.util.CopyUtil;
import com.gitee.sop.admin.controller.serve.param.ApiInfoPageParam;
import com.gitee.sop.admin.controller.serve.vo.ApiInfoVO;
import com.gitee.sop.admin.dao.entity.ApiInfo;
import com.gitee.sop.admin.service.serve.ApiInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


/**
 * 接口管理
 *
 * @author 六如
 */
@RestController
@RequestMapping("serve/api")
public class ApiInfoController {

    @Autowired
    private ApiInfoService apiInfoService;

    /**
     * 分页查询
     *
     * @param param
     * @return
     */
    @GetMapping("/page")
    public Result<PageInfo<ApiInfo>> page(ApiInfoPageParam param) {
        Query query = param.toQuery();
        query.orderByDesc("id");
        PageInfo<ApiInfo> pageInfo = apiInfoService.page(query);
        pageInfo.convert(apiInfo -> CopyUtil.copyBean(apiInfo, ApiInfoVO::new));
        return Result.ok(pageInfo);
    }

    /**
     * 查询全部
     *
     * @param param
     * @return
     */
    @GetMapping("/listAll")
    public Result<List<ApiInfoVO>> listAll(ApiInfoPageParam param) {
        Query query = param.toQuery();
        query.orderByDesc("id");
        List<ApiInfo> list = apiInfoService.list(query);
        return Result.ok(CopyUtil.copyList(list, ApiInfoVO::new));
    }

    /**
     * 新增记录
     *
     * @param user
     * @return 返回添加后的主键值
     */
    @PostMapping("/add")
    public Result<Long> add(@Validated @RequestBody ApiInfo user) {
        apiInfoService.save(user);
        // 返回添加后的主键值
        return Result.ok(user.getId());
    }

    /**
     * 修改记录
     *
     * @param user 表单数据
     * @return 返回影响行数
     */
    @PostMapping("/update")
    public Result<Integer> update(@Validated @RequestBody ApiInfo user) {
        return Result.ok(apiInfoService.update(user));
    }

    /**
     * 修改状态
     *
     * @param param 表单数据
     * @return 返回影响行数
     */
    @PostMapping("/updateStatus")
    public Result<Integer> updateStatus(@Validated @RequestBody StatusUpdateParam param) {
        StatusUpdateDTO statusUpdateDTO = CopyUtil.copyBean(param, StatusUpdateDTO::new);
        return Result.ok(apiInfoService.updateStatus(statusUpdateDTO));
    }

}
