package com.gic.haoban.manage.service.service.contact.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.enums.PlatformChannelEnum;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.manage.api.dto.contact.ContactOrderGoodsInfoDTO;
import com.gic.haoban.manage.api.dto.contact.ContactOrderDetailDTO;
import com.gic.haoban.manage.api.qdto.contact.ContactOrderSearchQDTO;
import com.gic.haoban.manage.service.dao.mapper.contact.TabContactOrderMapper;
import com.gic.haoban.manage.service.entity.contact.TabContactLog;
import com.gic.haoban.manage.service.entity.contact.TabContactOrder;
import com.gic.haoban.manage.service.service.ESMemberInfoService;
import com.gic.haoban.manage.service.service.contact.ContactLogService;
import com.gic.haoban.manage.service.service.contact.ContactOrderService;
import com.gic.member.api.dto.es.MemberDataDTO;
import com.gic.member.tag.api.dto.MemberTagGroupDetailDTO;
import com.gic.member.tag.api.dto.MemberTagGroupSimpleDTO;
import com.gic.member.tag.api.service.MemberTagGroupApiService;
import com.gic.order.api.dto.resp.OrderInfoResp;
import com.gic.order.api.dto.resp.OrderItemResp;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service("contactOrderService")
public class ContactOrderServiceImpl implements ContactOrderService {

    private static final Logger logger = LogManager.getLogger(ContactOrderService.class);

    @Autowired
    private TabContactOrderMapper contactOrderMapper;
    @Autowired
    private ContactLogService contactLogService;
    @Autowired
    private ESMemberInfoService esMemberInfoService;
    @Autowired
    private MemberTagGroupApiService memberTagGroupApiService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private ClerkService clerkService;

    @Override
    public boolean saveContactOrder(OrderInfoResp orderInfoResp) {
        Integer orderType = orderInfoResp.getOrderType();
        PlatformChannelEnum platformChannelEnum = PlatformChannelEnum.getEnumByOldOrderType(orderType);
        if (platformChannelEnum == null) {
            return false;
        }
        String orderId = orderInfoResp.getOrderId();
        TabContactOrder oldContactOrder = contactOrderMapper.queryByOrderId(orderId);
        if (oldContactOrder != null) {
            logger.info("订单已处理,订单id:{}", orderId);
            return false;
        }
        if (orderInfoResp.getOrderStatus() == null || orderInfoResp.getOrderStatus() != 1) {
            logger.info("订单不是销售单");
            return false;
        }
        long noGiveCount = orderInfoResp.getOrderItems().stream().filter(x -> !Objects.equals(x.getProType(), 2)).count();
        if (noGiveCount == 0) {
            logger.info("都是赠品订单:{}", orderId);
            return false;
        }
        String enterpriseId = orderInfoResp.getEnterpriseId();
        String memberId = orderInfoResp.getMemberId();
        logger.info("建联处理订单:{},memberId:{}", orderId,memberId);
        Date receiptsDate = orderInfoResp.getReceiptsDate();
        Date contactBeginTime = null;
        String channelCode = platformChannelEnum.getChannelCode();
        // 1 线上; 2 线下
        Integer channelType = null;
        if (Objects.equals(PlatformChannelEnum.C_POS.getChannelCode(), channelCode)) {
            channelType = 2;
            contactBeginTime = DateUtil.offsetDay(receiptsDate, -7);
        }else {
            channelType = 1;
            contactBeginTime = DateUtil.offsetDay(receiptsDate, -1);
        }

        Map<Integer, TabContactLog> contactMap = contactLogService.getLastByTime(memberId, null, contactBeginTime, receiptsDate);
        if (contactMap == null || contactMap.isEmpty()) {
            return false;
        }
        for (Map.Entry<Integer, TabContactLog> entry : contactMap.entrySet()) {
            Integer key = entry.getKey();
            TabContactLog lastContactLog = entry.getValue();
            if (lastContactLog == null) {
                continue;
            }
            logger.info("建联转化订单建联信息:{}", JSON.toJSONString(lastContactLog));
            TabContactOrder contactOrder = new TabContactOrder();
            contactOrder.setOrderId(orderId);
            contactOrder.setMemberId(memberId);
            contactOrder.setOrderNumber(orderInfoResp.getOrderNo());
            Double paidAmount = orderInfoResp.getPayAmount();
            if (Objects.equals(PlatformChannelEnum.C_WECHAT_MINI.getChannelCode(), channelCode)) {
                paidAmount = paidAmount + (Objects.isNull(orderInfoResp.getDeliveryPaymentAmount()) ? 0.0 : orderInfoResp.getDeliveryPaymentAmount());
            }
            contactOrder.setPaidAmount(paidAmount);
            contactOrder.setProductCount(orderInfoResp.getGoodsCount());
            contactOrder.setPayTime(orderInfoResp.getReceiptsDate());
            contactOrder.setReceiptsDate(orderInfoResp.getReceiptsDate());
            List<OrderItemResp> orderItems = orderInfoResp.getOrderItems();
            if (CollectionUtils.isNotEmpty(orderItems)) {
                List<ContactOrderGoodsInfoDTO> goodsInfoDTOS = JSONObject.parseArray(JSON.toJSONString(orderItems), ContactOrderGoodsInfoDTO.class);
                contactOrder.setGoodsInfo(JSON.toJSONString(goodsInfoDTOS));
            }
            contactOrder.setChannelCode(channelCode);
            contactOrder.setChannelType(channelType);
            contactOrder.setClerkId(lastContactLog.getClerkId());
            contactOrder.setClerkCode(lastContactLog.getClerkCode());
            contactOrder.setClerkName(lastContactLog.getClerkName());
            contactOrder.setStoreId(lastContactLog.getStoreId());
            contactOrder.setContactLogId(lastContactLog.getLogId());
            contactOrder.setContactTime(lastContactLog.getContactTime());
            contactOrder.setPotentialTime(lastContactLog.getPotentialTime());
            contactOrder.setSourceType(lastContactLog.getSourceType());
            contactOrder.setBizType(lastContactLog.getBizType());
            contactOrder.setEnterpriseId(lastContactLog.getEnterpriseId());

            JSONObject jsonObject = esMemberInfoService.queryDataSingle(enterpriseId, memberId, "potentialScore");
            if (jsonObject != null && jsonObject.getInteger("potentialScore") != null) {
                contactOrder.setPotentialScore(jsonObject.getInteger("potentialScore"));
            }
            String groupInfo = convertGroupInfo(enterpriseId, memberId);
            contactOrder.setGroupInfo(groupInfo);
            contactOrderMapper.insert(contactOrder);
        }
        return true;
    }

