package com.usoft.credit.rest.service.impl;

import com.google.protobuf.InvalidProtocolBufferException;
import com.usoft.credit.rest.api.protobuf.EnterpriseJsonResponse;
import com.usoft.credit.rest.api.protobuf.EnterpriseQueryRequest;
import com.usoft.credit.rest.api.protobuf.PersonJsonResponse;
import com.usoft.credit.rest.api.protobuf.PersonQueryRequest;
import com.usoft.credit.rest.api.query.entity.EnterpriseQuery;
import com.usoft.credit.rest.api.query.entity.PersonQuery;
import com.usoft.credit.rest.api.query.entity.ResponseHeader;
import com.usoft.credit.rest.api.result.entity.User;
import com.usoft.credit.rest.domain.EnterPriseJsonDomain;
import com.usoft.credit.rest.domain.LogDomain;
import com.usoft.credit.rest.domain.PersonJsonDomain;
import com.usoft.credit.rest.domain.UserDomain;
import com.usoft.credit.rest.domain.util.ResponseUtil;
import com.usoft.credit.util.ProtoBufUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author liuam
 * @since 2018/8/7 0007 下午 19:24
 */
@RestController
@RequestMapping("erpquery")
public class CreditQueryController {

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


    @Autowired
    private UserDomain userDomain;

    @Autowired
    private LogDomain logDomain;

    @Autowired
    private EnterPriseJsonDomain enterPriseJsonDomain;

    @Autowired
    private PersonJsonDomain personJsonDomain;

    /**
     * ERP对企业进行查询
     * @param data enterpriseQuery 查询条件
     * @param password user信息
     * @param enuu user信息
     * @param useruu user信息
     * @return
     */
    @RequestMapping(value = "/queryEn", method = RequestMethod.POST)
    public String queryEn(String data, String password, Integer enuu, Integer useruu) {
        // 将查询记录保存到数据库
        logDomain.saveEnterpriseLog();

        // 创建返回的 enterpriseJson
        EnterpriseJsonResponse.Builder builder = EnterpriseJsonResponse.newBuilder();

        // 创建查询的 enterpriseQuery ，转换异常则进行记录并返回
        EnterpriseQuery.Builder enterpriseQuery = null;
        try {
            enterpriseQuery = ProtoBufUtil.toProtoBuf(EnterpriseQuery.newBuilder(), data);
        } catch (InvalidProtocolBufferException e) {
            logger.warn("查询企业信息[CreditQueryController.queryEn]异常，enterpriseQuery 参数错误，参数：{}", data);
            ResponseHeader responseHeader = ResponseUtil.getResponseHeader(10005, "enterpriseQuery不正确");
            builder.setResponseHeader(responseHeader);
            return ProtoBufUtil.toJSONHasTryCatch(builder.build());
        }

        // TODO 使用拦截器校验？
        // 创建用来身份校验的 user
        if (password == null || useruu == null || enuu == null) {
            logger.warn("查询企业信息[CreditQueryController.queryEn]异常，user 参数错误，password：{}，enuu：{}，useruu：{}", password, enuu, useruu);
            ResponseHeader responseHeader = ResponseUtil.getResponseHeader(10004, "用户不正确");
            builder.setResponseHeader(responseHeader);
            return ProtoBufUtil.toJSONHasTryCatch(builder.build());
        }
        User.Builder userBuilder = User.newBuilder();
        userBuilder.setPassword(password);
        userBuilder.setEnuu(enuu);
        userBuilder.setUseruu(useruu);

        // 将 user 和 enterpriseQuery 封装进 request，传递给domain
        EnterpriseQueryRequest.Builder request = EnterpriseQueryRequest.newBuilder();
        request.setUser(userBuilder);
        request.setEnterpriseQuery(enterpriseQuery);

        if (!userDomain.verifyEnterprise(request.build())) {
            logger.warn("查询企业信息[CreditQueryController.queryEn]异常，user 不正确，参数：{}", ProtoBufUtil.toJSONHasTryCatch(request));
            ResponseHeader responseHeader = ResponseUtil.getResponseHeader(10004, "用户不正确");
            builder.setResponseHeader(responseHeader);
        } else {
            try {
                builder = enterPriseJsonDomain.queryEn(request.build());
                logger.info("查询企业信用信息[CreditQueryController.queryEn]正常，参数：{}", ProtoBufUtil.toJSONHasTryCatch(request));
            } catch (Exception e) {
                logger.error("查询企业信用信息[CreditQueryController.queryEn]异常，参数：{}，异常信息：{}", ProtoBufUtil.toJSONHasTryCatch(request), e);
                ResponseHeader responseHeader = ResponseUtil.getResponseHeader(10003, e.getMessage());
                builder.setResponseHeader(responseHeader);
            }
        }

        return ProtoBufUtil.toJSONHasTryCatch(builder.build());
    }

