package cn.iocoder.yudao.module.pms.service.yanfan.sip.config;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.constant.YanfanConstant;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.redis.RedisCache;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.sip.config.vo.IotYfSipConfigPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.sip.config.vo.IotYfSipConfigSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.yanfan.device.YfIotDeviceDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.yanfan.sip.config.IotSipConfigDO;
import cn.iocoder.yudao.module.pms.dal.mysql.yanfan.device.YfIotDeviceMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.yanfan.sip.config.IotSipConfigMapper;
import cn.iocoder.yudao.module.pms.service.yanfan.config.SysSipConfig;
import cn.iocoder.yudao.module.pms.service.yanfan.device.YfIotDeviceService;
import liquibase.pro.packaged.Y;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import javax.annotation.Resource;

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

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * yf-sip系统配置 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class IotSipConfigServiceImpl implements IotSipConfigService {

    @Resource
    private IotSipConfigMapper iotSipConfigMapper;
    @Autowired
    private YfIotDeviceService yfIotDeviceService;

    @Override
    @TenantIgnore
    public IotSipConfigDO selectSipConfigBydeviceSipId(String deviceSipId) {
        YfIotDeviceDO device = yfIotDeviceService.selectDeviceBySerialNumber(deviceSipId);
        if (device != null) {
            return this.selectSipConfigByProductId(device.getProductId());
        } else {
            return this.GetDefaultSipConfig();
        }
    }

    /**
     * 查询产品下第一条sip系统配置
     *
     * @return sip系统配置
     */
    @Cacheable(cacheNames = "sipConfig", key = "#root.methodName +'_' + #productId", unless = "#result == null")
    @Override
    public IotSipConfigDO selectSipConfigByProductId(Long productId) {
        List<IotSipConfigDO> productId1 = iotSipConfigMapper.selectList("product_id", productId);
        IotSipConfigDO sipConfig;
        if (CollUtil.isEmpty(productId1)) {
            sipConfig = GetDefaultSipConfig();
            sipConfig.setProductId(productId);
            sipConfig.setCreateTime(LocalDateTime.now());
            iotSipConfigMapper.insert(sipConfig);
        } else {
            sipConfig = productId1.get(0);
        }
        return sipConfig;
    }


    @Autowired
    private SysSipConfig sysSipConfig;
    @Autowired
    private RedisCache redisCache;

    @Override
    public IotSipConfigDO GetDefaultSipConfig() {
        Object temp = redisCache.getCacheObject(YanfanConstant.REDIS.DEFAULT_SIP_CONFIG);
        IotSipConfigDO sipConfig = new IotSipConfigDO();
        if (temp == null) {
            sipConfig.setEnabled(sysSipConfig.isEnabled() ? 1 : 0);
            sipConfig.setIp(sysSipConfig.getIp());
            sipConfig.setPort(sysSipConfig.getPort());
            sipConfig.setDomain(sysSipConfig.getDomain());
            sipConfig.setServerSipid(sysSipConfig.getId());
            sipConfig.setPassword(sysSipConfig.getPassword());
            redisCache.setCacheObject(YanfanConstant.REDIS.DEFAULT_SIP_CONFIG, sipConfig);
        } else if (temp instanceof IotSipConfigDO){
            sipConfig = (IotSipConfigDO) temp;
            updateDefaultSipConfig(sipConfig);
        } else if (temp instanceof SysSipConfig){
            SysSipConfig temp2 = (SysSipConfig) temp;
            sipConfig.setEnabled(temp2.isEnabled() ? 1 : 0);
            sipConfig.setIp(temp2.getIp());
            sipConfig.setPort(temp2.getPort());
            sipConfig.setDomain(temp2.getDomain());
            sipConfig.setServerSipid(temp2.getId());
            sipConfig.setPassword(temp2.getPassword());
        }
        return sipConfig;
    }

    @Override
    public void updateDefaultSipConfig(IotSipConfigDO sipConfig) {
        SysSipConfig defConfig = new SysSipConfig();
        defConfig.setEnabled(sipConfig.getEnabled()==1);
        defConfig.setIp(sipConfig.getIp());
        defConfig.setPort(sipConfig.getPort());
        defConfig.setDomain(sipConfig.getDomain());
        defConfig.setId(sipConfig.getServerSipid());
        defConfig.setPassword(sipConfig.getPassword());
        redisCache.setCacheObject(YanfanConstant.REDIS.DEFAULT_SIP_CONFIG, sipConfig);
    }

    @Override
    public int deleteSipConfigByProductIds(Long[] productIds) {
        return iotSipConfigMapper.deleteSipConfigByProductId(productIds);
    }

    @Override
    public Long createIotSipConfig(IotYfSipConfigSaveReqVO createReqVO) {
        // 插入
        IotSipConfigDO sipConfig = BeanUtils.toBean(createReqVO, IotSipConfigDO.class);

        sipConfig.setCreateTime(LocalDateTime.now());
        if (sipConfig.getIsdefault() != null && sipConfig.getIsdefault() == 1) {
            iotSipConfigMapper.resetDefaultSipConfig();
            updateDefaultSipConfig(sipConfig);
        }
        iotSipConfigMapper.insert(sipConfig);
        return sipConfig.getId();
//        iotSipConfigMapper.insert(iotSipConfig);
//        // 返回
//        return iotSipConfig.getId();
    }

    @Override
    public void updateIotSipConfig(IotYfSipConfigSaveReqVO updateReqVO) {
        // 校验存在
        validateIotSipConfigExists(updateReqVO.getId());
        // 更新
        IotSipConfigDO updateObj = BeanUtils.toBean(updateReqVO, IotSipConfigDO.class);
        iotSipConfigMapper.updateById(updateObj);

        IotSipConfigDO sipConfig = BeanUtils.toBean(updateReqVO, IotSipConfigDO.class);
        sipConfig.setUpdateTime(LocalDateTime.now());
        if (sipConfig.getIsdefault() != null && sipConfig.getIsdefault() == 1) {
            iotSipConfigMapper.resetDefaultSipConfig();
            updateDefaultSipConfig(sipConfig);
        }
        iotSipConfigMapper.updateById(sipConfig);
    }

    @Override
    public void deleteIotSipConfig(Long id) {
        // 校验存在
        validateIotSipConfigExists(id);
        // 删除
        iotSipConfigMapper.deleteById(id);
    }

    private void validateIotSipConfigExists(Long id) {
        if (iotSipConfigMapper.selectById(id) == null) {
            throw exception(new ErrorCode(999,"不存在"));
        }
    }

    @Override
    public IotSipConfigDO getIotSipConfig(Long id) {
        return iotSipConfigMapper.selectById(id);
    }

    @Override
    public PageResult<IotSipConfigDO> getIotSipConfigPage(IotYfSipConfigPageReqVO pageReqVO) {
        return iotSipConfigMapper.selectPage(pageReqVO);
    }


    @Override
    public void syncSipConfig(SysSipConfig sipConfig) {
        List<IotSipConfigDO> list = iotSipConfigMapper.selectSipConfigList(new IotSipConfigDO());
        for (IotSipConfigDO config : list) {
            config.setIp(sipConfig.getIp());
            config.setPort(sipConfig.getPort());
            iotSipConfigMapper.updateById(config);
        }
        GetDefaultSipConfig();
    }
}
