package com.njcn.gather.pqdif.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.OperateType;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.LogUtil;
import com.njcn.gather.pqdif.pojo.enums.PqdifResponseEnum;
import com.njcn.gather.pqdif.pojo.param.PqPqdifPathParam;
import com.njcn.gather.pqdif.pojo.po.PqPqdifPath;
import com.njcn.gather.pqdif.service.IPqPqdifPathService;
import com.njcn.gather.pqdif.service.support.PqdifImportParser;
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.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Api(tags = "PQDIF管理")
@RestController
@RequestMapping("/pqdif")
@RequiredArgsConstructor
public class PqPqdifPathController extends BaseController {
    private final IPqPqdifPathService pqPqdifPathService;

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @GetMapping("/listAll")
    @ApiOperation("获取全部PQDIF")
    public HttpResult<List<PqPqdifPath>> listAll() {
        String methodDescribe = getMethodDescribe("listAll");
        List<PqPqdifPath> result = pqPqdifPathService.listAll();
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo
    @PostMapping("/list")
    @ApiOperation("分页查询PQDIF")
    @ApiImplicitParam(name = "param", value = "查询参数", required = true)
    public HttpResult<Page<PqPqdifPath>> list(@RequestBody @Validated PqPqdifPathParam.QueryParam param) {
        String methodDescribe = getMethodDescribe("list");
        LogUtil.njcnDebug(log, "{}，查询数据为：{}", methodDescribe, param);
        Page<PqPqdifPath> result = pqPqdifPathService.listPqdif(param);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
    @PostMapping("/import/json")
    @ApiOperation("导入PQDIF json")
    @ApiImplicitParam(name = "file", value = "json文件", required = true)
    public HttpResult<Boolean> importJson(@RequestParam("file") MultipartFile file) {
        String methodDescribe = getMethodDescribe("importJson");
        LogUtil.njcnDebug(log, "{}，导入文件为：{}", methodDescribe, file == null ? null : file.getOriginalFilename());
        List<PqPqdifPathParam.ImportItem> items = parseImportItems(file);
        boolean result = pqPqdifPathService.importPqdif(items);
        if (result) {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
        }
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
    }

    private List<PqPqdifPathParam.ImportItem> parseImportItems(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException(PqdifResponseEnum.JSON_FILE_NOT_NULL);
        }
        String fileName = file.getOriginalFilename();
        if (fileName == null || !fileName.toLowerCase().endsWith(".json")) {
            throw new BusinessException(PqdifResponseEnum.JSON_FORMAT_ERROR);
        }
        try {
            return PqdifImportParser.parse(new String(file.getBytes(), StandardCharsets.UTF_8));
        } catch (BusinessException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new BusinessException(PqdifResponseEnum.JSON_FORMAT_ERROR);
        }
    }
}
