package com.yice.webadmin.app.controller;

import com.github.pagehelper.page.PageMethod;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.yice.common.core.annotation.MyRequestBody;
import com.yice.common.core.constant.ErrorCodeEnum;
import com.yice.common.core.object.*;
import com.yice.common.core.util.MyCommonUtil;
import com.yice.common.core.util.MyModelUtil;
import com.yice.common.core.util.MyPageUtil;
import com.yice.common.log.annotation.OperationLog;
import com.yice.common.log.model.constant.SysOperationLogType;
import com.yice.webadmin.app.dto.ModelInstanceDto;
import com.yice.webadmin.app.model.ModelInstance;
import com.yice.webadmin.app.service.ModelInstanceService;
import com.yice.webadmin.app.vo.ModelInstanceVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 模型实例管理操作控制器类。
 *
 * @author linking
 * @date 2023-04-13
 */
@Api(tags = "模型实例管理接口")
@Slf4j
@RestController
@RequestMapping("/admin/app/modelInstance")
public class ModelInstanceController {

    @Autowired
    private ModelInstanceService modelInstanceService;

    /**
     * 新增知识图谱管理数据。
     *
     * @param modelInstanceDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"modelInstanceDto.deployId"})
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(@MyRequestBody ModelInstanceDto modelInstanceDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(modelInstanceDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        ModelInstance modelInstance = MyModelUtil.copyTo(modelInstanceDto, ModelInstance.class);
        modelInstance = modelInstanceService.saveNew(modelInstance);
        return ResponseResult.success(modelInstance.getDeployId());
    }

    /**
     * 更新知识图谱管理数据。
     *
     * @param modelInstanceDto 更新对象。
     * @return 应答结果对象。
     */
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody ModelInstanceDto modelInstanceDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(modelInstanceDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        ModelInstance modelInstance = MyModelUtil.copyTo(modelInstanceDto, ModelInstance.class);
        ModelInstance originalModelInstance = modelInstanceService.getById(modelInstance.getDeployId());
        if (originalModelInstance == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [数据] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!modelInstanceService.update(modelInstance, originalModelInstance)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 删除知识图谱管理数据。
     *
     * @param deployId 删除对象主键Id。
     * @return 应答结果对象。
     */
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/delete")
    public ResponseResult<Void> delete(@MyRequestBody Long deployId) {
        if (MyCommonUtil.existBlankArgument(deployId)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        return this.doDelete(deployId);
    }

    /**
     * 批量删除知识图谱管理数据。
     *
     * @param deployIdList 待删除对象的主键Id列表。
     * @return 应答结果对象。
     */
    @OperationLog(type = SysOperationLogType.DELETE_BATCH)
    @PostMapping("/deleteBatch")
    public ResponseResult<Void> deleteBatch(@MyRequestBody List<Long> deployIdList) {
        if (MyCommonUtil.existBlankArgument(deployIdList)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        for (Long deployId : deployIdList) {
            ResponseResult<Void> responseResult = this.doDelete(deployId);
            if (!responseResult.isSuccess()) {
                return responseResult;
            }
        }
        return ResponseResult.success();
    }

    /**
     * 列出符合过滤条件的知识图谱管理列表。
     *
     * @param modelInstanceDtoFilter 过滤对象。
     * @param orderParam 排序参数。
     * @param pageParam 分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/list")
    public ResponseResult<MyPageData<ModelInstanceVo>> list(
            @MyRequestBody ModelInstanceDto modelInstanceDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        }
        ModelInstance modelInstanceFilter = MyModelUtil.copyTo(modelInstanceDtoFilter, ModelInstance.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, ModelInstance.class);
        List<ModelInstance> modelInstanceList =
                modelInstanceService.getModelInstanceListWithRelation(modelInstanceFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(modelInstanceList, ModelInstance.INSTANCE));
    }

    /**
     * 查看指定知识图谱管理对象详情。
     *
     * @param deployId 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @GetMapping("/view")
    public ResponseResult<ModelInstanceVo> view(@RequestParam Long deployId) {
        ModelInstance modelInstance = modelInstanceService.getByIdWithRelation(deployId, MyRelationParam.full());
        if (modelInstance == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        ModelInstanceVo modelInstanceVo = MyModelUtil.copyTo(modelInstance, ModelInstanceVo.class);
        return ResponseResult.success(modelInstanceVo);
    }

    private ResponseResult<Void> doDelete(Long deployId) {
        String errorMessage;
        // 验证关联Id的数据合法性
        ModelInstance originalModelInstance = modelInstanceService.getById(deployId);
        if (originalModelInstance == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!modelInstanceService.remove(deployId)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }
}
