package com.skr.mdm.api.equipment.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.skr.mdm.api.equipment.service.ClientToFileAccessService;
import com.skr.mdm.bean.vo.content.ClientToFileAccessVO;
import com.skr.mdm.constant.RedisPrefixConstant;
import com.skr.mdm.constant.SendCmdTypeConstants;
import com.skr.mdm.dao.DeviceEquipmentDao;
import com.skr.mdm.dto.LoginAdminDTO;
import com.skr.mdm.entity.DeviceEquipmentDO;
import com.skr.mdm.enums.ResultCodeEnum;
import com.skr.mdm.handle.IssuedUserHandler;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @ProjectName: mdm_new
 * @Package: com.skr.mdm.api.content.service.impl
 * @ClassName: ClientToFileAccessServiceImpl
 * @Author: Tty
 * @Description: 获取文件实现接口
 * @Date: 2021/2/25 15:27
 * @Version: 1.0
 */
@Service
@Slf4j
public class ClientToFileAccessServiceImpl implements ClientToFileAccessService {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private IssuedUserHandler issuedUserHandler;
    @Autowired
    private DeviceEquipmentDao deviceEquipmentDao;

    @Override
    public ResponseResult getFileAccess(LoginAdminDTO admin, Integer deviceId, String filePath) {
        ResponseResult result;
        try {
            String redisKey = admin.getCompanyId() + RedisPrefixConstant.TIER_KEY_PREFIX + deviceId;
            // 提前清除redis中文件信息
            redisUtils.del(redisKey);
            log.info("redisKey:{}", redisKey);
            // 推送客户端上传文件指令
            issuedUserHandler.issuedUser(Collections.singletonList(deviceId), admin.getCompanyId()
                    , SendCmdTypeConstants.FILE_ACCESS, filePath);
            long startTime = System.currentTimeMillis();
            String pathData = null;
            long count = new LambdaQueryChainWrapper<>(deviceEquipmentDao)
                    .eq(DeviceEquipmentDO::getId, deviceId)
                    .in(DeviceEquipmentDO::getEquipmentState, Arrays.asList(1, 2))
                    .count();

            if (count >= 1) {
                while (true) {
                    // 定时获取十秒 十秒获取 未获得则提示获取文件信息异常
                    if (Objects.nonNull(pathData) || System.currentTimeMillis() - startTime > 10 * 1000) {
                        break;
                    }
                    Thread.sleep(600);
                    pathData = null == redisUtils.get(redisKey) ? null : redisUtils.get(redisKey).toString();
                }
                if (StringUtils.isNotEmpty(pathData)) {
                    List<ClientToFileAccessVO> clientToFileAccessVos = JSONUtil.toList(pathData, ClientToFileAccessVO.class);
                    result = ResponseResult.success(clientToFileAccessVos);
                    //  取完数据 置空缓存信息
                    redisUtils.del(redisKey);
                } else {
                    result = ResponseResult.failure(ResultCodeEnum.SERVER_CONNECT_TIMEOUT);
                }
            } else {
                result = ResponseResult.failure(ResultCodeEnum.CLIENT_NONE_LOGIN);
            }
        } catch (InterruptedException e) {
            log.error("获取客户端文件信息异常", e);
            result = ResponseResult.failure();
        }
        return result;
    }

    @Override
    public ResponseResult uploadFile(LoginAdminDTO admin, Integer deviceId, List<String> filePath) throws Exception {
        ResponseResult result;
        String filePathStr = JSONUtil.toJsonStr(filePath).replaceAll("\\\\n", " ");
        // 客户端上传文件
        issuedUserHandler.issuedUser(Collections.singletonList(deviceId), admin.getCompanyId()
                , SendCmdTypeConstants.UPLOAD_FILE, filePathStr);
        String redisKey = redisUtils.getRedisKey(admin.getCompanyId() + RedisPrefixConstant.FILE_KEY_PREFIX.concat(deviceId + "__0"));
        log.info("可用Key值 ： {}", redisKey);
        // 文件路径
        long startTime = System.currentTimeMillis();
        String uploadUrl = null;
        Long count = new LambdaQueryChainWrapper<>(deviceEquipmentDao)
                .eq(DeviceEquipmentDO::getId, deviceId)
                .in(DeviceEquipmentDO::getEquipmentState, Arrays.asList(1, 2))
                .count();
        if (count >= 0) {
            while (true) {
                //  文件是否存在  一分钟
                if (StringUtils.isNotEmpty(uploadUrl) || (System.currentTimeMillis() - startTime) > 60 * 1000) {
                    log.info("文件获取 上传文件路径 ：{}  redisKey：{} ", uploadUrl, redisKey);
                    break;
                }
                Thread.sleep(1500);
                uploadUrl = null == redisUtils.get(redisKey) ? null : redisUtils.get(redisKey).toString();
            }
            if (StringUtils.isNotEmpty(uploadUrl)) {
                result = ResponseResult.success(uploadUrl);
            } else {
                result = ResponseResult.failure(ResultCodeEnum.SERVER_CONNECT_TIMEOUT);
            }
        } else {
            result = ResponseResult.failure(ResultCodeEnum.CLIENT_NONE_LOGIN);
        }
        return result;
    }

}