package com.njcn.gather.icd.mapping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.gather.icd.mapping.mapper.CsDevTypeMapper;
import com.njcn.gather.icd.mapping.mapper.CsIcdPathMapper;
import com.njcn.gather.icd.mapping.pojo.param.IcdCheckResultSaveParam;
import com.njcn.gather.icd.mapping.pojo.po.CsDevTypePO;
import com.njcn.gather.icd.mapping.pojo.po.CsIcdPathPO;
import com.njcn.gather.icd.mapping.pojo.vo.MmsDeviceTypeVO;
import com.njcn.gather.icd.mapping.pojo.vo.PqdifCheckPlaceholderVO;
import com.njcn.gather.icd.mapping.service.MmsDeviceTypeService;
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;

/**
 * 设备类型校验服务实现。
 */
@Service
@RequiredArgsConstructor
public class MmsDeviceTypeServiceImpl implements MmsDeviceTypeService {

    private static final int STATE_NORMAL = 1;

    private static final int ICD_TYPE_STANDARD = 1;

    private static final String PQDIF_NOT_SUPPORTED = "NOT_SUPPORTED";

    private final CsDevTypeMapper csDevTypeMapper;

    private final CsIcdPathMapper csIcdPathMapper;

    @Override
    public List<MmsDeviceTypeVO> listDeviceTypes() {
        return csDevTypeMapper.selectDeviceTypeCheckList();
    }

    @Override
    @Transactional
    public boolean saveIcdCheckResult(String devTypeId, IcdCheckResultSaveParam param) {
        if (param == null) {
            throw new IllegalArgumentException("ICD校验结果不能为空");
        }
        CsDevTypePO devType = requireDevType(devTypeId);
        if (isBlank(devType.getIcd())) {
            throw new IllegalArgumentException("设备类型未关联ICD，不能保存校验结果");
        }

        CsIcdPathPO referenceIcd = requireUniqueReferenceIcd();
        CsIcdPathPO icdPath = csIcdPathMapper.selectById(devType.getIcd());
        if (icdPath == null || !Integer.valueOf(STATE_NORMAL).equals(icdPath.getState())) {
            throw new IllegalArgumentException("设备类型关联的ICD不存在或已删除");
        }

        icdPath.setJsonStr(trimToNull(param.getMappingJson()));
        icdPath.setXmlStr(trimToNull(param.getXml()));
        icdPath.setResult(normalizeResult(param.getResult()));
        icdPath.setMsg(trimToNull(param.getMsg()));
        icdPath.setReferenceIcdId(referenceIcd.getId());
        icdPath.setUpdateBy(currentUserId());
        icdPath.setUpdateTime(LocalDateTime.now());
        return csIcdPathMapper.updateById(icdPath) > 0;
    }

    @Override
    public PqdifCheckPlaceholderVO pqdifCheck(String devTypeId) {
        requireDevType(devTypeId);
        PqdifCheckPlaceholderVO result = new PqdifCheckPlaceholderVO();
        result.setStatus(PQDIF_NOT_SUPPORTED);
        result.setMessage("PQDIF校验功能待实现");
        return result;
    }

    private CsDevTypePO requireDevType(String devTypeId) {
        String id = requireText(devTypeId, "设备类型ID不能为空");
        CsDevTypePO devType = csDevTypeMapper.selectById(id);
        if (devType == null || !Integer.valueOf(STATE_NORMAL).equals(devType.getState())) {
            throw new IllegalArgumentException("设备类型不存在或已删除");
        }
        return devType;
    }

    /**
     * 全系统只允许一个正常状态的标准 ICD 作为唯一参照。
     */
    private CsIcdPathPO requireUniqueReferenceIcd() {
        List<CsIcdPathPO> referenceIcdList = csIcdPathMapper.selectList(new LambdaQueryWrapper<CsIcdPathPO>()
                .eq(CsIcdPathPO::getState, STATE_NORMAL)
                .eq(CsIcdPathPO::getType, ICD_TYPE_STANDARD));
        if (referenceIcdList == null || referenceIcdList.isEmpty()) {
            throw new IllegalArgumentException("未配置标准ICD，无法执行唯一性校验");
        }
        if (referenceIcdList.size() > 1) {
            throw new IllegalArgumentException("存在多个标准ICD，无法确定唯一参照");
        }
        return referenceIcdList.get(0);
    }

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

    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 "未知用户";
        }
    }
}
