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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.yeejoin.amos.boot.module.jyjc.api.entity.JyjcInspectionResult;
import com.yeejoin.amos.boot.module.jyjc.biz.event.InspectionDetectionSaveToDbEvent;
import com.yeejoin.amos.boot.module.jyjc.biz.event.publisher.BizEmqPublisher;
import com.yeejoin.amos.boot.module.jyjc.biz.service.impl.CommonServiceImpl;
import com.yeejoin.amos.boot.module.ymt.api.entity.InspectionDetectionInfo;
import com.yeejoin.amos.boot.module.ymt.api.entity.TzsUserInfo;
import com.yeejoin.amos.boot.module.ymt.api.mapper.InspectionDetectionInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Component
@Slf4j
public class InspectionDetectionSaveToDbEventListener implements ApplicationListener<InspectionDetectionSaveToDbEvent> {

    @Value("${inspect.info.save.thread.number:3}")
    private int threadNumber;

    @Autowired
    CommonServiceImpl commonService;

    @Autowired
    private Sequence sequence;

    @Autowired
    InspectionDetectionInfoMapper inspectionDetectionInfoMapper;

    @Autowired
    BizEmqPublisher bizEmqPublisher;


    private BlockingQueue<JyjcInspectionResult> blockingQueue = new LinkedBlockingQueue<>();



    @Override
    public void onApplicationEvent(InspectionDetectionSaveToDbEvent event) {
        log.info("收到检验检测信息插入或者更新消息:{}", JSONObject.toJSONString(event.getJyjcInspectionResultList()));
        blockingQueue.addAll(event.getJyjcInspectionResultList());
    }

    @PostConstruct
    public void init() {
        ExecutorService executorService = Executors.newFixedThreadPool(threadNumber);
        for (int i = 0; i < threadNumber; i++) {
            executorService.execute(() -> {
                while (true) {
                    try {
                        JyjcInspectionResult jyjcInspectionResult = blockingQueue.take();
                        InspectionDetectionInfo info = new InspectionDetectionInfo();
                        QueryWrapper<InspectionDetectionInfo> wrapper = new QueryWrapper<>();
                        wrapper.lambda().eq(InspectionDetectionInfo::getInspectReportNo, jyjcInspectionResult.getResultNo());
                        List<InspectionDetectionInfo> list = inspectionDetectionInfoMapper.selectList(wrapper);
                        if (CollectionUtils.isEmpty(list)) {
                            fillInspectionFields(jyjcInspectionResult, info);
                            info.setSequenceNbr(sequence.nextId() + "");
                            inspectionDetectionInfoMapper.insert(info);
                            bizEmqPublisher.sendInspectionMsgAfterSave(info, "insert");
                        } else {
                            info = list.get(0);
                            fillInspectionFields(jyjcInspectionResult, info);
                            inspectionDetectionInfoMapper.updateById(info);
                            bizEmqPublisher.sendInspectionMsgAfterSave(info, "update");
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            });

        }
    }





    private void fillInspectionFields(JyjcInspectionResult jyjcInspectionResult, InspectionDetectionInfo info) {
        info.setInspectOrgName(jyjcInspectionResult.getInspectionTypeName());
        info.setInspectType(jyjcInspectionResult.getInspectionType());
        info.setRecord(jyjcInspectionResult.getEquipUnicode());
        info.setInspectDate(jyjcInspectionResult.getInspectionDate());
        info.setInspectStaff(getInspectUserName(jyjcInspectionResult));
        info.setInspectStaffCode(jyjcInspectionResult.getInspector());
        info.setInspectConclusion(jyjcInspectionResult.getInspectionConclusion());
        info.setProblemRemark(jyjcInspectionResult.getNonConformance());
        info.setNextInspectDate(jyjcInspectionResult.getNextInspectionDate());
        info.setSequenceCode(jyjcInspectionResult.getEquipUnicode());
        info.setInspectOrgCode(jyjcInspectionResult.getInspectionUnitCode());
        info.setInspectReportNo(jyjcInspectionResult.getResultNo());
        info.setRecDate(new Date());
    }

    private String getInspectUserName(JyjcInspectionResult model) {
        List<TzsUserInfo> userInfos = commonService.getUserInfosByUnitCode(model.getInspectionUnitCode());
        return userInfos.stream().filter(u -> model.getInspector().contains(u.getSequenceNbr() + "")).map(TzsUserInfo::getName).collect(Collectors.joining(","));
    }

}
