package com.yice.webadmin.app.controller;

import com.alibaba.fastjson.JSONObject;
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.annotation.NoAuthInterface;
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.ModelCompressDto;
import com.yice.webadmin.app.dto.ModelTaskDto;
import com.yice.webadmin.app.model.ModelCompress;
import com.yice.webadmin.app.model.ModelTask;
import com.yice.webadmin.app.service.ModelCompressService;
import com.yice.webadmin.app.service.ModelTaskService;
import com.yice.webadmin.app.service.ModelVersionService;
import com.yice.webadmin.app.vo.ModelCompressVo;
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.Date;
import java.util.List;

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

    @Autowired
    private ModelCompressService modelCompressService;
    @Autowired
    private ModelTaskService modelTaskService;
    @Autowired
    private ModelVersionService modelVersionService;

    /**
     * 新增模型压缩数据，及其关联的从表数据。
     *
     * @param modelCompressDto 新增主表对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"modelCompressDto.taskId", "modelCompressDto.searchString"})
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(
            @MyRequestBody ModelCompressDto modelCompressDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(modelCompressDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        ModelCompress modelCompress = MyModelUtil.copyTo(modelCompressDto, ModelCompress.class);
        modelCompress = modelCompressService.saveNew(modelCompress);
        return ResponseResult.success(modelCompress.getTaskId());
    }

    @NoAuthInterface
    @OperationLog(type = SysOperationLogType.UPLOAD, saveResponse = false)
    @PostMapping("/postCompressStatus")
    public ResponseResult<Void> postCompressStatus(@MyRequestBody Long taskId,
                                                   @MyRequestBody Long runTime,
                                                   @MyRequestBody Integer taskStatus) {
        String errorMessage;
        ModelCompress modelCompress = this.modelCompressService.getById(taskId);
        if (modelCompress == null) {
            errorMessage = "数据验证失败，当前模型压缩并不存在，请联系管理员！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        modelCompress.setTaskStatus(taskStatus);
        modelCompress.setUpdateTime(new Date());
        if (!modelCompressService.updateById(modelCompress)) {
            errorMessage = "型压缩信息提交错误！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }

    /**
     * 修改模型压缩数据，及其关联的从表数据。
     *
     * @param modelCompressDto 修改后的对象。
     * @param modelTaskDto     一对一模型任务从表Dto。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"modelCompressDto.taskId", "modelCompressDto.searchString"})
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Long> update(
            @MyRequestBody ModelCompressDto modelCompressDto,
            @MyRequestBody ModelTaskDto modelTaskDto) {
        String errorMessage;
        ResponseResult<Tuple2<ModelCompress, JSONObject>> verifyResult =
                this.doBusinessDataVerifyAndConvert(modelCompressDto, true, modelTaskDto);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        Tuple2<ModelCompress, JSONObject> bizData = verifyResult.getData();
        ModelCompress originalModelCompress = bizData.getSecond().getObject("originalData", ModelCompress.class);
        ModelCompress modelCompress = bizData.getFirst();
        if (!modelCompressService.updateWithRelation(modelCompress, originalModelCompress, bizData.getSecond())) {
            errorMessage = "数据验证失败，[ModelCompress] 数据不存在!";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success(modelCompress.getTaskId());
    }

    /**
     * 删除模型压缩数据。
     *
     * @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 modelCompressDtoFilter 过滤对象。
     * @param modelTaskDtoFilter     一对一从表过滤对象。
     * @param orderParam             排序参数。
     * @param pageParam              分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @PostMapping("/list")
    public ResponseResult<MyPageData<ModelCompressVo>> list(
            @MyRequestBody ModelCompressDto modelCompressDtoFilter,
            @MyRequestBody ModelTaskDto modelTaskDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        }
        ModelCompress modelCompressFilter = MyModelUtil.copyTo(modelCompressDtoFilter, ModelCompress.class);
        ModelTask modelTaskFilter = MyModelUtil.copyTo(modelTaskDtoFilter, ModelTask.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, ModelCompress.class);
        List<ModelCompress> modelCompressList =
                modelCompressService.getModelCompressListWithRelation(modelCompressFilter, modelTaskFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(modelCompressList, ModelCompress.INSTANCE));
    }

    /**
     * 查看指定模型压缩对象详情。
     *
     * @param taskId 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @GetMapping("/view")
    public ResponseResult<ModelCompressVo> view(@RequestParam Long taskId) {
        ModelCompress modelCompress = modelCompressService.getByIdWithRelation(taskId, MyRelationParam.full());
        if (modelCompress == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        ModelCompressVo modelCompressVo = ModelCompress.INSTANCE.fromModel(modelCompress);
        return ResponseResult.success(modelCompressVo);
    }

    private ResponseResult<Tuple2<ModelCompress, JSONObject>> doBusinessDataVerifyAndConvert(
            ModelCompressDto modelCompressDto,
            boolean forUpdate,
            ModelTaskDto modelTaskDto) {
        ErrorCodeEnum errorCode = ErrorCodeEnum.DATA_VALIDATED_FAILED;
        String errorMessage = MyCommonUtil.getModelValidationError(modelCompressDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(errorCode, errorMessage);
        }
        errorMessage = MyCommonUtil.getModelValidationError(modelTaskDto);
        if (errorMessage != null) {
            return ResponseResult.error(errorCode, "参数 [modelTaskDto] " + errorMessage);
        }
        // 全部关联从表数据的验证和转换
        JSONObject relationData = new JSONObject();
        CallResult verifyResult;
        // 下面是输入参数中，主表关联数据的验证。
        ModelCompress modelCompress = MyModelUtil.copyTo(modelCompressDto, ModelCompress.class);
        ModelCompress originalData;
        if (forUpdate && modelCompress != null) {
            originalData = modelCompressService.getById(modelCompress.getTaskId());
            if (originalData == null) {
                return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
            }
            relationData.put("originalData", originalData);
        }
        // 处理主表的一对一关联 [ModelTask]
        ModelTask modelTask = MyModelUtil.copyTo(modelTaskDto, ModelTask.class);
        verifyResult = modelTaskService.verifyRelatedData(modelTask);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        relationData.put("modelTask", modelTask);
        return ResponseResult.success(new Tuple2<>(modelCompress, relationData));
    }

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