package cn.iocoder.yudao.module.system.service.deviceinfo;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.deviceinfo.vo.DeviceInfoPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.deviceinfo.vo.DeviceInfoSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.deviceInfo.DeviceInfoDO;
import cn.iocoder.yudao.module.system.dal.dataobject.facedeviceinfo.FaceDeviceInfoDO;
import cn.iocoder.yudao.module.system.dal.mysql.deviceInfo.DeviceInfoMapper;
import cn.iocoder.yudao.module.system.dal.mysql.facedeviceinfo.FaceDeviceInfoMapper;
import cn.iocoder.yudao.module.system.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.system.service.facedeviceinfo.FaceDeviceInfoService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

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

/**
 * 设备信息关联门店 Service 实现类
 *
 * @author 开发账号
 */
@Service
@Validated
public class DeviceInfoServiceImpl implements DeviceInfoService {

    @Resource
    private DeviceInfoMapper deviceInfoMapper;

    @Resource
    private StringRedisTemplate RedisTemplate;

    @Resource
    private HttpServletRequest httpServletRequest;

    @Resource
    private FaceDeviceInfoMapper faceDeviceInfoMapper;

    @Override
    public Long createDeviceInfo(DeviceInfoSaveReqVO createReqVO) {
        // 插入
        DeviceInfoDO deviceInfo = BeanUtils.toBean(createReqVO, DeviceInfoDO.class);
        deviceInfoMapper.insert(deviceInfo);
        // 返回
        return deviceInfo.getId();
    }

    @Override
    public void updateDeviceInfo(DeviceInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateDeviceInfoExists(updateReqVO.getId());
        // 更新
        DeviceInfoDO updateObj = BeanUtils.toBean(updateReqVO, DeviceInfoDO.class);
        deviceInfoMapper.updateById(updateObj);
    }

    @Override
    public void deleteDeviceInfo(Long id) {
        // 校验存在
        validateDeviceInfoExists(id);
        // 删除
        deviceInfoMapper.deleteById(id);
    }

    private void validateDeviceInfoExists(Long id) {
        if (deviceInfoMapper.selectById(id) == null) {
            throw exception(ErrorCodeConstants.DEVUCE_NOT_EXISTS);
        }
    }

    @Override
    public DeviceInfoDO getDeviceInfo(Long id) {
        return deviceInfoMapper.selectById(id);
    }

    @Override
    public PageResult<DeviceInfoDO> getDeviceInfoPage(DeviceInfoPageReqVO pageReqVO) {
        return deviceInfoMapper.selectPage(pageReqVO);
    }

    @Override
    public void alive() {
        String deviceSn = getHearder();
        RedisTemplate.opsForValue().set(deviceSn, String.valueOf(System.currentTimeMillis()));
        deviceInfoMapper.update(new DeviceInfoDO(),new LambdaUpdateWrapper<DeviceInfoDO>()
                .eq(DeviceInfoDO::getDeviceIp,deviceSn)
                .set(DeviceInfoDO::getAlive,"1"));
        faceDeviceInfoMapper.update(new FaceDeviceInfoDO(),new LambdaUpdateWrapper<FaceDeviceInfoDO>()
                .eq(FaceDeviceInfoDO::getMac,deviceSn)
                .set(FaceDeviceInfoDO::getAlive,"1"));
    }

    @Override
    public int updateAlive() {
        List<String> updateList = new ArrayList<>();
        List<DeviceInfoDO> deviceInfoDOS = deviceInfoMapper.selectList();
        List<String> devuceList = deviceInfoDOS.stream().map(DeviceInfoDO::getDeviceIp).collect(Collectors.toList());
        for (String deviceSn : devuceList){
            String time = RedisTemplate.opsForValue().get(deviceSn);
            if(StringUtils.isBlank(time)){
                updateList.add(deviceSn);
                continue;
            }
            if(System.currentTimeMillis()-Long.valueOf(time)>120000){
                updateList.add(deviceSn);
            }
        }

        if(CollectionUtil.isNotEmpty(updateList)){
            deviceInfoMapper.update(new DeviceInfoDO(),new LambdaUpdateWrapper<DeviceInfoDO>()
                    .set(DeviceInfoDO::getAlive,"0")
                    .in(DeviceInfoDO::getDeviceIp,updateList));
        }

        List<String> upList = new ArrayList<>();
        List<FaceDeviceInfoDO> faceDeviceInfoDOS = faceDeviceInfoMapper.selectList();
        List<String> macList = faceDeviceInfoDOS.stream().map(FaceDeviceInfoDO::getMac).collect(Collectors.toList());
        for (String deviceSn : macList){
            String time = RedisTemplate.opsForValue().get(deviceSn);
            if(StringUtils.isBlank(time)){
                upList.add(deviceSn);
                continue;
            }
            if(System.currentTimeMillis()-Long.valueOf(time)>120000){
                upList.add(deviceSn);
            }
        }

        if(CollectionUtil.isNotEmpty(upList)){
            faceDeviceInfoMapper.update(new FaceDeviceInfoDO(),new LambdaUpdateWrapper<FaceDeviceInfoDO>()
                    .set(FaceDeviceInfoDO::getAlive,"0")
                    .in(FaceDeviceInfoDO::getMac,upList));
        }

        return updateList.size()+upList.size();
    }

    public String getHearder(){
        try {
            return httpServletRequest.getHeader("Authorization");
        } catch (Exception e) {
            throw exception(2000_10_001,"无法获取设备编码");
        }
    }

}