package com.njcn.gather.tool.parsepqdif.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.njcn.gather.tool.parsepqdif.mapper.CsPqdifPathMapper;
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.po.CsPqdifPathPO;
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.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * PQDIF 存储记录服务实现。
 */
@Service
@RequiredArgsConstructor
public class CsPqdifPathServiceImpl implements CsPqdifPathService {

    private static final int STATE_NORMAL = 1;

    private static final int STATE_DELETED = 0;

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    private final CsPqdifPathMapper csPqdifPathMapper;

    @Override
    public List<CsPqdifPathVO> listPqdifPaths(CsPqdifPathParam.ListParam param) {
        CsPqdifPathParam.ListParam checkedParam = param == null ? new CsPqdifPathParam.ListParam() : param;
        return csPqdifPathMapper.selectPqdifPathList(
                trimToNull(checkedParam.getKeyword()),
                checkedParam.getResult());
    }

    @Override
    public JsonNode getPqdifParseMsg(String pqdifId) {
        String id = requireText(pqdifId, "PQDIF记录ID不能为空");
        CsPqdifPathVO pqdifPath = csPqdifPathMapper.selectPqdifParseMsgById(id);
        return pqdifPath == null ? null : pqdifPath.getMsg();
    }

    @Override
    public CsPqdifPathDetailVO getPqdifParseDetail(String pqdifId) {
        String id = requireText(pqdifId, "PQDIF记录ID不能为空");
        return csPqdifPathMapper.selectPqdifPathDetailById(id);
    }

    @Override
    @Transactional
    public boolean addPqdifPath(CsPqdifPathParam param) {
        CsPqdifPathParam checkedParam = requireParam(param);
        LocalDateTime now = LocalDateTime.now();
        CsPqdifPathPO pqdifPath = buildPqdifPath(checkedParam);
        pqdifPath.setId(UUID.randomUUID().toString().replace("-", ""));
        pqdifPath.setState(STATE_NORMAL);
        pqdifPath.setCreateBy(currentUserId());
        pqdifPath.setCreateTime(now);
        pqdifPath.setUpdateBy(currentUserId());
        pqdifPath.setUpdateTime(now);
        return csPqdifPathMapper.insert(pqdifPath) > 0;
    }

    @Override
    @Transactional
    public boolean updatePqdifPath(CsPqdifPathParam.UpdateParam param) {
        CsPqdifPathParam.UpdateParam checkedParam = requireUpdateParam(param);
        requireNormalPqdifPath(checkedParam.getId());
        CsPqdifPathPO pqdifPath = buildPqdifPath(checkedParam);
        pqdifPath.setId(checkedParam.getId());
        pqdifPath.setUpdateBy(currentUserId());
        pqdifPath.setUpdateTime(LocalDateTime.now());
        return csPqdifPathMapper.updateById(pqdifPath) > 0;
    }

    @Override
    @Transactional
    public boolean deletePqdifPath(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("PQDIF记录ID不能为空");
        }
        CsPqdifPathPO pqdifPath = new CsPqdifPathPO();
        pqdifPath.setState(STATE_DELETED);
        pqdifPath.setUpdateBy(currentUserId());
        pqdifPath.setUpdateTime(LocalDateTime.now());
        return csPqdifPathMapper.update(pqdifPath, new LambdaUpdateWrapper<CsPqdifPathPO>()
                .in(CsPqdifPathPO::getId, ids)
                .eq(CsPqdifPathPO::getState, STATE_NORMAL)) > 0;
    }

    @Override
    @Transactional
    public boolean savePqdifParseResult(String pqdifId, PqdifParseResultSaveParam param) {
        if (param == null) {
            throw new IllegalArgumentException("PQDIF解析结果不能为空");
        }
        String id = requireNormalPqdifPath(pqdifId);
        CsPqdifPathPO pqdifPath = new CsPqdifPathPO();
        pqdifPath.setId(id);
        pqdifPath.setRecordCount(param.getRecordCount());
        pqdifPath.setObservationCount(param.getObservationCount());
        pqdifPath.setSampleValueCount(param.getSampleValueCount());
        Integer result = normalizeResult(param.getResult());
        pqdifPath.setResult(result);
        pqdifPath.setMsg(buildStorageResultMsg(result));
        pqdifPath.setUpdateBy(currentUserId());
        pqdifPath.setUpdateTime(LocalDateTime.now());
        return csPqdifPathMapper.updateById(pqdifPath) > 0;
    }

    private CsPqdifPathPO buildPqdifPath(CsPqdifPathParam param) {
        CsPqdifPathPO pqdifPath = new CsPqdifPathPO();
        pqdifPath.setName(requireText(param.getName(), "PQDIF名称不能为空"));
        pqdifPath.setFilePath(trimToNull(param.getFilePath()));
        pqdifPath.setFileName(trimToNull(param.getFileName()));
        return pqdifPath;
    }

    private CsPqdifPathParam requireParam(CsPqdifPathParam param) {
        if (param == null) {
            throw new IllegalArgumentException("PQDIF记录参数不能为空");
        }
        return param;
    }

    private CsPqdifPathParam.UpdateParam requireUpdateParam(CsPqdifPathParam.UpdateParam param) {
        if (param == null) {
            throw new IllegalArgumentException("PQDIF记录参数不能为空");
        }
        requireText(param.getId(), "PQDIF记录ID不能为空");
        return param;
    }

    private String requireNormalPqdifPath(String pqdifId) {
        String id = requireText(pqdifId, "PQDIF记录ID不能为空");
        CsPqdifPathDetailVO pqdifPath = csPqdifPathMapper.selectPqdifPathDetailById(id);
        if (pqdifPath == null) {
            throw new IllegalArgumentException("PQDIF记录不存在或已删除");
        }
        return id;
    }

    private Integer normalizeResult(Integer result) {
        if (result == null) {
            throw new IllegalArgumentException("解析结果不能为空");
        }
        if (result != 0 && result != 1) {
            throw new IllegalArgumentException("解析结果只能是0或1");
        }
        return result;
    }

    private JsonNode buildStorageResultMsg(Integer result) {
        ObjectNode msg = OBJECT_MAPPER.createObjectNode();
        if (Integer.valueOf(1).equals(result)) {
            msg.put("storageResult", "SUCCESS");
            msg.put("message", "存储成功");
        } else {
            msg.put("storageResult", "FAILED");
            msg.put("message", "存储失败");
        }
        return msg;
    }

    private String requireText(String value, String message) {
        String text = trimToNull(value);
        if (text == null) {
            throw new IllegalArgumentException(message);
        }
        return text;
    }

    private String trimToNull(String value) {
        if (value == null) {
            return null;
        }
        String text = value.trim();
        return text.isEmpty() ? null : text;
    }

    private boolean isBlank(String value) {
        return trimToNull(value) == null;
    }

    private String currentUserId() {
        try {
            String userId = RequestUtil.getUserId();
            return isBlank(userId) ? "未知用户" : userId;
        } catch (Exception ex) {
            return "未知用户";
        }
    }
}
