
package com.yeejoin.equipmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.interceptors.PermissionInterceptorContext;
import com.yeejoin.equipmanage.common.dto.FireRiskSourceDto;
import com.yeejoin.equipmanage.common.entity.*;
import com.yeejoin.equipmanage.common.enums.DynamicLabelEnum;
import com.yeejoin.equipmanage.common.enums.EquipQrcodeColorEnum;
import com.yeejoin.equipmanage.common.enums.RiskSourceTypeEnum;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.common.utils.TreeNodeUtil;
import com.yeejoin.equipmanage.common.vo.*;
import com.yeejoin.equipmanage.mapper.*;
import com.yeejoin.equipmanage.service.IEquipmentSpecificIndexService;
import com.yeejoin.equipmanage.service.IRiskSourceService;
import liquibase.pro.packaged.E;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service("riskSourceService")
public class RiskSourceServiceImpl implements IRiskSourceService {

    static IEquipmentSpecificIndexService equipmentSpecificIndexService;

    @Autowired
    private RiskSourceMapper riskSourceMapper;

    @Autowired
    private EquipmentSpecificMapper equipmentSpecificMapper;

    @Autowired
    EquipmentDetailMapper equipmentDetailMapper;

    @Autowired
    private ManufacturerInfoMapper manufacturerInfoMapper;

    @Autowired
    private FireFightingSystemMapper fireFightingSystemMapper;

    @Autowired
    EquipmentSpecificIndexMapper equipmentSpecificIndexMapper;

    @Value("${auth-key-auth-enabled:}")
    private String authKey;

    @Override
    @Transactional
    public List<FireRiskSourceDto> getFiskSourceTierTree(Integer tier, Boolean isRegion) {
        List<FireRiskSourceDto> list = null;
        if (isRegion != null) {
            list = riskSourceMapper.findByIsRegion(isRegion);
        } else {
            list = riskSourceMapper.findAll();
        }
        if (!CollectionUtils.isEmpty(list)) {
            if (tier != null) {
                return TreeNodeUtil.assembleTree(list, tier);
            } else {
                return TreeNodeUtil.assembleTree(list);
            }
        }
        return Lists.newArrayList();
    }

