package com.yeejoin.amos.boot.module.jg.biz.refresh.handler;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.module.common.api.dao.EsEquipmentDao;
import com.yeejoin.amos.boot.module.common.api.dto.ESEquipmentCategoryDto;
import com.yeejoin.amos.boot.module.common.api.entity.ESEquipmentInfo;
import com.yeejoin.amos.boot.module.common.api.entity.TzsDataRefreshMessage;
import com.yeejoin.amos.boot.module.common.api.service.IDataRefreshHandler;
import com.yeejoin.amos.boot.module.common.biz.refresh.DataRefreshEvent;
import com.yeejoin.amos.boot.module.jg.biz.refresh.StatisticsDataUpdateService;
import com.yeejoin.amos.boot.module.jg.biz.service.IIdxBizJgInspectionDetectionInfoService;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.IdxBizJgDesignInfoServiceImpl;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.IdxBizJgFactoryInfoServiceImpl;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.IdxBizJgMaintenanceRecordInfoServiceImpl;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.IdxBizJgUseInfoServiceImpl;
import com.yeejoin.amos.boot.module.ymt.api.entity.*;
import com.yeejoin.amos.boot.module.ymt.api.mapper.CategoryOtherInfoMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static com.alibaba.fastjson.JSON.toJSONString;

@Component
@RequiredArgsConstructor
@Slf4j
public class EquipRefreshHandler implements IDataRefreshHandler {

    private final IdxBizJgUseInfoServiceImpl useInfoService;
    private final IdxBizJgFactoryInfoServiceImpl factoryInfoService;
    private final IIdxBizJgInspectionDetectionInfoService iIdxBizJgInspectionDetectionInfoService;
    private final CategoryOtherInfoMapper categoryOtherInfoMapper;
    private final EsEquipmentDao esEquipmentDao;
    private final IdxBizJgMaintenanceRecordInfoServiceImpl maintenanceRecordInfoService;
    private final IdxBizJgDesignInfoServiceImpl idxBizJgDesignInfoServiceImpl;
    private final StatisticsDataUpdateService statisticsDataUpdateService;


    @Override
    public String supportType() {
        return "equipment";
    }

    @Override
    public void doRefresh(TzsDataRefreshMessage message) {
        log.info("3库数据，设备开始刷库：唯一标识：{}", message.getDataId());
        switch (DataRefreshEvent.Operation.valueOf(message.getOperation())) {
            case DELETE:
                esEquipmentDao.deleteById(message.getDataId());
            case INSERT:
            case UPDATE:
                String record = message.getDataId();
                ESEquipmentInfo esEquipmentInfo = new ESEquipmentInfo();
                Map<String, Object> map = categoryOtherInfoMapper.selectDataById(record);
                ESEquipmentCategoryDto categoryEs = JSON.parseObject(toJSONString(map), ESEquipmentCategoryDto.class);
                BeanUtil.copyProperties(categoryEs, esEquipmentInfo);
                IdxBizJgUseInfo useInfo = useInfoService.getOne(new LambdaQueryWrapper<IdxBizJgUseInfo>().eq(IdxBizJgUseInfo::getRecord, record).select(IdxBizJgUseInfo::getRecord, IdxBizJgUseInfo::getCreateDate));
                IdxBizJgDesignInfo designInfo = idxBizJgDesignInfoServiceImpl.getOne(new LambdaQueryWrapper<IdxBizJgDesignInfo>()
                        .eq(IdxBizJgDesignInfo::getRecord, record)
                        .select(IdxBizJgDesignInfo::getRecord, IdxBizJgDesignInfo::getDesignUnitName, IdxBizJgDesignInfo::getDesignUnitCreditCode));
                IdxBizJgFactoryInfo factoryInfo = factoryInfoService.getOne(new LambdaQueryWrapper<IdxBizJgFactoryInfo>()
                        .eq(IdxBizJgFactoryInfo::getRecord, record)
                        .select(IdxBizJgFactoryInfo::getRecord, IdxBizJgFactoryInfo::getProduceUnitCreditCode));
                IdxBizJgInspectionDetectionInfo inspectionDetectionInfo = iIdxBizJgInspectionDetectionInfoService.queryNewestDetailByRecord(record);
                IdxBizJgMaintenanceRecordInfo lastMaintenanceRecordInfo = maintenanceRecordInfoService.queryNewestDetailByRecord(record);
                try {
                    esEquipmentInfo.setINSPECT_DATE(inspectionDetectionInfo.getSequenceNbr() != null ? inspectionDetectionInfo.getInspectDate() != null ? inspectionDetectionInfo.getInspectDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate() : null : null);
                    esEquipmentInfo.setNEXT_INSPECT_DATE(inspectionDetectionInfo.getSequenceNbr() != null ? inspectionDetectionInfo.getNextInspectDate() != null ? inspectionDetectionInfo.getNextInspectDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate() : null : null);
                    esEquipmentInfo.setCreateDate(useInfo.getCreateDate() != null ? useInfo.getCreateDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() : null);
                } catch (Exception e) {
                    log.error("时区转换失败：{}", record, e);
                }
                esEquipmentInfo.setDesignUnitCreditCode(designInfo.getDesignUnitCreditCode());
                esEquipmentInfo.setMAINTAIN_UNIT(lastMaintenanceRecordInfo.getMeUnitCreditCode());
                esEquipmentInfo.setMAINTAIN_UNIT_NAME(lastMaintenanceRecordInfo.getMeUnitName());
                esEquipmentInfo.setDesignUnitName(designInfo.getDesignUnitName());
                esEquipmentInfo.setProduceUnitCreditCode(factoryInfo.getProduceUnitCreditCode());
                esEquipmentInfo.setInspections(inspectionDetectionInfo.getSequenceNbr() != null ? Collections.singletonList(BeanUtil.copyProperties(inspectionDetectionInfo, ESEquipmentInfo.Inspection.class)) : new ArrayList<>());
                esEquipmentInfo.setMaintenances(lastMaintenanceRecordInfo.getSequenceNbr() != null ? Collections.singletonList(BeanUtil.copyProperties(lastMaintenanceRecordInfo, ESEquipmentInfo.Maintenance.class)) : new ArrayList<>());
                esEquipmentInfo.setTechParams(this.buildTechParamByEquList(record, categoryEs.getEQU_LIST_CODE()));
                esEquipmentDao.save(esEquipmentInfo);
                break;
            default:
                log.error("unknown operation: {}", message.getOperation());
        }
    }

    private List<ESEquipmentInfo.TechParam> buildTechParamByEquList(String record, String equListCode) {
        return StringUtils.isNotEmpty(equListCode) ? statisticsDataUpdateService.getTechParams(equListCode, record) : new ArrayList<>();
    }
}
