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

import com.alibaba.fastjson.JSONObject;
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.biz.event.CancellationEvent;
import com.yeejoin.amos.boot.module.jg.biz.service.ICommonService;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.IdxBizJgRegisterInfoServiceImpl;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.IdxBizJgUseInfoServiceImpl;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgRegisterInfo;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgUseInfo;
import lombok.RequiredArgsConstructor;
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
@RequiredArgsConstructor
public class CancellationEventListener {

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

    private final ICommonService commonService;

    private final ESEquipmentCategory esEquipmentCategoryDao;

    private final IdxBizJgUseInfoServiceImpl idxBizJgUseInfoService;

    private final IdxBizJgRegisterInfoServiceImpl idxBizJgRegisterInfoService;

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

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

    @PostConstruct
    public void init() {
        ExecutorService executorService = Executors.newFixedThreadPool(threadNumber, r -> {
            Thread t = new Thread(r);
            t.setName("CancellationWorker-" + t.getId());
            return t;
        });
        for (int i = 0; i < threadNumber; i++) {
            executorService.execute(() -> {
                while (true) {
                    try {
                        String record = queue.take();
                        log.info("线程 {} 开始处理 record: {}", Thread.currentThread().getName(), record);
                        this.dealData(record);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            });

        }
    }

    private void dealData(String record) {
        log.info("开始检查设备的引用:{}", record);
        // 所有业务单据（除去作废、删除状态单据），有在引用设备的则不修改设备纳管状态
        Boolean inUsed = commonService.checkEquipIsUsed(record);
        // 无引用则进行修改纳管状态为未纳管
        if (!inUsed) {
            log.info("进行设备作废处理:{}", record);
            try {
                // 更新已纳管为未纳管 - 数据库
                idxBizJgUseInfoService.lambdaUpdate()
                        .eq(IdxBizJgUseInfo::getRecord, record)
                        .set(IdxBizJgUseInfo::getIsIntoManagement, false)
                        .update();

                // 清除系统自动生成的设备代码`equCode`
                boolean isRegisterUpdated = idxBizJgRegisterInfoService.lambdaUpdate()
                        .eq(IdxBizJgRegisterInfo::getRecord, record)
                        .eq(IdxBizJgRegisterInfo::getEquCodeType, "2")
                        .set(IdxBizJgRegisterInfo::getEquCode, null)
                        .update();

                // 同步修改ES数据
                Optional<ESEquipmentCategoryDto> optional = esEquipmentCategoryDao.findById(record);
                optional.ifPresent(esEquipmentCategoryDto -> {
                    esEquipmentCategoryDto.setIS_INTO_MANAGEMENT(false);
                    if (isRegisterUpdated) {
                        esEquipmentCategoryDto.setEQU_CODE(null);
                    }
                    esEquipmentCategoryDao.save(esEquipmentCategoryDto);
                });
            } catch (Exception e) {
                log.error("设备作废异常:{}", e.getMessage());
            }
        }
    }
}