    public RiskBizInfoVo getEquipmentToRiskInfo(String source, String id, String indexKey){
        String equipmentSpecId = null;
        SendToMsgRiskDetailVo detailVo = new SendToMsgRiskDetailVo();
        SendToMsgRiskEquipInfoVo equipInfoVo = new SendToMsgRiskEquipInfoVo();
        SendToMsgRiskAlarmInfoVo equipAlarm = new SendToMsgRiskAlarmInfoVo();
        Map<String, Object> m = new HashMap<>();
        RiskBizInfoVo infoVo = new RiskBizInfoVo();
        // 权限处理
        PermissionInterceptorContext.setDataAuthRule(authKey);
        if (source.equalsIgnoreCase(RiskSourceTypeEnum.PATROL.getName())) {
            List<Map<String, Object>> checkInputItems = equipmentSpecificMapper.queryCheckInputItemsByCheckId(id);
            Map<String, Object> map = checkInputItems.get(0);
            if (map.containsKey("equipId")) {
                equipmentSpecId = String.valueOf(map.get("equipId"));
                Map<String, Object> pointMap = equipmentSpecificMapper.getPointById(Long.valueOf(String.valueOf(map.get("pointId"))));
                equipAlarm.setIndexNo(String.valueOf(pointMap.get("id")));
                equipAlarm.setName(String.valueOf(pointMap.get("pointName")));
                equipAlarm.setIndexNo(String.valueOf(pointMap.get("pointNo")));
                equipAlarm.setKey(String.valueOf(map.get("inputItem")));
                equipAlarm.setValue(String.valueOf(map.get("input_value")));

                equipInfoVo.setName(String.valueOf(map.get("inputItem")));
                equipInfoVo.setValue(String.valueOf(map.get("input_value")));
                equipInfoVo.setCode(String.valueOf(map.get("item_no")));
                equipInfoVo.setBizOrgCode(String.valueOf(map.get("biz_org_code")));
                equipInfoVo.setBizOrgName(String.valueOf(map.get("biz_org_name")));

                Map<String, Object> patrolMap = equipmentSpecificMapper.getPatrolData(Long.valueOf(id));
                m.put("station", String.valueOf(map.get("biz_org_name")));
                m.put("stationCode", String.valueOf(map.get("biz_org_code")));
                m.put("planName", String.valueOf(patrolMap.get("planName")));
                m.put("routeName", String.valueOf(patrolMap.get("routeName")));
                m.put("pointName", String.valueOf(patrolMap.get("pointName")));
                m.put("inputItemName", String.valueOf(patrolMap.get("inputName")));
                m.put("checkUser", String.valueOf(patrolMap.get("username")));
                m.put("checkResult", String.valueOf(patrolMap.get("inputStatus")));
                m.put("checkTime", String.valueOf(patrolMap.get("checkTime")));
                infoVo.setSourceSupplyField(String.valueOf(patrolMap.get("checkInputId")));
            }
        } else if (source.equalsIgnoreCase(RiskSourceTypeEnum.EQUIP.getName())) {
            equipmentSpecId = id;
            QueryWrapper<EquipmentSpecificIndex> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("equipment_specific_id", equipmentSpecId);
            queryWrapper.eq("equipment_index_key", indexKey);
            EquipmentSpecificIndex equipmentSpeIndex = equipmentSpecificIndexMapper.selectOne(queryWrapper);
            equipAlarm.setKey(indexKey);
            equipAlarm.setValue(equipmentSpeIndex.getValue());
            equipAlarm.setAlarmContent(equipmentSpeIndex.getEquipmentSpecificName() + equipmentSpeIndex.getEquipmentIndexName());
            equipAlarm.setAlarmDate(equipmentSpeIndex.getUpdateDate());


            equipInfoVo.setName(equipmentSpeIndex.getEquipmentSpecificName());
            equipInfoVo.setCode(equipmentSpeIndex.getEquipmentSpecificCode());
            equipInfoVo.setReportIsAlarm(Boolean.TRUE);
            equipInfoVo.setEquipSpeId(equipmentSpecId);
        } else {
            equipmentSpecId = id;
        }
        equipInfoVo.setId(equipmentSpecId);

        if (StringUtil.isNotEmpty(equipmentSpecId)) {
            EquipmentSpecific specific = equipmentSpecificMapper.selectById(equipmentSpecId);
            equipInfoVo.setPosition(specific.getPosition());
            equipInfoVo.setManufacturerName(getEquipmentDetailInfo(specific.getEquipmentDetailId()).getManufacturerName());
            equipInfoVo.setSystemIds(specific.getSystemId());
            equipInfoVo.setSystemName(getSystemNameBySpeId(specific));
            equipInfoVo.setQrCode(specific.getQrCode());
            equipInfoVo.setCodeColor(EquipQrcodeColorEnum.getEnumByKey(specific.getEquipStatus()).getColor());
            equipInfoVo.setBatchNo(getEquipmentDetailInfo(specific.getEquipmentDetailId()).getStandard());
            equipInfoVo.setBizOrgCode(specific.getBizOrgCode());
            equipInfoVo.setBizOrgName(specific.getBizOrgName());
            equipInfoVo.setName(specific.getName());
            equipInfoVo.setCode(specific.getCode());
            if (source.equalsIgnoreCase(RiskSourceTypeEnum.HIDDENDANGER.getName()) || source.equalsIgnoreCase(RiskSourceTypeEnum.DEFECT.getName()) || source.equalsIgnoreCase(RiskSourceTypeEnum.SCRAP.getName())) {
                equipInfoVo.setName(specific.getName());
                equipInfoVo.setCode(specific.getCode());
                equipInfoVo.setReportIsAlarm(Boolean.TRUE);
                equipInfoVo.setEquipSpeId(equipmentSpecId);
            }

            m.put("equipSpeId", equipmentSpecId);
            m.put("checkEquipName", specific.getName());
            m.put("equipPosition", specific.getPosition());
        } else {

        }


        detailVo.setEquipInfo(equipInfoVo);
        detailVo.setAlarmInfo(equipAlarm);

        infoVo.setWarningObjectName(detailVo.getEquipInfo().getName());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        infoVo.setWarningTime(sdf.format(new Date()));
        infoVo.setSourceAttribution(detailVo.getEquipInfo().getBizOrgCode());
        infoVo.setSourceAttributionDesc(detailVo.getEquipInfo().getBizOrgName());
        infoVo.setWarningObjectCode(detailVo.getEquipInfo().getId());
        List<RiskDynamicDetailsVo> detailsVos = new ArrayList<>();
        RiskDynamicDetailsVo dynamicDetailsVo = new RiskDynamicDetailsVo();
        dynamicDetailsVo.setTabName("预警详情");
        List<TableContentVo> contentVos = new ArrayList<>();
        for (DynamicLabelEnum u : DynamicLabelEnum.values()) {
            TableContentVo contentVo = new TableContentVo();
            contentVo.setKey(u.getCode());
            switch (u.getCode()) {
                case "name":
                    contentVo.setLabel(u.getDescribe());
                    contentVo.setValue(equipInfoVo.getName());
                    contentVo.setType("text");
                    break;
                case "code":
                    contentVo.setLabel(u.getDescribe());
                    contentVo.setValue(equipInfoVo.getCode());
                    contentVo.setType("text");
                    break;
                case "position":
                    contentVo.setLabel(u.getDescribe());
                    contentVo.setValue(equipInfoVo.getPosition());
                    contentVo.setType("text");
                    break;
                case "manufacturer":
                    contentVo.setLabel(u.getDescribe());
                    contentVo.setValue(equipInfoVo.getManufacturerName());
                    contentVo.setType("text");
                    break;
                case "systemName":
                    contentVo.setLabel(u.getDescribe());
                    contentVo.setValue(equipInfoVo.getSystemName());
                    contentVo.setType("text");
                    break;
                case "alarmContent":
                    if(!source.equalsIgnoreCase(RiskSourceTypeEnum.PATROL.getName()) && !source.equalsIgnoreCase(RiskSourceTypeEnum.SCRAP.getName())) {
                        contentVo.setLabel(u.getDescribe());
                        contentVo.setValue(equipAlarm.getAlarmContent());
                        contentVo.setType("text");
                        break;
                    } else {
                        break;
                    }
                case "alarmDate":
                    if(!source.equalsIgnoreCase(RiskSourceTypeEnum.PATROL.getName()) && !source.equalsIgnoreCase(RiskSourceTypeEnum.SCRAP.getName())) {
                        contentVo.setLabel(u.getDescribe());
                        contentVo.setValue(equipAlarm.getAlarmDate());
                        contentVo.setType("text");
                        break;
                    } else {
                        break;
                    }
                default:
                    log.info("方法参数错误 !!!");
                    break;
            }
            contentVos.add(contentVo);
        }

        dynamicDetailsVo.setTabContent(contentVos);
        dynamicDetailsVo.setSpecialMap(m);
        detailsVos.add(dynamicDetailsVo);
        infoVo.setDynamicDetails(detailsVos);
        return infoVo;
    }

