package com.pcloud.book.mq.topic;

import com.google.common.collect.Maps;

import com.pcloud.book.advertising.biz.AdvertisingSpaceBiz;
import com.pcloud.book.advertising.entity.AdvertisingSpace;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.core.constant.ConvertEnum;
import com.pcloud.common.core.constant.MQQueueConstant;
import com.pcloud.common.core.dto.ConvertQueueDto;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.FileUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.contentcenter.resource.enums.ResourceTypeEnum;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

/**
 * @描述：文件转码
 * @作者：zhuyajie
 * @创建时间：11:31 2019/6/25
 * @版本：1.0
 */
@Component("convertFileListener")
@RabbitListener(queues = MQQueueConstant.CONVERT_TO_BOOK)
public class ConvertFileListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConvertFileListener.class);

    private static ConvertFileListener convertFileListener;
    @Autowired
    private AdvertisingSpaceBiz advertisingSpaceBiz;

    /**
     * 当转换过快，消息先一步到达资源中心时，找不到对应的记录就保存下来
     */
    private static Map<String, ConvertQueueDto> cqds = Maps.newHashMap();

    private static Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                //如果cqds没有记录，休眠60秒
                if (MapUtils.isEmpty(cqds)) {
                    try {
                        Thread.sleep(1000 * 60);
                    } catch (InterruptedException e) {
                        LOGGER.error("pmrismap线程执行出错", e);
                    }
                } else {
                    for (Map.Entry<String, ConvertQueueDto> e : cqds.entrySet()) {
                        if (e.getValue() != null) {
                            ConvertQueueDto convertFileDto = e.getValue();
                            LOGGER.info("转码后信息>>>>>" + convertFileDto.toString());
                            String fileCategory = FileUtils.getGatherName(convertFileDto.getFileType());
                            String fileId = convertFileDto.getFileId();
                            String fileUrl = convertFileDto.getFileUrl();
                            if (ResourceTypeEnum.AUDIO.code.equals(fileCategory) || ResourceTypeEnum.VIDEO.code.equals(fileCategory)) {
                                List<AdvertisingSpace> filelist = convertFileListener.advertisingSpaceBiz.getUnConvertFile(fileId);
                                if (!ListUtils.isEmpty(filelist)) {
                                    //更新
                                    convertFileListener.advertisingSpaceBiz.updateFile(filelist, fileUrl);
                                    cqds.remove(e.getKey());
                                } else {
                                    if (convertFileDto.getProcessTimes() < 10) {
                                        convertFileDto.setProcessTimes(convertFileDto.getProcessTimes() + 1);
                                        LOGGER.info("音频资源 ，未找到对应记录，进入下一个循环！fileid=" + convertFileDto.getFileId());
                                    } else {
                                        cqds.remove(e.getKey());
                                    }
                                }
                            }
                        } else {
                            // 当该key内无实体时，即清除
                            cqds.remove(e.getKey());
                        }
                    }
                }
            }
        }
    });

    // 开始缓存处理
    static {
        t1.start();
    }


    @RabbitHandler
    @ParamLog("文件转码")
    public void process(ConvertQueueDto convertQueueDto) throws BizException {
        //消息处理
        update(convertQueueDto);
    }

    /**
     * 更新数据库
     */
    private void update(ConvertQueueDto convertFileDto) {
        if (null == convertFileDto) {
            return;
        }
        if (!ConvertEnum.BOOK.value.equals(convertFileDto.getFromType())) {
            return;
        }
        String fileCategory = FileUtils.getGatherName(convertFileDto.getFileType());
        //转换成功
        if (convertFileDto.getState() == null || convertFileDto.getState()) {
            String fileId = convertFileDto.getFileId();
            String fileUrl = convertFileDto.getFileUrl();
            // 修改点读书音频转码后的地址
            if (ResourceTypeEnum.AUDIO.code.equals(fileCategory)) {
                List<AdvertisingSpace> filelist = convertFileListener.advertisingSpaceBiz.getUnConvertFile(fileId);
                if (ListUtils.isEmpty(filelist)) {
                    LOGGER.info("接收到转码状态时，数据库还未插入记录，先将音频转码信息放到缓存fileId=" + fileId + "convertFileDto=" + convertFileDto.toString());
                    cqds.put(fileId, convertFileDto);
                } else {
                    convertFileListener.advertisingSpaceBiz.updateFile(filelist, fileUrl);
                }
            }
        }
    }

    @PostConstruct
    public void init() {
        convertFileListener = this;
        convertFileListener.advertisingSpaceBiz = this.advertisingSpaceBiz;
    }


}
