package com.mortals.xhx.module.hik.face.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.module.hik.AbstractHikService;
import com.mortals.xhx.module.hik.HikApiRest;
import com.mortals.xhx.module.hik.face.model.req.face.FaceListReq;
import com.mortals.xhx.module.hik.face.model.req.face.FaceReq;
import com.mortals.xhx.module.hik.face.model.req.face.ResRecognReq;
import com.mortals.xhx.module.hik.face.model.req.group.FaceGroupReq;
import com.mortals.xhx.module.hik.face.model.req.img.ImgReq;
import com.mortals.xhx.module.hik.face.model.req.resource.ResourceReq;
import com.mortals.xhx.module.hik.face.model.rsp.face.FaceDataInfo;
import com.mortals.xhx.module.hik.face.model.rsp.face.ResRecognDataInfo;
import com.mortals.xhx.module.hik.face.model.rsp.group.FaceGroupDataInfo;
import com.mortals.xhx.module.hik.face.model.rsp.resource.ResourceDataInfo;
import com.mortals.xhx.module.hik.face.service.IHikFaceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.hikvision.artemis.sdk.util.HttpUtil.wrapClient;

/**
 * 海康人员接口类
 *
 * @author: zxfei
 * @date: 2023/4/12 17:51
 */
@Service("hikFaceService")
@Slf4j
public class HikFaceServiceImpl extends AbstractHikService implements IHikFaceService {

