package com.zt.plat.module.qms.resource.device.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceConfigBusinessRulePageReqVO;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceConfigBusinessRuleRespVO;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceConfigBusinessRuleSaveReqVO;
import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceInfomationDO;
import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceProductDO;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;

import java.util.*;

import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceConfigBusinessRuleDO;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;

import com.zt.plat.module.qms.resource.device.dal.mapper.DeviceConfigBusinessRuleMapper;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception0;
import static com.zt.plat.framework.common.util.collection.CollectionUtils.convertList;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.DEVICE_CONFIG_BUSINESS_RULE_NOT_EXISTS;

/**
 * 设备-业务配置 Service 实现类
 *
 * @author 后台管理-1
 */
@Service
@Validated
public class DeviceConfigBusinessRuleServiceImpl implements DeviceConfigBusinessRuleService {

    @Resource private DeviceConfigBusinessRuleMapper deviceConfigBusinessRuleMapper;
    @Resource private DeviceInfomationService deviceInfomationService;
    @Resource private DeviceProductService deviceProductService;

    @Override
    public DeviceConfigBusinessRuleDO getByProductId(Long productId, String businessDomain) {
        LambdaQueryWrapper<DeviceConfigBusinessRuleDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceConfigBusinessRuleDO::getProductId, productId).eq(DeviceConfigBusinessRuleDO::getBusinessDomain, businessDomain);
        List<DeviceConfigBusinessRuleDO> list = deviceConfigBusinessRuleMapper.selectList(queryWrapper);
        if(list.size() > 1)
            throw exception0(DEVICE_CONFIG_BUSINESS_RULE_NOT_EXISTS.getCode(), "业务配置数据有" + list.size() + "行， 请联系管理员处理！");
        if(list.isEmpty())
            return null;
        return list.get(0);
    }

    @Override
    public CommonResult<DeviceConfigBusinessRuleDO> getRuleByDeviceIdAndType(Long deviceId, String type) {
        DeviceInfomationDO deviceDO = deviceInfomationService.getDeviceInfomation(deviceId);
        DeviceProductDO productDO = deviceProductService.getDeviceProduct(deviceDO.getProductId());
        String path = productDO.getIdPath();
        List<Long> productIdList = new ArrayList<>();
        if(!ObjectUtils.isEmpty(path)){
            String[] split = path.split("/");
            for (String s : split) {
                if(ObjectUtils.isEmpty(s))
                    continue;
                String id = s.replaceAll("/", "");
                if(id.equals("0"))
                    continue;
                productIdList.add(Long.valueOf(s));
            }
        }else
            productIdList.add(productDO.getId());
        List<DeviceConfigBusinessRuleDO> ruleList = getByProductIdListAndBusinessDomain(productIdList, type);
        if(ruleList.isEmpty())
            return CommonResult.error(DEVICE_CONFIG_BUSINESS_RULE_NOT_EXISTS);
        if(ruleList.size() == 1)
            return CommonResult.success(ruleList.get(0));
        //取最底层的配置
        for(int i = productIdList.size() - 1; i > 0; i--){
            Long id = productIdList.get(i);
            for(DeviceConfigBusinessRuleDO rule : ruleList){
                if(Objects.equals(rule.getProductId(), id))
                    return CommonResult.success(rule);
            }
        }
        return CommonResult.error(DEVICE_CONFIG_BUSINESS_RULE_NOT_EXISTS);
    }

    @Override
    public List<DeviceConfigBusinessRuleDO> getByProductIdListAndBusinessDomain(List<Long> productIdList, String businessDomain) {
        if(productIdList.isEmpty())
            return Collections.emptyList();
        LambdaQueryWrapper<DeviceConfigBusinessRuleDO> query = new LambdaQueryWrapper<>();
        query.in(DeviceConfigBusinessRuleDO::getProductId, productIdList);
        if(!ObjectUtils.isEmpty(businessDomain))
            query.eq(DeviceConfigBusinessRuleDO::getBusinessDomain, businessDomain);
        return deviceConfigBusinessRuleMapper.selectList( query);
    }

    @Override
    public DeviceConfigBusinessRuleRespVO createDeviceConfigBusinessRule(DeviceConfigBusinessRuleSaveReqVO createReqVO) {
        // 插入
        DeviceConfigBusinessRuleDO deviceConfigBusinessRule = BeanUtils.toBean(createReqVO, DeviceConfigBusinessRuleDO.class);
        deviceConfigBusinessRuleMapper.insert(deviceConfigBusinessRule);
        // 返回
        return BeanUtils.toBean(deviceConfigBusinessRule, DeviceConfigBusinessRuleRespVO.class);
    }

    @Override
    public void updateDeviceConfigBusinessRule(DeviceConfigBusinessRuleSaveReqVO updateReqVO) {
        // 校验存在
        validateDeviceConfigBusinessRuleExists(updateReqVO.getId());
        // 更新
        DeviceConfigBusinessRuleDO updateObj = BeanUtils.toBean(updateReqVO, DeviceConfigBusinessRuleDO.class);
        deviceConfigBusinessRuleMapper.updateById(updateObj);
    }

    @Override
    public void deleteDeviceConfigBusinessRule(Long id) {
        // 校验存在
        validateDeviceConfigBusinessRuleExists(id);
        // 删除
        deviceConfigBusinessRuleMapper.deleteById(id);
    }

    @Override
        public void deleteDeviceConfigBusinessRuleListByIds(List<Long> ids) {
        // 校验存在
        validateDeviceConfigBusinessRuleExists(ids);
        // 删除
        deviceConfigBusinessRuleMapper.deleteByIds(ids);
        }

    private void validateDeviceConfigBusinessRuleExists(List<Long> ids) {
        List<DeviceConfigBusinessRuleDO> list = deviceConfigBusinessRuleMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(DEVICE_CONFIG_BUSINESS_RULE_NOT_EXISTS);
        }
    }

    private void validateDeviceConfigBusinessRuleExists(Long id) {
        if (deviceConfigBusinessRuleMapper.selectById(id) == null) {
            throw exception(DEVICE_CONFIG_BUSINESS_RULE_NOT_EXISTS);
        }
    }

    @Override
    public DeviceConfigBusinessRuleDO getDeviceConfigBusinessRule(Long id) {
        return deviceConfigBusinessRuleMapper.selectById(id);
    }

    @Override
    public PageResult<DeviceConfigBusinessRuleRespVO> getDeviceConfigBusinessRulePage(DeviceConfigBusinessRulePageReqVO pageReqVO) {
        return deviceConfigBusinessRuleMapper.selectPage(pageReqVO);
    }

}