package com.yeejoin.amos.boot.module.jg.biz.event.listener;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yeejoin.amos.boot.module.common.api.dao.ESEquipmentCategory;
import com.yeejoin.amos.boot.module.common.api.dto.ESEquipmentCategoryDto;
import com.yeejoin.amos.boot.module.jg.api.mapper.CommonMapper;
import com.yeejoin.amos.boot.module.jg.biz.event.CancellationEvent;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgUseInfo;
import com.yeejoin.amos.boot.module.ymt.api.mapper.IdxBizJgUseInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author Administrator
 */
@Component
@Slf4j
public class CancellationEventListener {

    @Value("${cancellation.deal.thread.number:1}")
    private int threadNumber;

    private CommonMapper commonMapper;

    private ESEquipmentCategory esEquipmentCategoryDao;

    private IdxBizJgUseInfoMapper idxBizJgUseInfoMapper;

    private BlockingQueue<String> queue = new LinkedBlockingQueue<>();

    public CancellationEventListener(CommonMapper commonMapper, ESEquipmentCategory esEquipmentCategoryDao, IdxBizJgUseInfoMapper idxBizJgUseInfoMapper) {
        this.commonMapper = commonMapper;
        this.esEquipmentCategoryDao = esEquipmentCategoryDao;
        this.idxBizJgUseInfoMapper = idxBizJgUseInfoMapper;
    }

    @EventListener(value = CancellationEvent.class)
    public void handleTransactionalEvent(CancellationEvent event) {
        List<String> records = event.getRecords();
        log.info("收到作废消息:{}", JSONObject.toJSONString(records));
        queue.addAll(records);
    }

    private Boolean checkEquipIsUsed(String record) {
        Integer useTime = commonMapper.countEquipInUseTimesWithOutZF(record);
        return useTime > 0;
    }

    @PostConstruct
    public void init() {
        ExecutorService executorService = Executors.newFixedThreadPool(threadNumber);
        for (int i = 0; i < threadNumber; i++) {
            executorService.execute(() -> {
                while (true) {
                    try {
                        String record = queue.take();
                        this.dealData(record);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            });

        }
    }

    private void dealData(String record) {
        // 所有业务单据（除去作废状态单据），有在引用设备的则不修改设备纳管状态
        Boolean inUsed = this.checkEquipIsUsed(record);
        // 无引用则进行修改纳管状态为未纳管
        if (!inUsed) {
            // 更新已纳管为未纳管-数据库
            LambdaUpdateWrapper<IdxBizJgUseInfo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(IdxBizJgUseInfo::getRecord, record);
            updateWrapper.set(IdxBizJgUseInfo::getIsIntoManagement, false);
            idxBizJgUseInfoMapper.update(null, updateWrapper);
            // 更新已纳管为未纳管-es
            Optional<ESEquipmentCategoryDto> optional = esEquipmentCategoryDao.findById(record);
            if (optional.isPresent()) {
                ESEquipmentCategoryDto esEquipmentCategoryDto = optional.get();
                esEquipmentCategoryDto.setIS_INTO_MANAGEMENT(false);
                esEquipmentCategoryDao.save(esEquipmentCategoryDto);
            }
        }
    }
}