    @Override
    public Rest<List<FaceDataInfo>> findFaceList(FaceListReq faceListReq) {
        ArtemisConfig config = getArtemisConfig();
        String getCamsApi = ARTEMIS_PATH + "/api/frs/v1/face";
        path.put(protocol, getCamsApi);
        try {
            String respJson = ArtemisHttpUtil.doPostStringArtemis(config, path, JSON.toJSONString(faceListReq), null, null, "application/json");
            HikApiRest<List<FaceDataInfo>> rest = JSON.parseObject(respJson, new TypeReference<HikApiRest<List<FaceDataInfo>>>() {
            });
            if ("0".equals(rest.getCode())) {
                return Rest.ok(rest.getData());
            } else {
                log.info("face single error resp=>", respJson);
                return Rest.fail(rest.getMsg());
            }
        } catch (Exception e) {
            log.error("face add error异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    @Override
    public Rest<FaceDataInfo> faceSingleAdd(FaceReq faceReq) {
        ArtemisConfig config = getArtemisConfig();
        String getCamsApi = ARTEMIS_PATH + "/api/frs/v1/face/single/addition";
        path.put(protocol, getCamsApi);
        try {
            //log.info("face single add req=>{}", JSON.toJSONString(faceReq));
            String respJson = ArtemisHttpUtil.doPostStringArtemis(config, path, JSON.toJSONString(faceReq), null, null, "application/json");
            log.info("face single add resp=>{}", respJson);
            HikApiRest<FaceDataInfo> rest = JSON.parseObject(respJson, new TypeReference<HikApiRest<FaceDataInfo>>() {
            });
            if ("0".equals(rest.getCode())) {
                return Rest.ok(rest.getData());
            } else {
                return Rest.fail(rest.getMsg());
            }
        } catch (Exception e) {
            log.error("face add error异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    @Override
    public Rest<Boolean> faceSingleUpdate(FaceReq faceReq) {
        ArtemisConfig config = getArtemisConfig();
        String getCamsApi = ARTEMIS_PATH + "/api/frs/v1/face/single/update";
        path.put(protocol, getCamsApi);
        try {
            String respJson = ArtemisHttpUtil.doPostStringArtemis(config, path, JSON.toJSONString(faceReq), null, null, "application/json");
            HikApiRest<Boolean> rest = JSON.parseObject(respJson, new TypeReference<HikApiRest<Boolean>>() {
            });
            if ("0".equals(rest.getCode())) {
                return Rest.ok(rest.getData());
            } else {
                log.info("face single error resp=>{}", respJson);
                return Rest.fail(rest.getMsg());
            }
        } catch (Exception e) {
            log.error("face add error异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    @Override
    public Rest<Boolean> faceSingleDel(FaceReq faceReq) {
        ArtemisConfig config = getArtemisConfig();
        String getCamsApi = ARTEMIS_PATH + "/api/frs/v1/face/deletion";
        path.put(protocol, getCamsApi);
        try {
            log.info("face single delete  req=>{}", JSON.toJSONString(faceReq));
            String respJson = ArtemisHttpUtil.doPostStringArtemis(config, path, JSON.toJSONString(faceReq), null, null, "application/json");
            HikApiRest<Boolean> rest = JSON.parseObject(respJson, new TypeReference<HikApiRest<Boolean>>() {
            });
            if ("0".equals(rest.getCode())) {
                return Rest.ok(rest.getData());
            } else {
                log.info("face single delete error resp=>{}", respJson);
                return Rest.fail(rest.getMsg());
            }
        } catch (Exception e) {
            log.error("face add error异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    @Override
    public Rest<List<FaceGroupDataInfo>> findFaceGroupList(FaceGroupReq faceGroupReq) {
        ArtemisConfig config = getArtemisConfig();
        String getCamsApi = ARTEMIS_PATH + "/api/frs/v1/group";
        path.put(protocol, getCamsApi);
        try {
            String respJson = ArtemisHttpUtil.doPostStringArtemis(config, path, JSON.toJSONString(faceGroupReq), null, null, "application/json");
            HikApiRest<List<FaceGroupDataInfo>> rest = JSON.parseObject(respJson, new TypeReference<HikApiRest<List<FaceGroupDataInfo>>>() {
            });
            if ("0".equals(rest.getCode())) {
                return Rest.ok(rest.getData());
            } else {
                log.info("face group list error resp=>{}", respJson);
                return Rest.fail(rest.getMsg());
            }
        } catch (Exception e) {
            log.error("face group list error异常", e);
            return Rest.fail(e.getMessage());
        }
    }


    @Override
    public Rest<FaceGroupDataInfo> faceGroupSingleAdd(FaceGroupReq faceGroupReq) {
        ArtemisConfig config = getArtemisConfig();
        String getCamsApi = ARTEMIS_PATH + "/api/frs/v1/face/group/single/addition";
        path.put(protocol, getCamsApi);
        try {
            log.info("face single req=>{}", JSON.toJSONString(faceGroupReq));
            String respJson = ArtemisHttpUtil.doPostStringArtemis(config, path, JSON.toJSONString(faceGroupReq), null, null, "application/json");
            log.info("face single resp=>{}", respJson);
            HikApiRest<FaceGroupDataInfo> rest = JSON.parseObject(respJson, new TypeReference<HikApiRest<FaceGroupDataInfo>>() {
            });
            if ("0".equals(rest.getCode())) {
                return Rest.ok(rest.getData());
            } else {
                return Rest.fail(rest.getMsg());
            }
        } catch (Exception e) {
            log.error("face add error异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    @Override
    public Rest<Boolean> faceGroupSingleDel(FaceGroupReq faceGroupReq) {
        ArtemisConfig config = getArtemisConfig();
        String getCamsApi = ARTEMIS_PATH + "/api/frs/v1/face/single/update";
        path.put(protocol, getCamsApi);
        try {
            String respJson = ArtemisHttpUtil.doPostStringArtemis(config, path, JSON.toJSONString(faceGroupReq), null, null, "application/json");
            HikApiRest<Boolean> rest = JSON.parseObject(respJson, new TypeReference<HikApiRest<Boolean>>() {
            });
            if ("0".equals(rest.getCode())) {
                return Rest.ok(rest.getData());
            } else {
                log.info("face single error resp=>{}", respJson);
                return Rest.fail(rest.getMsg());
            }
        } catch (Exception e) {
            log.error("face add error异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    /**
     * 识别计划需要人脸资源
     *
     * @param recognReq
     * @return
     */
    @Override
    public Rest<List<ResRecognDataInfo>> findResRecognList(ResRecognReq recognReq) {
        ArtemisConfig config = getArtemisConfig();
        String getCamsApi = ARTEMIS_PATH + "/api/frs/v1/resource/recognition";
        path.put(protocol, getCamsApi);
        try {
            String respJson = ArtemisHttpUtil.doPostStringArtemis(config, path, JSON.toJSONString(recognReq), null, null, "application/json");
            HikApiRest<List<ResRecognDataInfo>> rest = JSON.parseObject(respJson, new TypeReference<HikApiRest<List<ResRecognDataInfo>>>() {
            });
            if ("0".equals(rest.getCode())) {
                return Rest.ok(rest.getData());
            } else {
                log.info("face res list error resp=>{}", respJson);
                return Rest.fail(rest.getMsg());
            }
        } catch (Exception e) {
            log.error("face res list error异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    @Override
    public Rest<String> downloadPicture(ImgReq imgReq) {
        ArtemisConfig config = getArtemisConfig();
        String getCamsApi = ARTEMIS_PATH + "/api/frs/v1/application/picture";
        path.put(protocol, getCamsApi);
        try {
            // log.info("download img req=>{}", JSON.toJSONString(imgReq));
            String respJson = ArtemisHttpUtil.doPostStringArtemis(config, path, JSON.toJSONString(imgReq), null, null, "application/json");
            //log.info("download img resp=>{}", respJson);
            HikApiRest<String> rest = JSON.parseObject(respJson, new TypeReference<HikApiRest<String>>() {
            });
            if ("0".equals(rest.getCode())) {
                return Rest.ok(rest.getMsg(), rest.getData());
            } else {
                return Rest.fail(rest.getMsg());
            }
        } catch (Exception e) {
            log.error("img download error异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    @Override
    public Rest<List<ResourceDataInfo>> getResourceRecognition(ResourceReq recognReq) {
        ArtemisConfig config = getArtemisConfig();
        String getCamsApi = ARTEMIS_PATH + "/api/frs/v1/resource/recognition";
        path.put(protocol, getCamsApi);
        try {
            String respJson = ArtemisHttpUtil.doPostStringArtemis(config, path, JSON.toJSONString(recognReq), null, null, "application/json");
            HikApiRest<List<ResourceDataInfo>> rest = JSON.parseObject(respJson, new TypeReference<HikApiRest<List<ResourceDataInfo>>>() {
            });
            if ("0".equals(rest.getCode())) {
                return Rest.ok(rest.getData());
            } else {
                log.info("resource recognition list error resp=>{}", respJson);
                return Rest.fail(rest.getMsg());
            }
        } catch (Exception e) {
            log.error("resource recognition", e);
            return Rest.fail(e.getMessage());
        }
    }

    //下载图片
    @Override
    public InputStream callPostImgs(ImgReq imgReq) throws Exception {
        ArtemisConfig config = getArtemisConfig();
        ///api/resource/v1/person/picture
        String getSecurityApi = ARTEMIS_PATH + "/api/resource/v1/person/picture";
        path.put(protocol, getSecurityApi);
        //ArtemisHttpUtil.doPostStringImgArtemis(config, path, JSON.toJSONString(recognReq), null, null, "application/json");
        Map<String, String> query = new HashMap<String, String>(2) {  //get请求的head参数
            {
                put("domainId", "0");
            }
        };
        //参数根据接口实际情况设置
        HttpResponse result = ArtemisHttpUtil.doPostStringImgArtemis(config, path, JSON.toJSONString(imgReq), query, null, "application/json", null);
        HttpResponse resp = result;
        if (302 == resp.getStatusLine().getStatusCode()) {

            Header header = resp.getFirstHeader("location");
            String newUrl = header.getValue();
            //本地测试
           // String replace = StrUtil.replace(newUrl, "https://10.12.177.245:6114", "http://8.136.255.30:8002");
           // HttpGet httpget = new HttpGet(replace);
            HttpGet httpget = new HttpGet(newUrl);
            HttpClient httpClient = wrapClient(httpget.getURI().getScheme() + "://" + httpget.getURI().getHost());
            HttpResponse execute = httpClient.execute(httpget);
            HttpEntity entity = execute.getEntity();
            InputStream in = entity.getContent();
            return in;

        } else {
            System.out.println("下载出错");
            return null;
        }


    }
}