    private String convertGroupInfo(String enterpriseId, String memberId) {
        JSONObject jo = new JSONObject();
        try {
            MemberTagGroupDetailDTO memberTagGroupDetail = memberTagGroupApiService.getMemberTagGroupDetail(enterpriseId, memberId, "1");
            if (memberTagGroupDetail == null) {
                return jo.toJSONString();
            }
            MemberTagGroupSimpleDTO allChannelMemberGradeGroup = memberTagGroupDetail.getAllChannelMemberGradeGroup();
            if (allChannelMemberGradeGroup != null) {
                jo.put("allChannelMemberGradeGroup", allChannelMemberGradeGroup.getGroupName());
            }
            MemberTagGroupSimpleDTO memberGradeGroup = memberTagGroupDetail.getMemberGradeGroup();
            if (memberGradeGroup != null) {
                jo.put("memberGradeGroup", memberGradeGroup.getGroupName());
            }
        } catch (Exception e) {
            logger.info("获取金字塔分层信息异常",e);
        }
        return jo.toJSONString();
    }

    @Override
    public Page<ContactOrderDetailDTO> pageContactOrder(String enterpriseId, ContactOrderSearchQDTO searchQDTO, BasePageInfo pageInfo) {
        PageHelper.startPage(pageInfo);
        List<TabContactOrder> list = contactOrderMapper.queryContactOrder(enterpriseId, searchQDTO);
        Page<ContactOrderDetailDTO> page = PageHelperUtils.changePageHelperToCurrentPage(list, ContactOrderDetailDTO.class);
        List<ContactOrderDetailDTO> pageList = convertExtInfo(enterpriseId,list);
        page.setResult(pageList);
        return page;
    }

