package com.mvc.service.aihcxd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mvc.model.ResultGeekerModel;
import com.mvc.model.TAireadModel;
import com.mvc.model.TServerReadModel;
import com.mvc.model.aihcxd.AioOutModel;
import com.mvc.netty.dealconstant.ResourcePath;
import com.mvc.netty.dealconstant.ResourceTag;
import com.mvc.service.copy.TAireadService;
import com.mvc.service.copy.TServerReadService;
import com.mvc.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Base64;

/**
 * Onnx大模型识别(调用)
 * 针对服务侧设备使用,免配置
 */
@Service
public class OnnxIdenService {
    private static Logger log = LoggerFactory.getLogger(OnnxIdenService.class);
    //临时部署在了M3终端的服务器上,地址先固定
    private static String URL_IDEN ="http://101.42.52.141:6090/api/v1/ai/watermeters/iden2";
    //private static String URL_IDEN = "http://127.0.0.1:6080/api/v1/ai/watermeters/iden2";

    @Resource
    private Environment env;

    @Resource
    private TServerReadService tServerReadService;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private TAireadService tAireadService;

    public TServerReadModel postInParam(TAireadModel tAireadModel) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        //headers.add("Authorization", "Bearer" + getTocken().getAccess_token());

        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("pumpWellCode", tAireadModel.getDeviceSn());

        try {
            String inImg = StringUtils.isNotEmpty(tAireadModel.getBigJpgUrl()) ? tAireadModel.getBigJpgUrl() : tAireadModel.getSmallJpgUrl();

            String imagePath = convertSmallUrl(inImg);
            //imagePath = "E:/shangchuan/14.png";
            byte[] data = FileUtil.readBytesFile(imagePath);

            String image = Base64.getEncoder().encodeToString(data);
            map.add("image", image);

            HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(map, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(URL_IDEN, entity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                String body = response.getBody();
                //log.info("服务侧识别结果:" + body);
                ResultGeekerModel aiIdenMap = JSON.parseObject(body, new TypeReference<>() {
                });

                String json = aiIdenMap.getData().toString();
                log.info("服务识别结果:[" + tAireadModel.getDeviceSn() + "]" + json);
                AioOutModel outModel = JSON.parseObject(json, AioOutModel.class);
                TServerReadModel serverReadModel = new TServerReadModel();
                serverReadModel.setStationCode(tAireadModel.getStationCode());
                serverReadModel.setAireadId(tAireadModel.getAireadId());
                serverReadModel.setGoodFlag(outModel.getServerAiValueIsOk() + "");
                serverReadModel.setDeviceSn(tAireadModel.getDeviceSn());
                serverReadModel.setIdentValue(new BigDecimal(outModel.getAiValue()));
                serverReadModel.setJpgUrl(outModel.getOutImagePath());

                if (outModel.getDebugInfo() != null && outModel.getDebugInfo().length == 2) {
                    int[] arrSzsbz = new int[outModel.getDebugInfo()[0].length];
                    int[] arrSzsbgl = new int[outModel.getDebugInfo()[1].length];
                    System.arraycopy(outModel.getDebugInfo()[0], 0, arrSzsbz, 0, arrSzsbz.length);
                    System.arraycopy(outModel.getDebugInfo()[1], 0, arrSzsbgl, 0, arrSzsbgl.length);

                    //处理调试信息中的88数值(无实际意义)
                    if (tAireadModel.getDeviceType().equals("4")) {//LED表是888代表无实际意义
                        serverReadModel.setSzsbz(StringUtils.join(arrSzsbz, ',').replace("888", "-"));
                        serverReadModel.setSzsbgl(StringUtils.join(arrSzsbgl, ',').replace("888", "-"));
                    } else {
                        serverReadModel.setSzsbz(StringUtils.join(arrSzsbz, ',').replace("88", "-"));
                        serverReadModel.setSzsbgl(StringUtils.join(arrSzsbgl, ',').replace("88", "-"));
                    }

                }
                dealServerReadRecord(serverReadModel, tAireadModel);
                return serverReadModel;
            } else {

            }
        } catch (Exception ex) {

        }
        return null;
    }

    private void dealServerReadRecord(TServerReadModel tServerReadModel, TAireadModel tAireadModel) {
        if (tServerReadModel == null) return;
        tServerReadModel = tServerReadService.saveTServerRead(tServerReadModel);
        if (tAireadModel.getFunCode().equals("32")) {//如果没有MCU的识别值,则更新ResultValue为服务侧值
            if (tAireadModel.getIdentValue() == null && tAireadModel.getRawValue() == null) {
                tAireadModel.setResultValue(tServerReadModel.getIdentValue());
            }
            tAireadService.updateTAiread(tAireadModel);
        }
    }

    /**
     * 转换小图本地路径为Url
     *
     * @param url
     * @return
     */
    private String convertSmallUrl(String url) {
        if (url.contains("http")) {
            int index = url.indexOf("//");
            if (index > -1) {
                url = url.substring(index + 2);
                index = url.indexOf("/");
                url = url.substring(index);
                String tar = env.getProperty(ResourceTag.UploadPathTag.getTag());
                url = url.replaceAll(ResourcePath.Image.getPath(), tar);
                return url;
            }
        }
        return "";
    }
}