    /**
     * erp对个人进行查询
     */
    @RequestMapping(value = "/queryPe", method = RequestMethod.POST)
    public String queryPerson(String data, String password, Integer enuu, Integer useruu) {
        // 将查询记录保存到数据库
        logDomain.savePersonLog();

        // 创建返回的 enterpriseJson
        PersonJsonResponse.Builder builder = PersonJsonResponse.newBuilder();

        // 创建查询的 personQuery ，转换异常则进行记录并返回
        PersonQuery.Builder personQuery = null;
        try {
            personQuery = ProtoBufUtil.toProtoBuf(PersonQuery.newBuilder(), data);
        } catch (InvalidProtocolBufferException e) {
            logger.warn("查询企业信息[CreditQueryController.queryPerson]异常，personQuery 参数错误，参数：{}", data);
            ResponseHeader responseHeader = ResponseUtil.getResponseHeader(10005, "personQuery不正确");
            builder.setResponseHeader(responseHeader);
            return ProtoBufUtil.toJSONHasTryCatch(builder.build());
        }

        // 创建用来身份校验的 user
        if (password == null || useruu == null || enuu == null) {
            logger.warn("查询企业信息[CreditQueryController.queryPerson]异常，user 参数错误，password：{}，enuu：{}，useruu：{}", password, enuu, useruu);
            ResponseHeader responseHeader = ResponseUtil.getResponseHeader(10004, "用户不正确");
            builder.setResponseHeader(responseHeader);
            return ProtoBufUtil.toJSONHasTryCatch(builder.build());
        }
        User.Builder userBuilder = User.newBuilder();
        userBuilder.setPassword(password);
        userBuilder.setEnuu(enuu);
        userBuilder.setUseruu(useruu);

        // 将 user 和 personQuery 封装进 request，传递给domain
        PersonQueryRequest.Builder request = PersonQueryRequest.newBuilder();
        request.setUser(userBuilder);
        request.setPersonQuery(personQuery);

        if (!userDomain.verifyPerson(request.build())) {
            logger.warn("查询个人信用信息[CreditQueryController.queryPerson]异常，user 不正确，参数：{}", ProtoBufUtil.toJSONHasTryCatch(request));
            ResponseHeader responseHeader = ResponseUtil.getResponseHeader(10004, "用户不正确");
            builder.setResponseHeader(responseHeader);
        } else {
            try {
                builder = personJsonDomain.queryPerson(request.build());
                logger.info("查询个人信用信息[CreditQueryController.queryPerson]正常，参数：{}", ProtoBufUtil.toJSONHasTryCatch(request));
            } catch (Exception e) {
                logger.error("查询个人信用信息[CreditQueryController.queryPerson]异常，参数：{}，异常信息：{}", ProtoBufUtil.toJSONHasTryCatch(request), e);
                ResponseHeader responseHeader = ResponseUtil.getResponseHeader(10003, e.getMessage());
                builder.setResponseHeader(responseHeader);
            }
        }

        return ProtoBufUtil.toJSONHasTryCatch(builder.build());
    }

}
