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 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 List<String> saveBayonetImage(String carPlate, Date eventStartTime) {
        XlwBayonetPictureSearchDTO searchDTO = new XlwBayonetPictureSearchDTO();
        searchDTO.setPage(1);
        searchDTO.setPageSize(10);
        searchDTO.setPlateNumber(carPlate);
        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"));
        List<XlwBayonetPictureDTO> pictureDTOS = new ArrayList<>();
        try {
            XlwPageDTO<XlwBayonetPictureDTO> pageDTO = xlwClientFeign.getBayonetPicture(searchDTO).getData();
            pictureDTOS = pageDTO.getRows();
        } catch (Exception e) {
            log.info("查询信路威抓拍流水卡口图片异常：{}" ,e.getMessage());
        }
        List<String> bayonetImageUrls = new ArrayList<>();
        if(!pictureDTOS.isEmpty()){
            XlwBayonetPictureDTO bayonetPictureDTO = pictureDTOS.get(0);
            String plateImageUrl = bayonetPictureDTO.getPlateImage();
            log.info("车牌卡口图片路径：" + plateImageUrl);
            if(StringUtils.isEmpty(plateImageUrl)){
                return bayonetImageUrls;
            }
            String [] plateUrlPaths = plateImageUrl.split("/");
            String dateFolder =  plateUrlPaths[plateUrlPaths.length -2];
            File dateFolderFile = new File(bayonetSavePath + "/" + dateFolder);
            if(!dateFolderFile.exists()){
                dateFolderFile.mkdirs();
            }
            String plateSaveImageUrl = bayonetSavePath + "/" + dateFolder + "/" + plateUrlPaths[plateUrlPaths.length - 1];
            String plateSavePath = doSaveImage( xlwImagePath +plateImageUrl,plateSaveImageUrl);
            if("error".equals(plateSavePath)){
                bayonetImageUrls.add("plate_error");
            }else{
                bayonetImageUrls.add("/" + dateFolder + "/" + plateUrlPaths[plateUrlPaths.length - 1]);
            }
            String headImageUrl = bayonetPictureDTO.getHeadImage();
            log.info("车头图片路径：" + headImageUrl);
            String [] headUrlPaths = headImageUrl.split("/");
            String headSaveImageUrl = bayonetSavePath + "/" + dateFolder + "/" + headUrlPaths[headUrlPaths.length - 1];
            String headSavePath = doSaveImage( xlwImagePath +headImageUrl,headSaveImageUrl);
            if("error".equals(headSavePath)){
                bayonetImageUrls.add("head_error");
            }else{
                bayonetImageUrls.add("/" + dateFolder + "/" + headUrlPaths[headUrlPaths.length - 1]);
            }
        }
        return bayonetImageUrls;
    }

    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 "";
    }

}
