package com.cico.nest.lcdp.boot.core.qxsd.infrastructure.gatewayimpl.http.xlw;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONArray;
import com.cico.nest.lcdp.boot.core.qxsd.domain.gateway.HistoryGateway;
import com.cico.nest.lcdp.boot.core.qxsd.domain.vehicle.HistoryTunnelVehicle;
import com.cico.nest.lcdp.boot.core.qxsd.infrastructure.gatewayimpl.database.dataobject.EventDetailDO;
import com.cico.nest.lcdp.boot.core.qxsd.infrastructure.gatewayimpl.database.dataobject.EventHisDO;
import com.cico.nest.lcdp.boot.core.qxsd.infrastructure.gatewayimpl.http.HistoryMapper;
import com.cico.nest.lcdp.boot.core.qxsd.infrastructure.gatewayimpl.http.xlw.dto.*;
import com.cico.nest.lcdp.boot.core.qxsd.infrastructure.gatewayimpl.http.xlw.feign.XlwClientFeign;
import com.cico.nest.lcdp.boot.core.qxsd.infrastructure.gatewayimpl.ws.xlw.dto.XlwRealTimeVehicleDTO;
import com.cico.nest.lcdp.framework.common.util.json.JsonUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zws
 * @date 2024/8/20
 */

@Component
@Slf4j
public class XlwHistoryMapper implements HistoryMapper {
    @Resource
    private XlwClientFeign xlwClientFeign;

    @Value("${qxsd.xlw.images}")
    private String xlwImagePath;
    @Value("${qxsd.images.eventSavePath}")
    private String eventSavePath;
    @Value("${qxsd.images.bayonetSavePath}")
    private String bayonetSavePath;
    @Value("${qxsd.images.bayonetDownPath}")
    private String bayonetDownPath;
    @Override
    public List<XlwHolographicTimeHistoryDTO> getVehicleInfo(String eventId) {
        XlwEventIdDTO eventIdDTO = new XlwEventIdDTO(eventId);
        return xlwClientFeign.getHolographicTimeHistory(eventIdDTO).getData();
    }

    @Override
    public String saveEventImage(String urlPath) {
        if (StringUtils.isEmpty(urlPath)){
            return null;
        }
        String [] urlPaths = urlPath.split("/");
        String dateFolder =  urlPaths[urlPaths.length -2];
        File dateFolderFile = new File(eventSavePath + "/" + dateFolder);
        if(!dateFolderFile.exists()){
            dateFolderFile.mkdirs();
        }
        String imageUrl = xlwImagePath + urlPath;
        String saveImageUrl = eventSavePath + "/" + dateFolder + "/" + urlPaths[urlPaths.length - 1];
        String savePath = doSaveImage(imageUrl,saveImageUrl);
        if("error".equals(savePath)){
            return "saveEventImage error ";
        }
        return "/" + dateFolder + "/" + urlPaths[urlPaths.length - 1];
    }

    @Override
    public EventHisDO.EventHisExpandInfo saveBayonetImage(String carPlate, Date eventStartTime) {
        XlwBayonetPictureSearchDTO searchDTO = new XlwBayonetPictureSearchDTO();
        searchDTO.setPage(1);
        searchDTO.setPageSize(10);
        searchDTO.setPlateNumber(carPlate);
        searchDTO.setPositionMark("入");
        Date startDate = DateUtil.offsetMinute(eventStartTime,-30);
        Date endDate = DateUtil.offsetMinute(eventStartTime,30);
        searchDTO.setStartImageTime(DateUtil.format(startDate,"yyyy-MM-dd HH:mm:ss"));
        searchDTO.setEndImageTime(DateUtil.format(endDate,"yyyy-MM-dd HH:mm:ss"));
        EventHisDO.EventHisExpandInfo eventHisExpandInfo = new EventHisDO.EventHisExpandInfo();
        List<XlwBayonetPictureDTO> pictureDTOS = new ArrayList<>();
        try {
            XlwPageDTO<XlwBayonetPictureDTO> pageDTO = xlwClientFeign.getBayonetPicture(searchDTO).getData();
            pictureDTOS = pageDTO.getRows();
            log.info("查询信路威抓拍流水卡口图片,参数:{},返回条数:{}" ,searchDTO,pageDTO.getRows().size() );
        } catch (Exception e) {
            log.info("查询信路威抓拍流水卡口图片参数：{}" , JsonUtils.toJsonString(searchDTO));
            log.info("查询信路威抓拍流水卡口图片异常：{}" ,e.getMessage());
            return eventHisExpandInfo;
        }
        if(!pictureDTOS.isEmpty()){
            XlwBayonetPictureDTO bayonetPictureDTO = pictureDTOS.get(0);
            String plateImageUrl = bayonetPictureDTO.getPlateImage();
            if(StringUtils.isEmpty(plateImageUrl)){
                return eventHisExpandInfo;
            }
            //保存文件夹
            String [] plateUrlPaths = plateImageUrl.split("/");
            String dateFolder =  plateUrlPaths[plateUrlPaths.length -2];
            File dateFolderFile = new File(bayonetSavePath + "/" + dateFolder);
            if(!dateFolderFile.exists()){
                dateFolderFile.mkdirs();
            }
            eventHisExpandInfo.setPlateImage(imageTo("卡口图片",carPlate,bayonetPictureDTO.getPlateImage(),xlwImagePath,dateFolder));
            eventHisExpandInfo.setHeadImage(imageTo("车头图片",carPlate,bayonetPictureDTO.getHeadImage(),xlwImagePath,dateFolder));
            eventHisExpandInfo.setSmallSideImage(imageTo("车辆图片",carPlate,bayonetPictureDTO.getSmallSideImage(),xlwImagePath,dateFolder));
        }
        return eventHisExpandInfo;
    }

    private String imageTo(String str,String carPlate,String headImageUrl,String xlwImagePath,String dateFolder){
        log.info("查询信路威抓拍流水卡口图片,车牌【{}】,{}图片路径：{}" ,carPlate,str,headImageUrl);
        String [] headUrlPaths = headImageUrl.split("/");
        String fileName = headUrlPaths[headUrlPaths.length - 1];
        String headSaveImageUrl = bayonetSavePath + "/" + dateFolder + "/" + fileName;
        String headSavePath = doSaveImage( xlwImagePath +headImageUrl,headSaveImageUrl);
        if("error".equals(headSavePath)){
            return "head_error";
        }else{
            return "/" + dateFolder + "/" + fileName;
        }
    }

    private String doSaveImage(String downloadUrl,String saveUrl){
        if (StringUtils.isEmpty(downloadUrl) ){
            log.error("下载图片的路径为空:" + downloadUrl );
            return "error";
        }
        try{
            //创建URL对象
            URL url = new URL(downloadUrl);
            //建立HTTP连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            //获取输入流
            InputStream inputStream = connection.getInputStream();
            //创建本地文件输出流
            FileOutputStream outputStream = new FileOutputStream(saveUrl);
            //读取数据并写入文件
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            //关闭流
            inputStream.close();
            outputStream.close();
        }catch (IOException e){
            log.error("下载图片失败:" + downloadUrl ,e);
            return "error";
        }
        return "";
    }

}
