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

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.module.hygf.api.dto.*;
import com.yeejoin.amos.boot.module.hygf.api.entity.HYGFMaintenanceTickets;
import com.yeejoin.amos.boot.module.hygf.api.entity.JpStation;
import com.yeejoin.amos.boot.module.hygf.api.entity.TdHygfJpInverterWarn;
import com.yeejoin.amos.boot.module.hygf.api.mapper.HYGFMaintenanceTicketsMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.JpStationMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.MaintenanceMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IHYGFMaintenanceTicketsService;
import com.yeejoin.amos.boot.module.hygf.api.tdenginemapper.TdHygfJpInverterWarnMapper;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.SmsRecordModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.nio.charset.StandardCharsets;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@Slf4j
@Service
public class HYGFMaintenanceTicketsServiceImpl extends BaseService<HYGFMaintenanceTicketsDto, HYGFMaintenanceTickets, HYGFMaintenanceTicketsMapper> implements IHYGFMaintenanceTicketsService {
    public static final String WARNING_RESULT_MESSAGE = "hygfmaintenance/warning/result";
    @Autowired
    EmqKeeper emqKeeper;
    @Autowired
    TdHygfJpInverterWarnMapper tdHygfJpInverterWarnMapper;
    @Value("${hygf.sms.maintenanceCode}")
    private String smsTempCode;
    @Autowired
    HYGFMaintenanceTicketsMapper hygfMaintenanceTicketsMapper;
    @Autowired
    JpStationMapper jpStationMapper;
    @Autowired
    MaintenanceMapper maintenanceMapper;

    /**
     * 分页查询
     */
    public Page<HYGFMaintenanceTicketsDto> queryForHYGFMaintenanceTicketsDtoPage(int current, int size, HYGFMaintenanceTicketsDto hygfMaintenanceTicketsDto) {
        String amosUserId = RequestContext.getExeUserId();
        PageHelper.startPage(current, size);
        List<HYGFMaintenanceTicketsDto> hygfMaintenanceTicketsDtos = this.getBaseMapper().qureyListByQueryparams(hygfMaintenanceTicketsDto,amosUserId);
        PageInfo<HYGFMaintenanceTicketsDto> page = new PageInfo<>(hygfMaintenanceTicketsDtos);
        Page<HYGFMaintenanceTicketsDto> pageNew = new Page<>();
        pageNew.setCurrent(current);
        pageNew.setTotal(page.getTotal());
        pageNew.setSize(size);
        pageNew.setRecords(page.getList());
        return pageNew;
    }

    public List<String> queryInverterSncodesByStationId(String stationId) {
        return this.getBaseMapper().queryInverterSncodesByStationId(stationId);
    }

    public HYGFMaintenanceTickets getDetailBySequenceNbr(Long sequenceNbr) {
        return this.getBaseMapper().selectById(sequenceNbr);
    }

    /**
     * 列表查询 示例
     */
    public List<HYGFMaintenanceTicketsDto> queryHYGFMaintenanceTicketsDtoList() {
        return this.queryForList("", false);
    }