    private List<ContactOrderDetailDTO> convertExtInfo(String enterpriseId, List<TabContactOrder> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        Set<String> memberIdSet = new HashSet<>();
        Map<String, ClerkDTO> clerkIdMap = new HashMap<>();
        Map<String, StoreDTO> storeIdMap = new HashMap<>();
        Map<String, MemberDataDTO> memberMap = new HashMap<>();
        Set<String> storeIdSet = new HashSet<>();
        Set<String> clerkIdSet = new HashSet<>();
        for (TabContactOrder contactOrder : list) {
            String memberId = contactOrder.getMemberId();
            String storeId = contactOrder.getStoreId();
            if (StringUtils.isNotBlank(memberId)) {
                memberIdSet.add(memberId);
            }
            storeIdSet.add(storeId);
        }
        // 组装商品信息
        if (CollectionUtils.isNotEmpty(memberIdSet)) {
            List<MemberDataDTO> memberList = esMemberInfoService.queryDataBatch(enterpriseId, Lists.newArrayList(memberIdSet), "memberId,name,cardNo,phoneNumber,nickName,photoUrl,mainClerkId,mainStoreId");
            for (MemberDataDTO memberDataDTO : memberList) {
                memberMap.put(memberDataDTO.getMemberId(), memberDataDTO);
                String mainClerkId = memberDataDTO.getMainClerkId();
                String mainStoreId = memberDataDTO.getMainStoreId();
                if (StringUtils.isNotBlank(mainClerkId)) {
                    clerkIdSet.add(mainClerkId);
                }
                if (StringUtils.isNotBlank(mainStoreId)) {
                    storeIdSet.add(mainStoreId);
                }
            }
        }
        // 构建门店map
        if (CollectionUtils.isNotEmpty(storeIdSet)) {
            List<StoreDTO> stores = storeService.getStores(storeIdSet.toArray(new String[0]));
            if (CollectionUtils.isNotEmpty(stores)) {
                storeIdMap = stores.stream().collect(Collectors.toMap(StoreDTO::getStoreId, x -> x, (e, x) -> e));
            }
        }
        // 构建导购map
        if (CollectionUtils.isNotEmpty(clerkIdSet)) {
            List<ClerkDTO> clerks = clerkService.getClerkByClerkIds(clerkIdSet);
            if (CollectionUtils.isNotEmpty(clerks)) {
                clerkIdMap = clerks.stream().collect(Collectors.toMap(ClerkDTO::getClerkId, x -> x, (e, x) -> e));
            }
        }
        List<ContactOrderDetailDTO> dtoList = new ArrayList<>();
        for (TabContactOrder contactOrder : list) {
            ContactOrderDetailDTO contactOrderDTO = EntityUtil.changeEntityNew(ContactOrderDetailDTO.class, contactOrder);
            PlatformChannelEnum enumByChannelCode = PlatformChannelEnum.getEnumByChannelCode(contactOrder.getChannelCode());
            contactOrderDTO.setOrderType(enumByChannelCode == null ? null : enumByChannelCode.getOrderTypeOld());
            String goodsInfo = contactOrder.getGoodsInfo();
            if (StringUtils.isNotBlank(goodsInfo)) {
                contactOrderDTO.setGoodsInfoList(JSONArray.parseArray(goodsInfo, ContactOrderGoodsInfoDTO.class));
            }
            String memberId = contactOrder.getMemberId();
            MemberDataDTO memberDataDTO = memberMap.get(memberId);
            if (memberDataDTO != null) {
                contactOrderDTO.setMemberName(memberDataDTO.getName());
                contactOrderDTO.setMemberNick(memberDataDTO.getNickName());
                contactOrderDTO.setMemberMobile(memberDataDTO.getPhoneNumber());
                contactOrderDTO.setMemberCard(memberDataDTO.getCardNo());
                contactOrderDTO.setMemberImage(memberDataDTO.getPhotoUrl());
                if (StringUtils.isNotBlank(memberDataDTO.getMainClerkId())) {
                    ClerkDTO clerkDTO = clerkIdMap.get(memberDataDTO.getMainClerkId());
                    if (clerkDTO != null) {
                        contactOrderDTO.setMainClerkCode(clerkDTO.getClerkCode());
                        contactOrderDTO.setMainClerkName(clerkDTO.getClerkName());
                    }
                }
                if (StringUtils.isNotBlank(memberDataDTO.getMainStoreId())) {
                    StoreDTO storeDTO = storeIdMap.get(memberDataDTO.getMainStoreId());
                    if (storeDTO != null) {
                        contactOrderDTO.setMainStoreCode(storeDTO.getStoreCode());
                        contactOrderDTO.setMainStoreName(storeDTO.getStoreName());
                    }
                }
            }else {
                contactOrderDTO.setMemberName("账号已注销");
                contactOrderDTO.setMemberDeleteFlag(1);
            }
            String storeId = contactOrder.getStoreId();
            if (StringUtils.isNotBlank(storeId)) {
                StoreDTO storeDTO = storeIdMap.get(storeId);
                if (storeDTO != null) {
                    contactOrderDTO.setStoreCode(storeDTO.getStoreCode());
                    contactOrderDTO.setStoreName(storeDTO.getStoreName());
                }
            }
            dtoList.add(contactOrderDTO);
        }
        return dtoList;
    }

}
