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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.utils.SnowflakeIdUtil;
import com.yeejoin.amos.boot.module.common.api.constant.TZSCommonConstant;
import com.yeejoin.amos.boot.module.common.biz.refresh.DataRefreshEvent;
import com.yeejoin.amos.boot.module.jyjc.api.entity.JyjcInspectionResult;
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.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.typroject.tyboot.component.emq.EmqKeeper;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class InspectionDetectionInfoUpdateService {

    @Autowired
    CommonServiceImpl commonService;

    @Autowired
    private SnowflakeIdUtil sequence;

    @Autowired
    InspectionDetectionInfoMapper inspectionDetectionInfoMapper;

    @Autowired
    BizEmqPublisher bizEmqPublisher;

    @Autowired
    private EmqKeeper emqKeeper;

    @Transactional(rollbackFor = Exception.class)
    public void update(JyjcInspectionResult jyjcInspectionResult) {
        InspectionDetectionInfo info = new InspectionDetectionInfo();
        QueryWrapper<InspectionDetectionInfo> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(InspectionDetectionInfo::getInspectReportNo, jyjcInspectionResult.getResultNo());
        List<InspectionDetectionInfo> list = inspectionDetectionInfoMapper.selectList(wrapper);
        String record;
        if (CollectionUtils.isEmpty(list)) {
            fillInspectionFields(jyjcInspectionResult, info);
            info.setSequenceNbr(sequence.nextId() + "");
            inspectionDetectionInfoMapper.insert(info);
            record = info.getRecord();
            bizEmqPublisher.sendInspectionMsgAfterSave(info, "insert");
        } else {
            info = list.get(0);
            fillInspectionFields(jyjcInspectionResult, info);
            inspectionDetectionInfoMapper.updateById(info);
            record = info.getRecord();
            bizEmqPublisher.sendInspectionMsgAfterSave(info, "update");
        }
        try {
            emqKeeper.getMqttClient().publish(String.format(TZSCommonConstant.DATA_REFRESH_TOPIC, DataRefreshEvent.DataType.equipment.name(), DataRefreshEvent.Operation.UPDATE), JSONObject.toJSONString(Collections.singletonList(record)).getBytes(StandardCharsets.UTF_8), 2, false);
        } catch (MqttException e) {
            log.error("发送数据变更emq消息失败：{}", 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(","));
    }
}