    public void sendMeassageToMcb(HYGFMaintenanceTicketsDto hygfMaintenanceTicketsDto) {

        MaintenanceDto data = maintenanceMapper.selectOneById(Long.valueOf(hygfMaintenanceTicketsDto.getMaintenancePersonId()));

        if (ObjectUtil.isNotEmpty(data)) {

            HashMap<String, String> params = new HashMap<>(3);
            //电站名称：${1}，地址：${2}，逆变器sn：${3}，故障事件：${4}
            params.put("1",hygfMaintenanceTicketsDto.getStationName());
            params.put("2",hygfMaintenanceTicketsDto.getAddress());
            params.put("3",hygfMaintenanceTicketsDto.getInverterSn());
            params.put("4",hygfMaintenanceTicketsDto.getContent());
            params.put("mobile",data.getTelephone());
            params.put("smsCode", smsTempCode);
            try {
                Systemctl.smsClient.sendCommonSms(params).getResult();
            } catch (Exception e) {

                throw new BadRequest("发送短信失败：" + e.getMessage());
            }
        }

        if(hygfMaintenanceTicketsDto.getWarningId()==null){


            JpStation jpStation = jpStationMapper.selectOne(new QueryWrapper<JpStation>().eq("third_station_id", hygfMaintenanceTicketsDto.getStationId()));
            if (ObjectUtil.isEmpty(jpStation)) {
                jpStation = jpStationMapper.selectById(hygfMaintenanceTicketsDto.getStationId());
            }

            if (ObjectUtil.isNotEmpty(jpStation)) {
                //场站名称
                hygfMaintenanceTicketsDto.setStationName(jpStation.getName());
                //区域公司编码
                hygfMaintenanceTicketsDto.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
                //经销商orgCode
                hygfMaintenanceTicketsDto.setAmosCompanyCode(jpStation.getAmosCompanyCode());
                //地址
                hygfMaintenanceTicketsDto.setStationAddress(jpStation.getAddress());
                //经度
                hygfMaintenanceTicketsDto.setStationLongitude(jpStation.getLongitude());
                //纬度
                hygfMaintenanceTicketsDto.setStationLatitude(jpStation.getLatitude());
                //电站联系人电话
                hygfMaintenanceTicketsDto.setStationContactPhone(jpStation.getUserPhone());
                // 电站联系人
                hygfMaintenanceTicketsDto.setStationContact(jpStation.getStationContact());
                //业主姓名
                hygfMaintenanceTicketsDto.setOwnerName(jpStation.getUserName());

                if (ObjectUtil.isEmpty(hygfMaintenanceTicketsDto.getStationContact())) {
                    hygfMaintenanceTicketsDto.setStationContact(jpStation.getUserName());
                }
            }
            MaintenanceDto maintenance = maintenanceMapper.selectOneById(Long.valueOf(hygfMaintenanceTicketsDto.getMaintenancePersonId()));
            if (ObjectUtil.isNotEmpty(maintenance)) {
                hygfMaintenanceTicketsDto.setMaintenancePersonName(maintenance.getName());
                hygfMaintenanceTicketsDto.setMaintenancePersonPhone(maintenance.getTelephone());

                HashMap<String, String> params = new HashMap<>(6);

                params.put("1",hygfMaintenanceTicketsDto.getStationName());
                params.put("2",hygfMaintenanceTicketsDto.getStationAddress());
                params.put("3",hygfMaintenanceTicketsDto.getInverterSn());
                params.put("4",hygfMaintenanceTicketsDto.getWarningContent());
                params.put("mobile",maintenance.getTelephone());
                params.put("smsCode", smsTempCode);
                try {
                    Systemctl.smsClient.sendCommonSms(params).getResult();
                } catch (Exception e) {

                    throw new BadRequest("发送短信失败：" + e.getMessage());
                }
            }
            HYGFMaintenanceTickets fMaintenanceTickets=new HYGFMaintenanceTickets();
            BeanUtils.copyProperties(hygfMaintenanceTicketsDto,fMaintenanceTickets);
            fMaintenanceTickets.setWarningId(0l);
            this.save(fMaintenanceTickets);

        }else{
        HashMap<String, Object> messageMain = new HashMap<>();
        HashMap<String, Object> rawData = new HashMap<>();
        HashMap<String, Object> bizInfo = new HashMap<>();
        HashMap<String, Object> specialMap = new HashMap<>();
        List<RiskDynamicDetailsVo> riskDynamicDetailsVoList = new ArrayList<>();
        RiskDynamicDetailsVo riskDynamicDetailsVo = new RiskDynamicDetailsVo();
        riskDynamicDetailsVo.setSpecialMap(specialMap);
        //电站id
        specialMap.put("stationId", hygfMaintenanceTicketsDto.getStationId());
        //电站名称
        specialMap.put("stationName", hygfMaintenanceTicketsDto.getStationName());
        specialMap.put("inverterSncode", hygfMaintenanceTicketsDto.getInverterSn());
        //告警id
        specialMap.put("warningId", hygfMaintenanceTicketsDto.getWarningId());
        specialMap.put("taskStartTime", hygfMaintenanceTicketsDto.getTaskStartTime());
        specialMap.put("taskEndTime", hygfMaintenanceTicketsDto.getTaskEndTime());

        specialMap.put("creatorUserId", hygfMaintenanceTicketsDto.getCreatorUserId());


        if (ObjectUtil.isNotEmpty(hygfMaintenanceTicketsDto.getWarningId())) {
            //告警内容
            specialMap.put("warningContent", hygfMaintenanceTicketsDto.getWarningContent());
            //告警等级
            specialMap.put("warningLevel", hygfMaintenanceTicketsDto.getWarningLevel());
            //告警状态
            specialMap.put("warningStatus", hygfMaintenanceTicketsDto.getWarningStatus());
            //告警开始时间
            specialMap.put("warningStartTime", hygfMaintenanceTicketsDto.getWarningStartTime());
        }
        specialMap.put("maintenancePersonId", hygfMaintenanceTicketsDto.getMaintenancePersonId());
        //电站联系人
        specialMap.put("stationContact", hygfMaintenanceTicketsDto.getStationContact());
        //电站电话
        specialMap.put("stationContactPhone", hygfMaintenanceTicketsDto.getStationContactPhone());
        //场站地址
        specialMap.put("stationAddress", hygfMaintenanceTicketsDto.getStationAddress());
        //业主姓名
        specialMap.put("ownerName", hygfMaintenanceTicketsDto.getOwnerName());
        //告警等级
        specialMap.put("warningLevel", hygfMaintenanceTicketsDto.getWarningLevel());
        //告警内容
        specialMap.put("warningContent", hygfMaintenanceTicketsDto.getWarningContent());
        //告警状态
        riskDynamicDetailsVoList.add(riskDynamicDetailsVo);
        bizInfo.put("sourceAttributionDesc", hygfMaintenanceTicketsDto.getStationName());
        bizInfo.put("sourceAttribution", hygfMaintenanceTicketsDto.getStationName());
        bizInfo.put("dynamicDetails", riskDynamicDetailsVoList);
        bizInfo.put("warningObjectCode", hygfMaintenanceTicketsDto.getInverterSn());
        bizInfo.put("warningTime", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        bizInfo.put("warningObjectName", hygfMaintenanceTicketsDto.getStationName());



        rawData.put("traceId", hygfMaintenanceTicketsDto.getInverterSn());
        rawData.put("bizInfo", bizInfo);
        rawData.put("indexKey", hygfMaintenanceTicketsDto.getInverterSn());
        rawData.put("dataSource", "户用光伏-告警");
        rawData.put("indexValue", hygfMaintenanceTicketsDto.getInverterSn());
        messageMain.put("rawData", rawData);
//        BizMessage bizMessage = new BizMessage();
//        bizMessage.setIndexKey(hygfMaintenanceTicketsDto.getStationName());
//        bizMessage.setIndexValue(hygfMaintenanceTicketsDto.getInverterSn());
//        RiskBizInfoVo riskBizInfoVo = new RiskBizInfoVo();
//        riskBizInfoVo.setWarningObjectName(hygfMaintenanceTicketsDto.getStationName());
//        riskBizInfoVo.setWarningObjectCode(idxBizPvWarningRecord.getKks());
//        riskBizInfoVo.setSourceAttribution(stationMap.get(idxBizPvWarningRecord.getGatewayId()).getProjectOrgCode());
//        riskBizInfoVo.setSourceAttributionDesc(idxBizPvWarningRecord.getStation());
//        riskBizInfoVo.setWarningObjectType("hygfmaintenance");
//        riskBizInfoVo.setWarningTime(DateUtil.now());
//        riskBizInfoVo.setWarningObjectLinkUrl(null);
//        List<RiskDynamicDetailsVo> detailsVos = new ArrayList<>();
//        RiskDynamicDetailsVo dynamicDetailsVo = new RiskDynamicDetailsVo();
//        dynamicDetailsVo.setTabName("预警详情");
//        List<TableContentVo> tabContent  =new ArrayList<>();
//        TableContentVo tableContentVo1=new TableContentVo("1", "场站名称",  idxBizPvWarningRecord.getStation(), "text");
//        TableContentVo tableContentVo3=new TableContentVo("2", "子阵",  idxBizPvWarningRecord.getSubarray(), "text");
//        TableContentVo tableContentVo2=new TableContentVo("3", "设备名称",  idxBizPvWarningRecord.getEquipmentName(), "text");
//        TableContentVo tableContentVo4=new TableContentVo("4", "分析变量",  idxBizPvWarningRecord.getPointName(), "text");
//        TableContentVo tableContentVo5=new TableContentVo("5", "健康状态指数",  idxBizPvWarningRecord.getHealthIndex(), "text");
//        TableContentVo tableContentVo6=new TableContentVo("6", "健康等级",  idxBizPvWarningRecord.getHealthLevel(), "text");
//        TableContentVo tableContentVo7=new TableContentVo("7", "预警周期",  idxBizPvWarningRecord.getWarningPeriod(), "text");
//        TableContentVo tableContentVo8=new TableContentVo("8", "预警时间",  idxBizPvWarningRecord.getRecDate(), "text");
//        TableContentVo tableContentVo10=new TableContentVo("9", "预警等级",  idxBizPvWarningRecord.getWarningName(), "text");
//        TableContentVo tableContentVo11=new TableContentVo("10", "预警原因",  idxBizPvWarningRecord.getContent(), "text");
//        tabContent.add(tableContentVo1);
//        tabContent.add(tableContentVo2);
//        tabContent.add(tableContentVo3);
//        tabContent.add(tableContentVo4);
//        tabContent.add(tableContentVo5);
//        tabContent.add(tableContentVo6);
//        tabContent.add(tableContentVo7);
//        tabContent.add(tableContentVo8);
//        tabContent.add(tableContentVo10);
//        tabContent.add(tableContentVo11);
//        dynamicDetailsVo.setTabContent(tabContent);
//        detailsVos.add(dynamicDetailsVo);
//        riskBizInfoVo.setDynamicDetails(detailsVos);
//        bizMessage.setBizInfo(riskBizInfoVo);
        // 子系统@健康指数@预警周期
//        String traceId2 = idxBizPvWarningRecord.getSubarray()+"@"+idxBizPvWarningRecord.getHealthLevel()+"@"+idxBizPvWarningRecord.getWarningPeriod();
//        bizMessage.setTraceId2(traceId2);
        try {
            emqKeeper.getMqttClient().publish(WARNING_RESULT_MESSAGE, JSON.toJSONString(messageMain).getBytes(StandardCharsets.UTF_8), 2, false);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        }
    }

    public HYGFMaintenanceTicketsDto updateHYGFMaintenanceTicketsDto(HYGFMaintenanceTicketsDto hygfMaintenanceTicketsDto) {
        hygfMaintenanceTicketsDto.setHandlerStatus("已处理");
        if(ObjectUtil.isNotEmpty(hygfMaintenanceTicketsDto.getWarningId())&&hygfMaintenanceTicketsDto.getWarningId()>0){
            hygfMaintenanceTicketsDto.setTaskEndTime(new Date());
            Long day = DateUtil.between(hygfMaintenanceTicketsDto.getWarningStartTime(),hygfMaintenanceTicketsDto.getTaskEndTime(), DateUnit.DAY);
            Long hour = DateUtil.between(hygfMaintenanceTicketsDto.getWarningStartTime(),hygfMaintenanceTicketsDto.getTaskEndTime(), DateUnit.HOUR)-day*24;
            Long minute = DateUtil.between(hygfMaintenanceTicketsDto.getWarningStartTime(),hygfMaintenanceTicketsDto.getTaskEndTime(), DateUnit.MINUTE)-day*24*60;
            hygfMaintenanceTicketsDto.setWarningDuration(day+"天"+hour+"小时"+minute+"分钟");
        }else {
            Long day = DateUtil.between(hygfMaintenanceTicketsDto.getTaskStartTime(),hygfMaintenanceTicketsDto.getRecDate(), DateUnit.DAY);
            Long hour = DateUtil.between(hygfMaintenanceTicketsDto.getTaskStartTime(),hygfMaintenanceTicketsDto.getRecDate(), DateUnit.HOUR)-day*24;
            Long minute = DateUtil.between(hygfMaintenanceTicketsDto.getTaskStartTime(),hygfMaintenanceTicketsDto.getRecDate(), DateUnit.MINUTE)-day*24*60;
            hygfMaintenanceTicketsDto.setWarningDuration(day+"天"+hour+"小时"+minute+"分钟");
        }
        this.updateWithModel(hygfMaintenanceTicketsDto);
//        if(ObjectUtil.isNotEmpty(hygfMaintenanceTicketsDto.getWarningId())){
//            TdHygfJpInverterWarn tdHygfJpInverterWarn = tdHygfJpInverterWarnMapper.getInverTerWarnByparams(hygfMaintenanceTicketsDto.getWarningId(), hygfMaintenanceTicketsDto.getInverterSn(), hygfMaintenanceTicketsDto.getStationId());
//            if (ObjectUtil.isNotEmpty(tdHygfJpInverterWarn)) {
//                tdHygfJpInverterWarn.setHandlerStatus("已处理");
//            }
//            tdHygfJpInverterWarnMapper.insert(tdHygfJpInverterWarn);
//        }
        log.info("更新运维工单成功{}", JSON.toJSONString(hygfMaintenanceTicketsDto));
        return hygfMaintenanceTicketsDto;
    }



    public Page<HYGFMaintenanceTicketsDto> queryForPageList(int current, int size, HYGFMaintenanceTicketsDto hygfMaintenanceTicketsDto) {
        String amosUserId = RequestContext.getExeUserId();
        PageHelper.startPage(current, size);
        List<HYGFMaintenanceTicketsDto> hygfMaintenanceTicketsDtos = this.getBaseMapper().queryForPageList(hygfMaintenanceTicketsDto,amosUserId);
        PageInfo<HYGFMaintenanceTicketsDto> page = new PageInfo<>(hygfMaintenanceTicketsDtos);
        Page<HYGFMaintenanceTicketsDto> pageNew = new Page<>();
        pageNew.setCurrent(current);
        pageNew.setTotal(page.getTotal());
        pageNew.setSize(size);
        pageNew.setRecords(page.getList());
        return pageNew;
    }
}
