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.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 StoreService storeService;
    @Autowired
    private ClerkService clerkService;

    @Override
    public void saveContactOrder(OrderInfoResp orderInfoResp) {
        Integer orderType = orderInfoResp.getOrderType();
        PlatformChannelEnum platformChannelEnum = PlatformChannelEnum.getEnumByOldOrderType(orderType);
        if (platformChannelEnum == null) {
            return;
        }
        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);
        }

        TabContactLog lastContactLog = contactLogService.getLastByTime(orderInfoResp.getMemberId(), contactBeginTime,receiptsDate);
        if (lastContactLog == null) {
            return;
        }
        logger.info("建联转化订单建联信息:{}", JSON.toJSONString(lastContactLog));
        TabContactOrder contactOrder = new TabContactOrder();
        contactOrder.setOrderId(orderInfoResp.getOrderId());
        contactOrder.setMemberId(orderInfoResp.getMemberId());
        contactOrder.setOrderNumber(orderInfoResp.getOrderNo());
        contactOrder.setPaidAmount(orderInfoResp.getPayAmount());
        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.setEnterpriseId(lastContactLog.getEnterpriseId());
        contactOrderMapper.insert(contactOrder);
    }

    @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;
    }

}
