package com.glxp.mipsdl.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONWriter;
import com.alibaba.fastjson.TypeReference;
import com.glxp.mipsdl.constant.ConstantType;
import com.glxp.mipsdl.dao.pzhzd.YyUcloudV31SetDao;
import com.glxp.mipsdl.entity.pzhzd.YyUcloudV31SetEntity;
import com.glxp.mipsdl.req.ucloud.*;
import com.glxp.mipsdl.res.ucloud.*;
import com.glxp.mipsdl.service.system.SysErpLogService;
import com.glxp.mipsdl.util.http.UHttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 请求片仔癀用友U8系统专用http工具类
 */
@Slf4j
@Service
public class UCloudHttpClient {

    @Resource
    private YyUcloudV31SetDao yyUcloudV31SetDao;
    @Resource
    private SysErpLogService erpLogService;

    /**
     * 用友U8的地址
     */
    private String u8Url;

    /**
     * 获取片仔癀用友U8接口请求头
     *
     * @return
     */
    public HttpHeaders getHeaders() {
        YyUcloudV31SetEntity setEntity = yyUcloudV31SetDao.findSetUp(null);
        this.u8Url = setEntity.getIpUrl();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=UTF-8");
        if (setEntity != null) {
            headers.add("system", setEntity.getSystemCode());
            headers.add("usercode", setEntity.getUserCode());
            headers.add("password", setEntity.getPasswd());
            headers.add("trantype", setEntity.getTransType());
        }
        return headers;
    }

