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.ModelDeployDto;
import com.yice.webadmin.app.dto.ModelManageDto;
import com.yice.webadmin.app.dto.ModelTaskDto;
import com.yice.webadmin.app.dto.ModelVersionDto;
import com.yice.webadmin.app.model.ModelDeploy;
import com.yice.webadmin.app.model.ModelManage;
import com.yice.webadmin.app.model.ModelTask;
import com.yice.webadmin.app.model.ModelVersion;
import com.yice.webadmin.app.service.ModelManageService;
import com.yice.webadmin.app.service.TuningRunService;
import com.yice.webadmin.app.vo.ModelManageVo;
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/modelManage")
public class ModelManageController {

    @Autowired
    private ModelManageService modelManageService;
    @Autowired
    private TuningRunService tuningRunService;


    /**
     * 新增模型管理数据，及其关联的从表数据。
     *
     * @param modelManageDto 新增主表对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"modelManageDto.modelId", "modelManageDto.searchString"})
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(
            @MyRequestBody ModelManageDto modelManageDto,
            @MyRequestBody ModelVersionDto modelVersionDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(modelManageDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        ModelManage modelManage = MyModelUtil.copyTo(modelManageDto, ModelManage.class);
        ModelVersion modelVersion = MyModelUtil.copyTo(modelVersionDto, ModelVersion.class);
        modelManage = this.tuningRunService.createToModel(modelManage, modelVersion);
        return ResponseResult.success(modelManage.getModelId());
    }

    /**
     * 更新模型管理数据。
     *
     * @param modelManageDto 更新对象。
     * @return 应答结果对象。
     */
    @ApiOperationSupport(ignoreParameters = {"modelManageDto.searchString"})
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody ModelManageDto modelManageDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(modelManageDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        ModelManage modelManage = MyModelUtil.copyTo(modelManageDto, ModelManage.class);
        ModelManage originalModelManage = modelManageService.getById(modelManage.getModelId());
        if (originalModelManage == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [数据] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!modelManageService.update(modelManage, originalModelManage)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 列出符合过滤条件的模型管理列表。
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/listForTree")
    public ResponseResult<List<ModelManageVo>> listForTree(@MyRequestBody ModelManageDto modelManageDtoFilter) {
        ModelManage modelManageFilter = MyModelUtil.copyTo(modelManageDtoFilter, ModelManage.class);
        List<ModelManage> modelManageList =
                modelManageService.getModelManageListWithRelation(modelManageFilter, new ModelVersion(), null, null, "");
        return ResponseResult.success(ModelManage.INSTANCE.fromModelList(modelManageList));
    }


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

    /**
     * 列出符合过滤条件的模型管理列表。
     *
     * @param modelManageDtoFilter  过滤对象。
     * @param modelVersionDtoFilter 一对多从表过滤对象。
     * @param modelTaskDtoFilter    一对多从表过滤对象。
     * @param modelDeployDtoFilter  一对多从表过滤对象。
     * @param orderParam            排序参数。
     * @param pageParam             分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/list")
    public ResponseResult<MyPageData<ModelManageVo>> list(
            @MyRequestBody ModelManageDto modelManageDtoFilter,
            @MyRequestBody ModelVersionDto modelVersionDtoFilter,
            @MyRequestBody ModelTaskDto modelTaskDtoFilter,
            @MyRequestBody ModelDeployDto modelDeployDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        }
        ModelManage modelManageFilter = MyModelUtil.copyTo(modelManageDtoFilter, ModelManage.class);
        ModelVersion modelVersionFilter = MyModelUtil.copyTo(modelVersionDtoFilter, ModelVersion.class);
        ModelTask modelTaskFilter = MyModelUtil.copyTo(modelTaskDtoFilter, ModelTask.class);
        ModelDeploy modelDeployFilter = MyModelUtil.copyTo(modelDeployDtoFilter, ModelDeploy.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, ModelManage.class);
        List<ModelManage> modelManageList =
                modelManageService.getModelManageListWithRelation(modelManageFilter, modelVersionFilter, modelTaskFilter, modelDeployFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(modelManageList, ModelManage.INSTANCE));
    }

    /**
     * 列出符合过滤条件的模型管理列表。
     *
     * @param modelManageDtoFilter  过滤对象。
     * @param modelVersionDtoFilter 一对多从表过滤对象。
     * @param modelTaskDtoFilter    一对多从表过滤对象。
     * @param modelDeployDtoFilter  一对多从表过滤对象。
     * @param orderParam            排序参数。
     * @param pageParam             分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/myList")
    public ResponseResult<MyPageData<ModelManageVo>> myList(
            @MyRequestBody ModelManageDto modelManageDtoFilter,
            @MyRequestBody ModelVersionDto modelVersionDtoFilter,
            @MyRequestBody ModelTaskDto modelTaskDtoFilter,
            @MyRequestBody ModelDeployDto modelDeployDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        }
        ModelManage modelManageFilter = MyModelUtil.copyTo(modelManageDtoFilter, ModelManage.class);
        ModelVersion modelVersionFilter = MyModelUtil.copyTo(modelVersionDtoFilter, ModelVersion.class);
        ModelTask modelTaskFilter = MyModelUtil.copyTo(modelTaskDtoFilter, ModelTask.class);
        ModelDeploy modelDeployFilter = MyModelUtil.copyTo(modelDeployDtoFilter, ModelDeploy.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, ModelManage.class);
        modelManageFilter.setCreateUserId(TokenData.takeFromRequest().getUserId());
        List<ModelManage> modelManageList =
                modelManageService.getModelManageListWithRelation(modelManageFilter, modelVersionFilter, modelTaskFilter, modelDeployFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(modelManageList, ModelManage.INSTANCE));
    }

    /**
     * 查看指定模型管理对象详情。
     *
     * @param modelId 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @GetMapping("/view")
    public ResponseResult<ModelManageVo> view(@RequestParam Long modelId) {
        ModelManage modelManage = modelManageService.getByIdWithRelation(modelId, MyRelationParam.full());
        if (modelManage == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        ModelManageVo modelManageVo = ModelManage.INSTANCE.fromModel(modelManage);
        return ResponseResult.success(modelManageVo);
    }

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