    public EquipmentDetail getEquipmentDetailInfo(long id) {
        EquipmentDetail detail = equipmentDetailMapper.selectById(id);
        if (ObjectUtils.isEmpty(detail.getManufacturerId())) {
            detail.setManufacturerName("");
            return detail;
        }
        ManufacturerInfo info = manufacturerInfoMapper.selectById(detail.getManufacturerId());
        detail.setManufacturerName(ObjectUtils.isEmpty(info) ? "" : info.getName());
        return Optional.ofNullable(detail).orElse(detail);
    }

    public String getSystemNameBySpeId(EquipmentSpecific equipmentSpecific) {
        List<FireFightingSystemEntity> sys = new ArrayList<>();
        String[] ids;
        String sysIds = equipmentSpecific.getSystemId();
        if (StringUtil.isNotEmpty(sysIds)) {
            if (-1 != sysIds.indexOf(",")) {
                ids = sysIds.split(",");
                sys = fireFightingSystemMapper.getFightingSysByIds(ids);
            } else {
                FireFightingSystemEntity entity = fireFightingSystemMapper.selectById(Long.valueOf(sysIds));
                sys.add(entity);
            }
        }
        StringBuilder sb = new StringBuilder();
        sys.forEach(x -> {
            if (0 < sb.length()) {
                sb.append(",");
            }
            sb.append(x.getName());
        });
        return sb.toString();
    }


}

