package com.njcn.gather.tool.parsepqdif.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.LogUtil;
import com.njcn.gather.tool.parsepqdif.component.PqdifFileStorageService;
import com.njcn.gather.tool.parsepqdif.pojo.param.CsPqdifPathParam;
import com.njcn.gather.tool.parsepqdif.pojo.param.PqdifParseResultSaveParam;
import com.njcn.gather.tool.parsepqdif.pojo.vo.CsPqdifPathDetailVO;
import com.njcn.gather.tool.parsepqdif.pojo.vo.CsPqdifPathVO;
import com.njcn.gather.tool.parsepqdif.service.CsPqdifPathService;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.HttpResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * PQDIF 存储记录维护入口。
 */
@Slf4j
@Api(tags = "PQDIF存储记录管理")
@RestController
@RequestMapping("/api/parse-pqdif/pqdif-paths")
@RequiredArgsConstructor
public class CsPqdifPathController extends BaseController {

    private final CsPqdifPathService csPqdifPathService;

    private final PqdifFileStorageService pqdifFileStorageService;

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("查询PQDIF存储记录列表")
    @PostMapping("/list")
    public HttpResult<List<CsPqdifPathVO>> list(@RequestBody(required = false) CsPqdifPathParam.ListParam param) {
        String methodDescribe = getMethodDescribe("list");
        LogUtil.njcnDebug(log, "{}，开始查询PQDIF存储记录列表", methodDescribe);
        List<CsPqdifPathVO> result = csPqdifPathService.listPqdifPaths(param);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("新增PQDIF存储记录")
    @PostMapping(value = "/add", consumes = {"application/json"})
    public HttpResult<Boolean> add(@RequestBody @Validated CsPqdifPathParam param) {
        String methodDescribe = getMethodDescribe("add");
        LogUtil.njcnDebug(log, "{}，开始新增PQDIF存储记录", methodDescribe);
        boolean result = csPqdifPathService.addPqdifPath(param);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("上传并新增PQDIF存储记录")
    @PostMapping(value = "/add", consumes = {"multipart/form-data"})
    public HttpResult<Boolean> addWithFile(@RequestPart("pqdifFile") MultipartFile pqdifFile,
                                           @RequestPart("request") @Validated CsPqdifPathParam param) {
        String methodDescribe = getMethodDescribe("addWithFile");
        LogUtil.njcnDebug(log, "{}，开始上传并新增PQDIF存储记录，fileName={}", methodDescribe, resolveFileName(pqdifFile));
        fillPqdifFilePath(param, pqdifFile);
        boolean result = csPqdifPathService.addPqdifPath(param);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("编辑PQDIF存储记录")
    @PostMapping(value = "/update", consumes = {"application/json"})
    public HttpResult<Boolean> update(@RequestBody @Validated CsPqdifPathParam.UpdateParam param) {
        String methodDescribe = getMethodDescribe("update");
        LogUtil.njcnDebug(log, "{}，开始编辑PQDIF存储记录，pqdifId={}", methodDescribe, param.getId());
        boolean result = csPqdifPathService.updatePqdifPath(param);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("上传并编辑PQDIF存储记录")
    @PostMapping(value = "/update", consumes = {"multipart/form-data"})
    public HttpResult<Boolean> updateWithFile(@RequestPart("pqdifFile") MultipartFile pqdifFile,
                                              @RequestPart("request") @Validated CsPqdifPathParam.UpdateParam param) {
        String methodDescribe = getMethodDescribe("updateWithFile");
        LogUtil.njcnDebug(log, "{}，开始上传并编辑PQDIF存储记录，pqdifId={}，fileName={}",
                methodDescribe, param.getId(), resolveFileName(pqdifFile));
        fillPqdifFilePath(param, pqdifFile);
        boolean result = csPqdifPathService.updatePqdifPath(param);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("删除PQDIF存储记录")
    @PostMapping("/delete")
    public HttpResult<Boolean> delete(@RequestBody List<String> ids) {
        String methodDescribe = getMethodDescribe("delete");
        LogUtil.njcnDebug(log, "{}，开始删除PQDIF存储记录，ids={}", methodDescribe, ids);
        boolean result = csPqdifPathService.deletePqdifPath(ids);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("查询PQDIF解析结果详情")
    @ApiImplicitParam(name = "id", value = "PQDIF记录ID", required = true)
    @PostMapping("/{id}/parse-msg")
    public HttpResult<JsonNode> getPqdifParseMsg(@PathVariable("id") String id) {
        String methodDescribe = getMethodDescribe("getPqdifParseMsg");
        LogUtil.njcnDebug(log, "{}，开始查询PQDIF解析结果详情，pqdifId={}", methodDescribe, id);
        JsonNode result = csPqdifPathService.getPqdifParseMsg(id);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("查询PQDIF文件和解析结果详情")
    @ApiImplicitParam(name = "id", value = "PQDIF记录ID", required = true)
    @PostMapping("/{id}/parse-detail")
    public HttpResult<CsPqdifPathDetailVO> getPqdifParseDetail(@PathVariable("id") String id) {
        String methodDescribe = getMethodDescribe("getPqdifParseDetail");
        LogUtil.njcnDebug(log, "{}，开始查询PQDIF文件和解析结果详情，pqdifId={}", methodDescribe, id);
        CsPqdifPathDetailVO result = csPqdifPathService.getPqdifParseDetail(id);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("保存PQDIF解析结果")
    @ApiImplicitParam(name = "id", value = "PQDIF记录ID", required = true)
    @PostMapping(value = "/{id}/parse-result", consumes = {"application/json"})
    public HttpResult<Boolean> savePqdifParseResult(@PathVariable("id") String id,
                                                    @RequestBody PqdifParseResultSaveParam param) {
        String methodDescribe = getMethodDescribe("savePqdifParseResult");
        LogUtil.njcnDebug(log, "{}，开始保存PQDIF解析结果，pqdifId={}", methodDescribe, id);
        boolean result = csPqdifPathService.savePqdifParseResult(id, param);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    private void fillPqdifFilePath(CsPqdifPathParam param, MultipartFile pqdifFile) {
        param.setFilePath(pqdifFileStorageService.save(pqdifFile));
        param.setFileName(resolveFileName(pqdifFile));
    }

    private String resolveFileName(MultipartFile pqdifFile) {
        if (pqdifFile == null || pqdifFile.getOriginalFilename() == null) {
            return null;
        }
        String fileName = pqdifFile.getOriginalFilename().trim();
        return fileName.isEmpty() ? null : fileName;
    }
}
