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.book.book.dto.ProjectOrderSheetDTO;
import com.pcloud.book.book.dto.ProjectRelateVO;
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;
import java.util.stream.Collectors;

@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.stream().distinct().collect(Collectors.toList()));
        bookAdviserChannelIdMap.put("channelIds", channelIds.stream().distinct().collect(Collectors.toList()));
        bookAdviserChannelIdMap.put("bookIds", bookIds.stream().distinct().collect(Collectors.toList()));

        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<>();
    }

    @ParamLog("根据isbn获取erp书刊信息")
    public ProjectOrderSheetDTO getByErpNumber(String erpNumber) throws BizException {
        Map<String, String> querys = new HashMap<>();
        querys.put("erpNumber", erpNumber);
        try {
            HttpResponse response = HttpUtils.doGet(domain, "/erp/project4Third/getByErpNumber", "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.parseObject(jsonObject.getString("data"), ProjectOrderSheetDTO.class);
        } catch (Exception e){
            LOGGER.error("根据isbn获取erp书刊信息[project4Third.getByErpNumber]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_CONTENT_ERROR, "根据isbn获取erp书刊信息失败~!");
        }
    }

    @ParamLog("获取ERP单号")
    public List<String> getErpNumbers(Long bookId, Long channelId, Long adviserId) {
        Map<String, String> querys = new HashMap<>();
        querys.put("bookId", bookId.toString());
        querys.put("channelId", channelId.toString());
        querys.put("adviserId", adviserId.toString());
        try {
            HttpResponse response = HttpUtils.doGet(domain, "/erp/project4Third/getErpNumbers", "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.parseArray(jsonObject.getJSONArray("data").toJSONString(), String.class);
        } catch (Exception e){
            LOGGER.error("根据isbn获取erp书刊信息[project4Third.getByErpNumber]:" + e.getMessage(), e);
        }
        return CollUtil.toList();
    }

    @ParamLog("关联RAYS书刊")
    public Integer relateRaysBook(ProjectRelateVO vo) throws BizException {
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            HttpResponse response = HttpUtils.doPost(domain, "/erp/project4Third/relateRaysBook", "POST", headers, new HashMap<>(), JSONObject.toJSONString(vo));
            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("关联RAYS书刊[project4Third.relateRaysBook]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_CONTENT_ERROR, "关联RAYS书刊失败~!");
        }
    }
}
