package com.pcloud.book.consumer.erp;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.book.dto.CreateBookResultVO;
import com.pcloud.book.book.dto.ERPPublishNumDTO;
import com.pcloud.book.book.dto.ErpBookApprovalDTO;
import com.pcloud.book.book.dto.ErpBookInfoDTO;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.NumberUtil;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.readercenter.common.utils.HttpUtils;
import org.apache.http.HttpResponse;
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.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository("erpConsr")
public class ErpConsr {
	/**
	 * logger
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(ErpConsr.class);

    @Value("${erp.domain}")
    private String domain;

	@ParamLog("根据书名获取等级")
	public Integer getBookServiceLevel(String bookName) throws BizException {
        Map<String, String> querys = new HashMap<>();
        querys.put("bookName", bookName);
        try {
            HttpResponse response = HttpUtils.doGet(domain, "/erp/project4Third/getBookServiceLevel", "GET", new HashMap<>(), querys);
            String entityString = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(entityString);
            if(jsonObject.getInteger("errCode") != 0){
                throw new BizException(jsonObject.getString("message"));
            }
            return jsonObject.getInteger("data");
        } catch (Exception e){
            LOGGER.error("获取资源基本信息[resourceService.mapByPass]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_CONTENT_ERROR, "获取资源基本信息失败~!");
        }
	}

    @ParamLog("批量获取项目名称")
    public Map<Long, String> getBookNames(List<Long> bookIds) throws BizException {
        if(ListUtils.isEmpty(bookIds)){
            return new HashMap<>();
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        try {
            HttpResponse response = HttpUtils.doPost(domain, "/erp/project4Third/getBookNames", "POST", headers, new HashMap<>(), JSONObject.toJSONString(bookIds));
            String entityString = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(entityString);
            if(jsonObject.getInteger("errCode") != 0){
                throw new BizException(jsonObject.getString("message"));
            }
            return JSONObject.parseObject(jsonObject.getString("data"), new TypeReference<Map<Long, String>>(){});
        } catch (Exception e){
            LOGGER.error("批量获取项目名称[projectService.getBookNames]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_CONTENT_ERROR, "批量获取项目名称~!");
        }
    }

    @ParamLog("通过书名获取ERP端的bookId")
    public List<Long> getIdByBookName(String bookName) throws BizException {
        if(StringUtil.isEmpty(bookName)){
            return null;
        }
        Map<String, String> querys = new HashMap<>();
        querys.put("bookName", bookName);
        try {
            HttpResponse response = HttpUtils.doGet(domain, "/erp/project4Third/getIdByBookName", "GET", new HashMap<>(), querys);
            String entityString = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(entityString);
            if(jsonObject.getInteger("errCode") != 0){
                throw new BizException(jsonObject.getString("message"));
            }
            return JSONArray.parseArray(jsonObject.getJSONArray("data").toJSONString(), Long.class);
        } catch (Exception e){
            LOGGER.error("通过书名获取ERP端的bookId[projectService.getIdByBookName]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_CONTENT_ERROR, "通过书名获取ERP端的bookId错误");
        }
    }

    @ParamLog("通过书名获取ERP端的bookId【模糊匹配】")
    public List<Long> getIdsByBookName(String bookName) throws BizException {
        if(StringUtil.isEmpty(bookName)){
            return null;
        }
        Map<String, String> querys = new HashMap<>();
        querys.put("bookName", bookName);
        try {
            HttpResponse response = HttpUtils.doGet(domain, "/erp/project4Third/getIdsByBookName", "GET", new HashMap<>(), querys);
            String entityString = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(entityString);
            if(jsonObject.getInteger("errCode") != 0){
                throw new BizException(jsonObject.getString("message"));
            }
            return JSONArray.parseArray(jsonObject.getJSONArray("data").toJSONString(), Long.class);
        } catch (Exception e){
            LOGGER.error("通过书名获取ERP端的bookId[projectService.getIdByBookName]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_CONTENT_ERROR, "通过书名获取ERP端的bookId错误");
        }
    }

    @ParamLog("通过项目id获取bookId")
    public Long getProjectIdByBookId(Long bookId,Long adviserId,Long channelId){
        if(!NumberUtil.isNumber(bookId)){
            return null;
        }
        Map<String, String> querys = new HashMap<>();
        querys.put("bookId", bookId.toString());
        if(NumberUtil.isNumber(adviserId)){
            querys.put("adviserId", adviserId.toString());
        }
        if(NumberUtil.isNumber(channelId)){
            querys.put("channelId", channelId.toString());
        }

        try {
            HttpResponse response = HttpUtils.doGet(domain, "/erp/project4Third/getProjectIdByBookId", "GET", new HashMap<>(), querys);
            String entityString = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(entityString);
            if(jsonObject.getInteger("errCode") != 0){
                throw new BizException(jsonObject.getString("message"));
            }
            return jsonObject.getLong("data");
        } catch (Exception e){
            LOGGER.error("通过项目id获取bookId[projectService.getBookIdByProjectId]:" + e.getMessage(), e);
//            throw new BookBizException(BookBizException.INVOKE_CONTENT_ERROR, "通过项目id获取bookId 错误");
            return null;
        }
    }

    @ParamLog("创建书刊之后同步去更新erp信息")
    public void batchUpdateRelateInfo(List<CreateBookResultVO> createBookResultVOS){
        if(ListUtils.isEmpty(createBookResultVOS)){
            return ;
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        try {
            HttpResponse response = HttpUtils.doPost(domain, "/erp/project/batchUpdateRelateInfo", "POST", headers, new HashMap<>(), JSONObject.toJSONString(createBookResultVOS));
            String entityString = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(entityString);
            if(jsonObject.getInteger("errCode") != 0){
                throw new BizException(jsonObject.getString("message"));
            }
        } catch (Exception e){
            LOGGER.error("创建书刊之后同步去更新erp信息[projectService.batchUpdateRelateInfo]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_CONTENT_ERROR, "创建书刊之后同步去更新erp信息~!");
        }
    }

    @ParamLog("获取图书印册量")
    public List<ERPPublishNumDTO> getBookExpectPublishNum(List<ERPPublishNumDTO> dtos) {
        if (CollUtil.isEmpty(dtos)) {
            return new ArrayList<>();
        }

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        try {
            HttpResponse response = HttpUtils.doPost(domain, "/erp/project4Third/getBookExpectPublishNum", "POST", headers, new HashMap<>(), JSONObject.toJSONString(dtos));
            String entityString = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(entityString);
            if (jsonObject.getInteger("errCode") != 0) {
                throw new BizException(jsonObject.getString("message"));
            }
            return JSONObject.parseArray(jsonObject.getJSONArray("data").toJSONString(), ERPPublishNumDTO.class);
        } catch (Exception e) {
            LOGGER.error("获取图书印册量失败 [projectService.getBookExpectPublishNum]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_CONTENT_ERROR, "获取图书印册量失败!");
        }
    }

    @ParamLog("模糊查询图书信息")
    public List<ErpBookInfoDTO> searchBookInfo(String name, List<Long> advisers, Date startTime, Date endTime) {
        if (CollUtil.isEmpty(advisers)) {
            return new ArrayList<>();
        }

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        params.put("advisers", advisers);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        try {
            HttpResponse response = HttpUtils.doPost(domain, "/erp/project4Third/searchBookInfo", "GET", headers, new HashMap<>(), JSONObject.toJSONString(params));
            String entityString = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(entityString);
            if (jsonObject.getInteger("errCode") != 0) {
                throw new BizException(jsonObject.getString("message"));
            }
            return JSONObject.parseArray(jsonObject.getJSONArray("data").toJSONString(), ErpBookInfoDTO.class);
        } catch (Exception e) {
            LOGGER.error("模糊查询图书信息 [projectService.searchBookInfo]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_CONTENT_ERROR, "模糊查询图书信息失败!");
        }
    }


    @ParamLog("模糊查询erp图书ID")
    public List<ErpBookInfoDTO> searchRaysBookId(List<ErpBookInfoDTO> erpBookInfoDTOS) {
        if (CollUtil.isEmpty(erpBookInfoDTOS)) {
            return new ArrayList<>();
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        try {
            HttpResponse response = HttpUtils.doPost(domain, "/erp/project4Third/searchRaysBookId", "GET", headers, new HashMap<>(), JSONObject.toJSONString(erpBookInfoDTOS));
            String entityString = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(entityString);
            if (jsonObject.getInteger("errCode") != 0) {
                throw new BizException(jsonObject.getString("message"));
            }
            return JSONObject.parseArray(jsonObject.getJSONArray("data").toJSONString(), ErpBookInfoDTO.class);
        } catch (Exception e) {
            LOGGER.error("模糊查询图书信息 [projectService.searchBookInfo]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_CONTENT_ERROR, "模糊查询erp图书ID失败!");
        }
    }

    @ParamLog("查询erp图书是否立项")
    public Map<String, ErpBookApprovalDTO> getIsApproval(List<Long> adviserIds, List<Long> channelIds, List<Long> bookIds) {
        if (ListUtils.isEmpty(adviserIds) || ListUtils.isEmpty(channelIds) || ListUtils.isEmpty(bookIds)){
            return new HashMap<>();
        }
        adviserIds.remove(0L);
        channelIds.remove(0L);
        bookIds.remove(0L);
        Map<String, List<Long>> bookAdviserChannelIdMap = new HashMap<>();
        bookAdviserChannelIdMap.put("adviserIds", adviserIds);
        bookAdviserChannelIdMap.put("channelIds", channelIds);
        bookAdviserChannelIdMap.put("bookIds", bookIds);
        Map<String, ErpBookApprovalDTO> resultMap = null;

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        try {
            HttpResponse response = HttpUtils.doPost(domain, "/erp/project4Third/getIsApproval", "POST", headers, new HashMap<>(), JSONObject.toJSONString(bookAdviserChannelIdMap));
            String entityString = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(entityString);
            if (jsonObject.getInteger("errCode") != 0) {
                LOGGER.error("查询erp图书是否立项失败 [erpConsr.getIsApproval]:" + jsonObject.getString("message"));
            }
            return JSONObject.parseObject(jsonObject.getString("data"), new TypeReference<Map<String, ErpBookApprovalDTO>>(){});
        } catch (Exception e) {
            LOGGER.error("查询erp图书是否立项失败 [erpConsr.getIsApproval]:" + e.getMessage(), e);
        }
        return new HashMap<>();
    }
}
