package com.dji.sample.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dji.sample.common.smsp.CallSmsp;
import com.dji.sample.common.util.DesUtil;
import com.dji.sample.manage.dao.IManageDeviceLivestreamUrlMapper;
import com.dji.sample.manage.dao.IUserMapper;
import com.dji.sample.manage.model.dto.ManageDeviceLivestreamUrlDTO;
import com.dji.sample.manage.model.entity.ManageDeviceLivestreamUrlEntity;
import com.dji.sample.manage.model.entity.UserEntity;
import com.dji.sample.manage.model.enums.LiveUrlTypeEnum;
import com.dji.sample.manage.service.IManageDeviceLivestreamUrlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional
@Slf4j
public class ManageDeviceLivestreamUrlServiceImpl implements IManageDeviceLivestreamUrlService {

    @Autowired
    private IUserMapper userMapper;

    @Autowired
    private IManageDeviceLivestreamUrlMapper mapper;

    private final String clientId = "e534550a85d94faba73e8040e76514bc";

    @Override
    public String getRtmpUrl(ManageDeviceLivestreamUrlDTO deviceLivestreamUrlDTO) {

        QueryWrapper<ManageDeviceLivestreamUrlEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ManageDeviceLivestreamUrlEntity::getDeviceSn,deviceLivestreamUrlDTO.getDeviceSn())
                .eq(ManageDeviceLivestreamUrlEntity::getWorkspaceId,deviceLivestreamUrlDTO.getWorkspaceId())
                .eq(ManageDeviceLivestreamUrlEntity::getPayload,deviceLivestreamUrlDTO.getPayload());
        ManageDeviceLivestreamUrlEntity urlEntity = mapper.selectOne(wrapper);
        if (urlEntity != null) {
            return urlEntity.getUrl();
        }

        QueryWrapper<UserEntity> userWrapper = new QueryWrapper<>();
        userWrapper.lambda().eq(UserEntity::getUserType,3).eq(UserEntity::getClientId,clientId);
        UserEntity userEntity = userMapper.selectOne(userWrapper);
        if (userEntity == null) {
            log.debug("The user is already null.");
            return null;
        }
        //密码解密
        String password = DesUtil.getDecryptData(userEntity.getPassword(),userEntity.getSalt());
        //获取token
        String token = CallSmsp.getSmspToken(userEntity.getUsername(),password);
        //获取rtmp地址
        String rtmp = CallSmsp.getRtmp(token,deviceLivestreamUrlDTO.getDeviceSn());
        deviceLivestreamUrlDTO.setUrlType(LiveUrlTypeEnum.RTMP.getVal());
        deviceLivestreamUrlDTO.setSubType(2);
        //dto转entity
        BeanUtils.copyProperties(urlEntity,deviceLivestreamUrlDTO);
        //存库
        mapper.insert(urlEntity);
        return rtmp;
    }
}
