package com.yeejoin.amos.boot.module.statistcs.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.module.elevator.api.dto.FormValue;
import com.yeejoin.amos.boot.module.elevator.api.entity.VoiceRecordFile;
import com.yeejoin.amos.boot.module.elevator.api.mapper.*;
import com.yeejoin.amos.boot.module.statistcs.biz.utils.JsonUtils;
import com.yeejoin.amos.boot.module.elevator.api.dto.AlertCalledDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.AlertCalledFormDto;
import com.yeejoin.amos.boot.module.elevator.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.elevator.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.elevator.api.entity.Elevator;
import com.yeejoin.amos.boot.module.elevator.api.entity.RepairConsult;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.DateUtil;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

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

@Service
public class EmergencyBizServiceImpl {

    @Value("classpath:/json/emergencyInformation.json")
    private Resource emergencyInformation;

    @Autowired
    public EmergencyBizServiceImpl(ElevatorMapper elevatorMapper,
                                   AlertCalledMapper alertCalledMapper,
                                   RepairConsultMapper repairConsultMapper,
                                   AlertFormValueMapper alertFormValueMapper,
                                   VoiceRecordFileMapper voiceRecordFileMapper) {
        this.elevatorMapper = elevatorMapper;
        this.alertCalledMapper = alertCalledMapper;
        this.repairConsultMapper = repairConsultMapper;
        this.alertFormValueMapper = alertFormValueMapper;
        this.voiceRecordFileMapper = voiceRecordFileMapper;
    }

    private ElevatorMapper elevatorMapper;
    private AlertCalledMapper alertCalledMapper;
    private RepairConsultMapper repairConsultMapper;
    private AlertFormValueMapper alertFormValueMapper;
    private VoiceRecordFileMapper voiceRecordFileMapper;

