package com.sv.service.common;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.sv.entity.Member;
import com.sv.entity.face.AddFaceResponse;
import com.sv.entity.face.AddMemberResponse;
import com.sv.entity.face.LoginResponse;
import com.sv.exception.FaceServiceException;
import com.ydd.framework.core.common.utils.JsonMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Service
public class FaceService {

    private final Logger logger = LoggerFactory.getLogger(FaceService.class);

    @Resource(name = "httpClient")
    private CloseableHttpClient httpClient;

    @Value("${face.url}")
    private String faceUrl;

    @Value("${face.account}")
    private String account;

    @Value("${face.pwd}")
    private String pwd;

    /**
     * face++登录
     */
    public void login() throws IOException {
        JsonObject param = new JsonObject();
        param.addProperty("username", account);
        param.addProperty("password", pwd);
        CloseableHttpResponse response = post(param, "auth/login");
        if (response.getStatusLine().getStatusCode() == 200) {
            LoginResponse loginResponse = JsonMapper.nonNullMapper().fromJson(response.getEntity().getContent(), LoginResponse.class);
            logger.info("登录成功" + ToStringBuilder.reflectionToString(loginResponse));

        } else {
            logger.error("face++登陆失败！");
            throw new FaceServiceException("登录失败");
        }
    }

    /**
     * 添加face用户
     *
     * @param faceId
     * @param member
     * @return
     */
    public Integer addSubject(Integer faceId, Member member) throws IOException {
        JsonObject param = new JsonObject();
        param.addProperty("gender", 1);
        if (!StringUtils.isEmpty(member.getNickname())) {
            param.addProperty("name", StringUtils.isEmpty(member.getNickname()) ? "" : member.getNickname());
        } else {
            param.addProperty("name", StringUtils.isEmpty(member.getMobile()) ? "" : member.getMobile());
        }
        param.addProperty("phone", StringUtils.isEmpty(member.getMobile()) ? "" : member.getMobile());
        param.addProperty("subject_type", 0);
        JsonArray faceIds = new JsonArray();
        faceIds.add(faceId);
        param.add("photo_ids", faceIds);
        CloseableHttpResponse response = post(param, "subject");
        if (response.getStatusLine().getStatusCode() == 200) {
            AddMemberResponse addMemberResponse = JsonMapper.nonNullMapper().fromJson(response.getEntity().getContent(), AddMemberResponse.class);
            if (addMemberResponse.getCode() == 0) {
                Integer subjectId = addMemberResponse.getData().getId();
                return subjectId;
            } else {
                throw new FaceServiceException(addMemberResponse.getDesc());
            }
        } else {
            logger.error("添加用户失败 code:" + response.getStatusLine().getStatusCode());
            throw new FaceServiceException("添加用户失败");
        }
    }

    public void show(String faceId,String money,String detail) {
        HttpPut req = new HttpPut("http://" + faceUrl + "/money/" + faceId);
        req.addHeader("Content-Type", "application/x-www-form-urlencoded");
        req.addHeader("user-agent", "Koala Admin");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("money", money));
        params.add(new BasicNameValuePair("detail", detail));
        try {
            req.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            CloseableHttpResponse response = httpClient.execute(req);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void show2() {
        HttpGet req = new HttpGet("http://" + faceUrl + "/money/7");
        req.addHeader("Content-Type", "application/x-www-form-urlencoded");
        req.addHeader("user-agent", "Koala Admin");

        try {
            CloseableHttpResponse response = httpClient.execute(req);

            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传识别头像
     *
     * @param face
     */
    public Integer uploadFace(InputStream face) throws IOException {
        HttpPost httpPost = new HttpPost("http://" + faceUrl + "/subject/photo");
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("photo", new InputStreamBody(face, System.currentTimeMillis() + ""));
        HttpEntity httpEntity = multipartEntityBuilder.build();
        httpPost.setEntity(httpEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            AddFaceResponse addFaceResponse = JsonMapper.nonNullMapper().fromJson(response.getEntity().getContent(), AddFaceResponse.class);
            if (addFaceResponse.getCode() == 0) {
                Integer faceId = addFaceResponse.getData().getId();
                return faceId;
            } else {
                logger.error("添加人脸失败 code:" + addFaceResponse.getCode() + " msg:" + addFaceResponse.getDesc());
                throw new FaceServiceException(addFaceResponse.getDesc());
            }
        } else {
            logger.error("上传头像失败 code:" + response.getStatusLine().getStatusCode());
            throw new FaceServiceException("上传头像失败");
        }
    }

    public void deleteSubject(Integer subjectId) throws IOException {
        HttpDelete httpDelete = new HttpDelete("http://" + faceUrl + "/subject/" + subjectId);
        CloseableHttpResponse response = httpClient.execute(httpDelete);
    }


    private CloseableHttpResponse post(JsonObject param, String uri) throws IOException {
        HttpPost httpPost = new HttpPost("http://" + faceUrl + "/" + uri);
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.addHeader("user-agent", "Koala Admin");
        if (param != null)
            httpPost.setEntity(new StringEntity(param.toString()));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        return response;
    }

}