    /**
     * 采购入库单查询
     *
     * @param uPurchaseinRequest
     * @return
     */
    public UBaseResponse purchaseinQuery(UPurchaseinRequest uPurchaseinRequest) {
        //请求开始时间
        Date date = new Date();

        RestTemplate restTemplate = new RestTemplate();
        String params = JSONObject.toJSONString(uPurchaseinRequest);
        HttpEntity<String> httpEntity = new HttpEntity<>(params, getHeaders());
        String url = u8Url + "/u8cloud/api/ic/purchasein/query";
        log.info(url + "\n" + params);
        String responseStr = restTemplate.postForObject(url, httpEntity, String.class);
        responseStr = UHttpUtils.formatResponse(responseStr);
        UBaseResponse<List<UPurchaseinQueryResponse>> response;

        //响应状态
        Integer status;
        try {
            response = JSONObject.parseObject(responseStr, new TypeReference<UBaseResponse<List<UPurchaseinQueryResponse>>>() {
            });
            status = ConstantType.LOG_STATUS_SUCCESS;
            erpLogService.addThirdErpLog(date, url, "purchaseinQuery", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
            return response;
        } catch (Exception e) {
            log.error("解析片仔癀采购入库单查询接口结果异常，返回结果：{}", responseStr);
            log.error("异常信息：{}", e);
            status = ConstantType.LOG_STATUS_ERROR;
            erpLogService.addThirdErpLog(date, url, "purchaseinQuery", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
        }
        return UHttpUtils.returnError();
    }

    /**
     * 销售出库单查询
     *
     * @param uSaleoutQueryRequest
     * @return
     */
    public UBaseResponse saleoutQuery(USaleoutQueryRequest uSaleoutQueryRequest) {
        //请求开始时间
        Date date = new Date();

        RestTemplate restTemplate = new RestTemplate();
        String params = JSONObject.toJSONString(uSaleoutQueryRequest);
        HttpEntity<String> httpEntity = new HttpEntity<>(params, getHeaders());
        String url = u8Url + "/u8cloud/api/ic/saleout/query";
        log.info(url + "\n" + params);
        String responseStr = restTemplate.postForObject(url, httpEntity, String.class);
        responseStr = UHttpUtils.formatResponse(responseStr);
        UBaseResponse<List<USaleoutQueryResponse>> response;

        //响应状态
        Integer status;
        try {
            response = JSONObject.parseObject(responseStr, new TypeReference<UBaseResponse<List<USaleoutQueryResponse>>>() {
            });
            status = ConstantType.LOG_STATUS_SUCCESS;
            erpLogService.addThirdErpLog(date, url, "saleoutQuery", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
            return response;
        } catch (Exception e) {
            log.error("解析片仔癀销售出库单查询接口结果异常，返回结果：{}", responseStr);
            log.error("异常信息：{}", e);
            status = ConstantType.LOG_STATUS_ERROR;
            erpLogService.addThirdErpLog(date, url, "saleoutQuery", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
        }
        return UHttpUtils.returnError();
    }

    /**
     * 采购入库单修改
     *
     * @param modifyPruchaseinRequest
     * @return
     */
    public UBaseResponse purchaseinModify(ModifyPruchaseinRequest modifyPruchaseinRequest) {
        //请求开始时间
        Date date = new Date();

        RestTemplate restTemplate = new RestTemplate();
        String params = JSONObject.toJSONString(modifyPruchaseinRequest);

        HttpEntity<String> httpEntity = new HttpEntity<>(params, getHeaders());
        String url = u8Url + "/u8cloud/api/ic/purchasein/update";
        log.info(url + "\n" + params);
        String responseStr = restTemplate.postForObject(url, httpEntity, String.class);
        UBaseResponse response = null;

        //响应状态
        Integer status;
        try {
            String body = JSONObject.toJSONString(responseStr);
            Object parse1 = JSON.parse(body);
            String s = parse1.toString();
            JSONObject jsonObject = JSON.parseObject(s);
            if (jsonObject.getString("status").equals("success")) {
                response = new UBaseResponse();
                response.setStatus("success");
            } else
                responseStr = UHttpUtils.formatResponse(responseStr);
            response = JSONObject.parseObject(responseStr, new TypeReference<UBaseResponse>() {
            });

            status = ConstantType.LOG_STATUS_SUCCESS;
            erpLogService.addThirdErpLog(date, url, "purchaseinModify", params, responseStr, System.currentTimeMillis() - date.getTime(), status);

        } catch (Exception e) {
            log.error("解析片仔癀采购入库单修改接口结果异常，返回结果：{}", responseStr);
            log.error("异常信息：{}", e);
            status = ConstantType.LOG_STATUS_ERROR;
            erpLogService.addThirdErpLog(date, url, "purchaseinModify", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
        }
        return response;
    }


    /**
     * 销售出库单修改
     *
     * @param modifyPruchaseinRequest
     * @return
     */
    public UBaseResponse saleModify(ModifyPruchaseinRequest modifyPruchaseinRequest) {
        //请求开始时间
        Date date = new Date();

        RestTemplate restTemplate = new RestTemplate();
        String params = JSONObject.toJSONString(modifyPruchaseinRequest);
        HttpEntity<String> httpEntity = new HttpEntity<>(params, getHeaders());
        String url = u8Url + "/u8cloud/api/ic/saleout/update";
        log.info(url + "\n" + params);

        String responseStr = restTemplate.postForObject(url, httpEntity, String.class);
        UBaseResponse response = null;

        //响应状态
        Integer status;
        try {
            String body = JSONObject.toJSONString(responseStr);
            Object parse1 = JSON.parse(body);
            String s = parse1.toString();
            JSONObject jsonObject = JSON.parseObject(s);
            if (jsonObject.getString("status").equals("success")) {
                response = new UBaseResponse();
                response.setStatus("success");
            } else
                responseStr = UHttpUtils.formatResponse(responseStr);
            response = JSONObject.parseObject(responseStr, new TypeReference<UBaseResponse>() {
            });

            status = ConstantType.LOG_STATUS_SUCCESS;
            erpLogService.addThirdErpLog(date, url, "saleModify", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
        } catch (Exception e) {
            log.error("解析片仔癀销售出库单修改接口结果异常，返回结果：{}", responseStr);
            log.error("异常信息：{}", e);
            status = ConstantType.LOG_STATUS_ERROR;
            erpLogService.addThirdErpLog(date, url, "saleModify", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
        }
        return response;
    }

    /**
     * 采购入库单签字
     *
     * @param purhaseinSignRequest
     * @return
     */
    public UBaseResponse purchaseinSign(UPurhaseinSignRequest purhaseinSignRequest) {
        //请求开始时间
        Date date = new Date();

        RestTemplate restTemplate = new RestTemplate();
        String params = JSONObject.toJSONString(purhaseinSignRequest);
        HttpEntity<String> httpEntity = new HttpEntity<>(params, getHeaders());
        String url = u8Url + "/u8cloud/api/ic/purchasein/sign";
        log.info(url + "\n" + params);

        String responseStr = restTemplate.postForObject(url, httpEntity, String.class);
        responseStr = UHttpUtils.formatResponse(responseStr);
        UBaseResponse response = null;

        //响应状态
        Integer status;
        try {
            JSONObject jsonObject = JSON.parseObject(responseStr);
            if (jsonObject.getString("status").equals("success")) {
                response = new UBaseResponse();
                response.setStatus("success");
            } else {
                response = JSONObject.parseObject(responseStr, new TypeReference<UBaseResponse>() {
                });
            }

            status = ConstantType.LOG_STATUS_SUCCESS;
            erpLogService.addThirdErpLog(date, url, "purchaseinSign", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
        } catch (Exception e) {
            log.error("解析片仔癀采购入库单签字接口结果异常，返回结果：{}", responseStr);
            log.error("异常信息：{}", e);
            status = ConstantType.LOG_STATUS_ERROR;
            erpLogService.addThirdErpLog(date, url, "purchaseinSign", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
        }
        log.info(responseStr);
        return response;
    }

    /**
     * 销售出库单签字
     *
     * @param saleoutSignRequest
     * @return
     */
    public UBaseResponse saleOutSign(USaleoutSignRequest saleoutSignRequest) {
        //请求开始时间
        Date date = new Date();

        RestTemplate restTemplate = new RestTemplate();
        String params = JSONObject.toJSONString(saleoutSignRequest);
        HttpEntity<String> httpEntity = new HttpEntity<>(params, getHeaders());
        String url = u8Url + "/u8cloud/api/ic/saleout/sign";
        log.info(url + "\n" + params);
        String responseStr = restTemplate.postForObject(url, httpEntity, String.class);

        responseStr = UHttpUtils.formatResponse(responseStr.trim());
        UBaseResponse response = null;

        //响应状态
        Integer status;
        try {
            JSONObject jsonObject = JSON.parseObject(responseStr);
            if (jsonObject.getString("status").equals("success")) {
                response = new UBaseResponse();
                response.setStatus("success");
            } else {
                response = JSONObject.parseObject(responseStr, UBaseResponse.class);
            }

            status = ConstantType.LOG_STATUS_SUCCESS;
            erpLogService.addThirdErpLog(date, url, "saleOutSign", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
        } catch (Exception e) {
            log.error("解析片销售出库单签字查询接口结果异常，返回结果：{}", responseStr);
            log.error("异常信息：{}", e);
            status = ConstantType.LOG_STATUS_ERROR;
            erpLogService.addThirdErpLog(date, url, "saleOutSign", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
        }
        return response;
    }

    /**
     * 现存量查询
     *
     * @param onhandQueryRequest
     * @return
     */
    public UBaseResponse onhandQuery(UOnhandQueryRequest onhandQueryRequest) {
        //请求开始时间
        Date date = new Date();

        RestTemplate restTemplate = new RestTemplate();
        String params = JSONObject.toJSONString(onhandQueryRequest);
        HttpEntity<String> httpEntity = new HttpEntity<>(params, getHeaders());
        String url = u8Url + "/u8cloud/api/ic/onhand/query";
        log.info("请求参数" + url + "\n" + params);
        String responseStr = restTemplate.postForObject(url, httpEntity, String.class);
        responseStr = UHttpUtils.formatResponse(responseStr);
        log.info("请求结果" + responseStr);
        UBaseResponse<List<UOnhandQueryResponse>> response;

        //响应状态
        Integer status;
        try {
            response = JSONObject.parseObject(responseStr, new TypeReference<UBaseResponse<List<UOnhandQueryResponse>>>() {
            });

            status = ConstantType.LOG_STATUS_SUCCESS;
            erpLogService.addThirdErpLog(date, url, "onhandQuery", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
            return response;
        } catch (Exception e) {
            log.error("解析片仔癀现存量查询接口结果异常，返回结果：{}", responseStr);
            log.error("异常信息：{}", e);
            status = ConstantType.LOG_STATUS_ERROR;
            erpLogService.addThirdErpLog(date, url, "onhandQuery", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
        }
        return UHttpUtils.returnError();
    }

    /**
     * 现存量查询
     *
     * @param onhandQueryRequest
     * @return
     */
    public UBaseResponse onhandQueryPost(UOnhandPostQueryRequest onhandQueryRequest) {
        //请求开始时间
        Date date = new Date();

        RestTemplate restTemplate = new RestTemplate();
        String params = JSONObject.toJSONString(onhandQueryRequest);
        HttpEntity<String> httpEntity = new HttpEntity<>(params, getHeaders());
        String url = u8Url + "/u8cloud/api/ic/onhand/query";
        log.info(url + "\n" + params);
        String responseStr = restTemplate.postForObject(url, httpEntity, String.class);
        responseStr = UHttpUtils.formatResponse(responseStr);
        UBaseResponse<List<UOnhandQueryResponse>> response;

        //响应状态
        Integer status;
        try {
            response = JSONObject.parseObject(responseStr, new TypeReference<UBaseResponse<List<UOnhandQueryResponse>>>() {
            });

            status = ConstantType.LOG_STATUS_SUCCESS;
            erpLogService.addThirdErpLog(date, url, "onhandQueryPost", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
            return response;
        } catch (Exception e) {
            log.error("解析片仔癀现存量查询接口结果异常，返回结果：{}", responseStr);
            log.error("异常信息：{}", e);
            status = ConstantType.LOG_STATUS_ERROR;
            erpLogService.addThirdErpLog(date, url, "onhandQueryPost", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
        }
        return UHttpUtils.returnError();
    }

    /**
     * 客商管理档案查询
     *
     * @param custmandocRequest
     * @return
     */
    public UBaseResponse custmandocQuery(UCustmandocRequest custmandocRequest) {
        //请求开始时间
        Date date = new Date();

        RestTemplate restTemplate = new RestTemplate();
        String params = JSONObject.toJSONString(custmandocRequest);
        HttpEntity<String> httpEntity = new HttpEntity<>(params, getHeaders());
        String url = u8Url + "/u8cloud/api/uapbd/custmandoc/query";
        log.info(url + "\n" + params);
        String responseStr = restTemplate.postForObject(url, httpEntity, String.class);

        responseStr = UHttpUtils.formatResponse(responseStr);
        UBaseResponse<List<UCustmandocResponse>> response;

        //响应状态
        Integer status;
        try {
            response = JSONObject.parseObject(responseStr, new TypeReference<UBaseResponse<List<UCustmandocResponse>>>() {
            });

            status = ConstantType.LOG_STATUS_SUCCESS;
            erpLogService.addThirdErpLog(date, url, "custmandocQuery", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
            return response;
        } catch (Exception e) {
            log.error("解析片仔癀客商管理档案查询接口结果异常，返回结果：{}", responseStr);
            log.error("异常信息：{}", e);
            status = ConstantType.LOG_STATUS_ERROR;
            erpLogService.addThirdErpLog(date, url, "custmandocQuery", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
        }
        return UHttpUtils.returnError();
    }

    /**
     * 存货管理档案查询
     *
     * @param uInvmandocRequest
     * @return
     */
    public UBaseResponse invmandocQuery(UInvmandocRequest uInvmandocRequest) {
        //请求开始时间
        Date date = new Date();

        RestTemplate restTemplate = new RestTemplate();
        String params = JSONObject.toJSONString(uInvmandocRequest);

        HttpEntity<String> httpEntity = new HttpEntity<>(params, getHeaders());
        String url = u8Url + "/u8cloud/api/uapbd/invmandoc/query";
        log.info(url + "\n" + params);
        String responseStr = restTemplate.postForObject(url, httpEntity, String.class);
        responseStr = UHttpUtils.formatResponse(responseStr);
        UBaseResponse<List<UInvmandocQueryResponse>> response;

        //响应状态
        Integer status;
        try {
            response = JSONObject.parseObject(responseStr, new TypeReference<UBaseResponse<List<UInvmandocQueryResponse>>>() {
            });

            status = ConstantType.LOG_STATUS_SUCCESS;
            erpLogService.addThirdErpLog(date, url, "invmandocQuery", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
            return response;
        } catch (Exception e) {
            log.error("解析片仔癀存货管理档案查询接口结果异常，返回结果：{}", responseStr);
            log.error("异常信息：{}", e);
            status = ConstantType.LOG_STATUS_ERROR;
            erpLogService.addThirdErpLog(date, url, "invmandocQuery", params, responseStr, System.currentTimeMillis() - date.getTime(), status);
        }
        return UHttpUtils.returnError();
    }


}