    public Object getDetail(Long id) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HashMap<String, Object> keyinfoData = new HashMap<>();
        // 基本信息
        List<FormValue> jsonData = JsonUtils.getJsonData(emergencyInformation);
        AlertCalledFormDto alertCalledFormVo = getAlertCalledFormDto(id);
        Map<String, Object> objectMap = Bean.BeantoMap(alertCalledFormVo.getAlertCalledDto());
        List<FormValue> dynamicFormAlert = alertCalledFormVo.getDynamicFormAlert();
        jsonData.forEach(f -> {
            Object o = objectMap.get(f.getKey());
            if (!ObjectUtils.isEmpty(o)) {
                f.setValue(o.toString());
                if ("callTime".equals(f.getKey())) {
                    f.setValue(simpleDateFormat.format(alertCalledFormVo.getAlertCalledDto().getCallTime()));
                }
            }
        });
        jsonData.addAll(dynamicFormAlert);
        // 使用单位信息
        // 获取根据警情获取电梯信息
        Map<String, Object> map = this.selectByAlertId(id);
        // 根据设备id 获取使用单位信息
        Map<String, Object> useUnitMap = elevatorMapper.selectUseUnitByAlertId(String.valueOf(map.get("sequenceNbr")));
        if (!ObjectUtils.isEmpty(useUnitMap)) {
            jsonData.forEach(f -> {
                // 单位名称
                if ("useUnitName".equals(f.getKey())) {
                    f.setValue(ObjectUtils.isEmpty(useUnitMap.get("useUnitName")) ? null : String.valueOf(useUnitMap.get("useUnitName")));
                }
                // 单位地址
                if ("unitAddress".equals(f.getKey())) {
                    f.setValue(ObjectUtils.isEmpty(useUnitMap.get("address")) ? null : String.valueOf(useUnitMap.get("address")));
                }
                // 安全管理员
                if ("securityAdministrator".equals(f.getKey())) {
                    f.setValue(ObjectUtils.isEmpty(useUnitMap.get("manager")) ? null : String.valueOf(useUnitMap.get("manager")));
                }
                // 安全管理员电话
                if ("securityAdministratorPhone".equals(f.getKey())) {
                    f.setValue(ObjectUtils.isEmpty(useUnitMap.get("managerPhone")) ? null : String.valueOf(useUnitMap.get("managerPhone")));
                }
            });
        }
        // 处置记录
        LambdaQueryWrapper<RepairConsult> queryWrapper = new LambdaQueryWrapper<RepairConsult>();
        queryWrapper.eq(RepairConsult::getParentId, id).orderByDesc(RepairConsult::getRecDate);
        List<RepairConsult> list = repairConsultMapper.selectList(queryWrapper);
        HashMap<String, Object> datas = new HashMap<>();
        ArrayList<Map<String, Object>> records = new ArrayList<>();
        list.forEach(r -> {
            HashMap<String, Object> data = new HashMap<>();
            data.put("label", r.getAlertStatus());
            data.put("operatingTime", r.getRecDate());
            data.put("operater", r.getDescription());
            records.add(data);
        });
        // 96333码
        HashMap<String, Object> qrcode = new HashMap<>();
        if (!ObjectUtils.isEmpty(alertCalledFormVo.getAlertCalledDto())) {
            qrcode.put("title", "96333码");
            qrcode.put("value", alertCalledFormVo.getAlertCalledDto().getDeviceId());
            try {
                String problemTime = DateUtil.formatDate(new Date(), DateUtil.Y_M_D_HMS);
                qrcode.put("text", DateUtil.formatDate(DateUtil.smartFormat(problemTime), "yyyy-MM-dd"));
                qrcode.put("subtext", DateUtil.formatDate(DateUtil.smartFormat(problemTime), "HH:mm:ss"));
                String color;
                if (alertCalledFormVo.getAlertCalledDto().getAlertStatus()) {
                    color = "green";
                } else {
                    color = "red";
                }
                qrcode.put("color", color);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        datas.put("datas", records);
        datas.put("title", "处置记录");
        datas.put("renderType", "timeline");
        keyinfoData.put("title", ObjectUtils.isEmpty(useUnitMap.get("useUnitName")) ? null : String.valueOf(useUnitMap.get("useUnitName")));
        keyinfoData.put("keyParams", jsonData);
        keyinfoData.put("infoRecords", datas);
        keyinfoData.put("qrcode", qrcode);
        return keyinfoData;
    }

    public AlertCalledFormDto getAlertCalledFormDto(Long id) {
        // 警情基本信息
        AlertCalled alertCalled = alertCalledMapper.selectById(id);
        LambdaQueryWrapper<AlertFormValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlertFormValue::getAlertCalledId, id);
        // 警情动态表单数据
        List<AlertFormValue> list = alertFormValueMapper.selectList(queryWrapper);
        List<FormValue> formValue = new ArrayList<FormValue>();
        if (list != null && !list.isEmpty()) {
            for (AlertFormValue alertFormValue : list) {
                FormValue value = new FormValue(alertFormValue.getFieldCode(), alertFormValue.getFieldName(), "text", alertFormValue.getFieldValue(), alertFormValue.getBlock());
                formValue.add(value);
            }
        }
        AlertCalledDto alertCalledDto = new AlertCalledDto();
        BeanUtils.copyProperties(alertCalled, alertCalledDto);
        Elevator elevator = new Elevator();
        elevator.setRescueCode(Integer.valueOf(alertCalled.getDeviceId()));
        elevator.setRegisterCode(alertCalled.getRegistrationCode());
        Map<String, Object> map = elevatorMapper.selectElevator(elevator);
        if (!ObjectUtils.isEmpty(map)) {
            alertCalledDto.setAddress(String.valueOf(map.get("address")));
            alertCalledDto.setProvince(String.valueOf(map.get("province")));
            alertCalledDto.setCity(String.valueOf(map.get("city")));
            alertCalledDto.setDistrict(String.valueOf(map.get("district")));
            alertCalledDto.setUseStatus(String.valueOf(map.get("useStatus")));
            alertCalledDto.setUseSiteCategory(ObjectUtils.isEmpty(map.get("useSiteCategory")) || "null".equals(String.valueOf(map.get("useSiteCategory"))) ? null : String.valueOf(map.get("useSiteCategory")));
            alertCalledDto.setUseUnit(String.valueOf(map.get("useUnit")));
            alertCalledDto.setRegionCode(String.valueOf(map.get("regionCode")));
        }

        String voiceRecord = "";
        VoiceRecordFile temp = voiceRecordFileMapper.selectOne(new LambdaQueryWrapper<VoiceRecordFile>().eq(VoiceRecordFile::getAlertId, id).eq(VoiceRecordFile::getAlertStageCode, "860").orderByAsc(VoiceRecordFile::getTelStartTime).last("limit 1"));
        if (temp != null) {
            voiceRecord = temp.getFilePath();
        }
        return new AlertCalledFormDto(alertCalledDto, formValue, voiceRecord);
    }

    public Map<String, Object> selectByAlertId(Long alertId) {
        AlertCalled alertCalled = alertCalledMapper.selectById(alertId);
        if (ValidationUtil.isEmpty(alertCalled)
                || ValidationUtil.isEmpty(alertCalled.getDeviceId())) {
            throw new BadRequest("警情不存在或者设备编码不存在");
        }
        // 设备类型 和 编码 确定设备的使用单位或者维保单位
        String equipmentClassificationCode = alertCalled.getEquipmentClassificationCode();
        String deviceId = alertCalled.getEquipmentId();
        // 目前只有电梯类型
        Elevator elevator = new Elevator();
        elevator.setOriginalId(deviceId);
        Map<String, Object> map = elevatorMapper.selectElevator(elevator);
        if (ValidationUtil.isEmpty(map)) {
            throw new BadRequest("设备未找到");
        }
        return map;
    }
}
