package com.njcn.gather.device.types.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.njcn.gather.device.types.mapper.CsDevTypeMapper;
import com.njcn.gather.device.types.pojo.param.DeviceTypeParam;
import com.njcn.gather.device.types.pojo.po.CsDevTypePO;
import com.njcn.gather.device.types.pojo.vo.DeviceTypeVO;
import com.njcn.gather.device.types.pojo.vo.PqdifCheckPlaceholderVO;
import com.njcn.gather.device.types.service.DeviceTypeService;
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;

/**
 * 设备类型服务实现。
 */
@Service
@RequiredArgsConstructor
public class DeviceTypeServiceImpl implements DeviceTypeService {

    private static final int STATE_NORMAL = 1;

    private static final int STATE_DELETED = 0;

    private static final String PQDIF_NOT_SUPPORTED = "NOT_SUPPORTED";

    private final CsDevTypeMapper csDevTypeMapper;

    @Override
    public List<DeviceTypeVO> listDeviceTypes(String keyword) {
        return csDevTypeMapper.selectDeviceTypeCheckList(trimToNull(keyword));
    }

    @Override
    @Transactional
    public boolean addDeviceType(DeviceTypeParam param) {
        DeviceTypeParam checkedParam = requireParam(param);
        LocalDateTime now = LocalDateTime.now();
        CsDevTypePO devType = buildDevType(checkedParam);
        devType.setId(UUID.randomUUID().toString().replace("-", ""));
        devType.setState(STATE_NORMAL);
        devType.setCreateBy(currentUserId());
        devType.setCreateTime(now);
        devType.setUpdateBy(currentUserId());
        devType.setUpdateTime(now);
        return csDevTypeMapper.insert(devType) > 0;
    }

    @Override
    @Transactional
    public boolean updateDeviceType(DeviceTypeParam.UpdateParam param) {
        DeviceTypeParam.UpdateParam checkedParam = requireUpdateParam(param);
        requireDevType(checkedParam.getId());
        CsDevTypePO devType = buildDevType(checkedParam);
        devType.setId(checkedParam.getId());
        devType.setUpdateBy(currentUserId());
        devType.setUpdateTime(LocalDateTime.now());
        return csDevTypeMapper.updateById(devType) > 0;
    }

    @Override
    @Transactional
    public boolean deleteDeviceType(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("设备类型ID不能为空");
        }
        CsDevTypePO devType = new CsDevTypePO();
        devType.setState(STATE_DELETED);
        devType.setUpdateBy(currentUserId());
        devType.setUpdateTime(LocalDateTime.now());
        return csDevTypeMapper.update(devType, new LambdaUpdateWrapper<CsDevTypePO>()
                .in(CsDevTypePO::getId, ids)
                .eq(CsDevTypePO::getState, STATE_NORMAL)) > 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 buildDevType(DeviceTypeParam param) {
        CsDevTypePO devType = new CsDevTypePO();
        devType.setName(requireText(param.getName(), "设备类型名称不能为空"));
        devType.setIcd(trimToNull(param.getIcd()));
        devType.setPower(trimToNull(param.getPower()));
        devType.setDevVolt(param.getDevVolt());
        devType.setDevCurr(param.getDevCurr());
        devType.setDevChns(param.getDevChns());
        devType.setWaveCmd(trimToNull(param.getWaveCmd()));
        devType.setReportName(trimToNull(param.getReportName()));
        return devType;
    }

    private DeviceTypeParam requireParam(DeviceTypeParam param) {
        if (param == null) {
            throw new IllegalArgumentException("设备类型参数不能为空");
        }
        return param;
    }

    private DeviceTypeParam.UpdateParam requireUpdateParam(DeviceTypeParam.UpdateParam param) {
        if (param == null) {
            throw new IllegalArgumentException("设备类型参数不能为空");
        }
        requireText(param.getId(), "设备类型ID不能为空");
        return param;
    }

    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;
    }

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