package com.mirs.biz.controller;

import com.mirs.biz.domain.BrdfData;
import com.mirs.biz.domain.EmiMeasurement;
import com.mirs.biz.domain.IntegratedData;
import com.mirs.biz.domain.Sample;
import com.mirs.biz.dto.IndexResultDTO;
import com.mirs.biz.dto.IndexSearchDTO;
import com.mirs.biz.service.IBrdfDataService;
import com.mirs.biz.service.IEmiMeasurementService;
import com.mirs.biz.service.IIntegratedDataService;
import com.mirs.biz.service.ISampleService;
import com.mirs.common.config.RuoYiConfig;
import com.mirs.common.core.controller.BaseController;
import com.mirs.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/index/search")
public class IndexController extends BaseController {
    @Autowired
    private IBrdfDataService brdfDataService;
    @Autowired
    private IEmiMeasurementService emiMeasurementService;

    @Autowired
    private IIntegratedDataService integratedDataService;

    @Autowired
    private ISampleService sampleService;

    @Autowired
    private RestTemplate restTemplate;
    /**
     * 查询主页的数据
     */

    @GetMapping("/getIndexInfo")
    public AjaxResult getIndexInfo(IndexSearchDTO dto) {
        IndexResultDTO indexResultDTO = new IndexResultDTO();
        Sample sample = sampleService.getOne(dto.getSample());

        if (sample == null) {
            indexResultDTO.setBrdfDataList(new ArrayList<>());
            indexResultDTO.setEmiMeasurementList(new ArrayList<>());
            indexResultDTO.setIntegratedDataList(new ArrayList<>());
            return success(indexResultDTO);
        }
        if ("1".equals(dto.getDataType())) {
            List<EmiMeasurement> emiMeasurementList = emiMeasurementService.selectEmiMeasurementList(dto.getEmiMeasurement());
            List<IntegratedData> integratedDataList = integratedDataService.selectIntegratedDataList(dto.getIntegratedData());
            indexResultDTO.setEmiMeasurementList(emiMeasurementList);
            indexResultDTO.setIntegratedDataList(integratedDataList);
        } else {
            List<BrdfData> brdfData = brdfDataService.selectBrdfDataList(dto.getBrdfData());
            // 调用画图接口
            String imagePath = getImagePath();
            indexResultDTO.setBrdfImagePath("/profile/upload/" + imagePath);
            getImage(brdfData, "D:/mirs/uploadPath/upload" + imagePath);
            indexResultDTO.setBrdfDataList(brdfData);
        }

        indexResultDTO.setSample(sample);

        return success(indexResultDTO);
    }

    private String getImagePath() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 定义日期部分格式
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("/yyyy/MM/dd");
        String datePath = now.format(dateFormatter);

        // 定义文件名时间部分格式（精确到微秒）
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String timePart = now.format(timeFormatter);

        // 组合完整路径
        return datePath + "/image" + timePart + ".png";
    }

    private void getImage(List<BrdfData> brdfData, String imagePath) {
        String url = "http://localhost:8081/process_brdf";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        Map<String, Object> requestMap = new HashMap<>(4);
        requestMap.put("filePath", imagePath);
        requestMap.put("brdfList", brdfData);
        HttpEntity<Map> request = new HttpEntity<>(requestMap, headers);
        logger.info("生成图片接口开始调用");
        ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
        Map body = response.getBody();
        if (body != null && (200 == (int) body.get("status"))) {
            logger.info("生成图片接口调用成功");
        } else {
            logger.warn("生成图片接口调用失败，response：{}", response);
        }
    }

    @GetMapping("/getSampleType")
    public AjaxResult getSampleType(IndexSearchDTO dto) {
        return success(sampleService.getSampleType(dto.getDataType()));
    }

    @GetMapping("/getSampleModel")
    public AjaxResult getSampleModel(IndexSearchDTO dto) {
        return success(sampleService.getSampleModel(dto));
    }

    @GetMapping("/getTemperatureK")
    public AjaxResult getTemperatureK(IndexSearchDTO dto) {
        if ("1".equals(dto.getDataType())) {
            return success(emiMeasurementService.getTemperatureK(dto.getEmiMeasurement()));
        } else {
            return success(brdfDataService.getTemperatureK(dto.getBrdfData()));
        }
    }

    @GetMapping("/getAllAngle")
    public AjaxResult getAllAngle(IndexSearchDTO dto) {
        return success(brdfDataService.getAllAngle(dto.getBrdfData()));
    }
    @GetMapping("/getOthersOptions")
    public AjaxResult getOthersOptions(IndexSearchDTO dto) {
        Map<String, Object> result = new HashMap<>(4);
        if("1".equals(dto.getDataType())){
            result.put("temperatureKOptions", emiMeasurementService.getTemperatureK(dto.getEmiMeasurement()));

            Map<String, Object> resultMap = new HashMap<>(4);
            resultMap.put("thetaIncidentOptions", new ArrayList<>());
            resultMap.put("phiIncidentOptions", new ArrayList<>());
            resultMap.put("thetaReflectedOptions", new ArrayList<>());
            resultMap.put("phiReflectedOptions", new ArrayList<>());
            result.put("allAngleOptions", resultMap);
        } else {
            result.put("temperatureKOptions", brdfDataService.getTemperatureK(dto.getBrdfData()));

            result.put("allAngleOptions", brdfDataService.getAllAngle(dto.getBrdfData()));
        }
        return success(result);
    }
}
