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.TuningRunDto;
import com.yice.webadmin.app.dto.TuningTaskDto;
import com.yice.webadmin.app.model.TuningRun;
import com.yice.webadmin.app.model.TuningTask;
import com.yice.webadmin.app.service.TuningTaskService;
import com.yice.webadmin.app.vo.TuningTaskVo;
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/tuningTask")
public class TuningTaskController {

    @Autowired
    private TuningTaskService tuningTaskService;

    /**
     * 新增精调任务数据。
     *
     * @param tuningTaskDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"tuningTaskDto.taskId", "tuningTaskDto.searchString"})
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(@MyRequestBody TuningTaskDto tuningTaskDto,
                                    @MyRequestBody TuningRunDto tuningRunDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(tuningTaskDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        TuningTask tuningTask = MyModelUtil.copyTo(tuningTaskDto, TuningTask.class);
        TuningRun tuningRun = MyModelUtil.copyTo(tuningRunDto, TuningRun.class);
        tuningTask = tuningTaskService.saveAndCreateVersion(tuningTask, tuningRun);
        return ResponseResult.success(tuningTask.getTaskId());
    }

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

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

    /**
     * 列出符合过滤条件的精调任务列表。
     *
     * @param tuningTaskDtoFilter 过滤对象。
     * @param tuningRunDtoFilter  一对多从表过滤对象。
     * @param orderParam          排序参数。
     * @param pageParam           分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/list")
    public ResponseResult<MyPageData<TuningTaskVo>> list(
            @MyRequestBody TuningTaskDto tuningTaskDtoFilter,
            @MyRequestBody TuningRunDto tuningRunDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        }
        TuningTask tuningTaskFilter = MyModelUtil.copyTo(tuningTaskDtoFilter, TuningTask.class);
        TuningRun tuningRunFilter = MyModelUtil.copyTo(tuningRunDtoFilter, TuningRun.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, TuningTask.class);
        List<TuningTask> tuningTaskList =
                tuningTaskService.getTuningTaskListWithRelation(tuningTaskFilter, tuningRunFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(tuningTaskList, TuningTask.INSTANCE));
    }

    /**
     * 列出符合过滤条件的SFT任务列表。
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/listForTree")
    public ResponseResult<List<TuningTaskVo>> listForTree() {
        List<TuningTask> tuningTaskList =
                tuningTaskService.getTuningTaskListWithRelation(new TuningTask(), new TuningRun(), "");
        return ResponseResult.success(TuningTask.INSTANCE.fromModelList(tuningTaskList));
    }

    /**
     * 查看指定精调任务对象详情。
     *
     * @param taskId 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @GetMapping("/view")
    public ResponseResult<TuningTaskVo> view(@RequestParam Long taskId) {
        TuningTask tuningTask = tuningTaskService.getByIdWithRelation(taskId, MyRelationParam.full());
        if (tuningTask == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        TuningTaskVo tuningTaskVo = TuningTask.INSTANCE.fromModel(tuningTask);
        return ResponseResult.success(tuningTaskVo);
    }

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