package com.fzm.mall.customer.service.customer.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fzm.mall.customer.service.customer.entity.dto.CustomerDTO;
import com.fzm.mall.customer.service.customer.entity.dto.CustomerSaveDTO;
import com.fzm.mall.customer.service.customer.entity.dto.ShopCustomerDTO;
import com.fzm.mall.customer.service.customer.mapper.GroupMapper;
import com.fzm.mall.customer.service.customer.mapper.GroupUserMapper;
import com.fzm.mall.customer.service.customer.mapper.MessageMapper;
import com.fzm.mall.customer.service.customer.mapper.ShopMapper;
import com.fzm.mall.customer.service.customer.model.Group;
import com.fzm.mall.customer.service.customer.model.Message;
import com.fzm.mall.customer.service.customer.service.CustomerService;
import com.fzm.mall.customer.service.websocket.WebSocketMsgServer;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wulixian
 * @since 2021-04-07
 */
@Service
@Transactional
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CustomerServiceImpl implements CustomerService {

    private final GroupMapper groupMapper;
    private final GroupUserMapper groupUserMapper;
    private final MessageMapper messageMapper;
    private final ShopMapper shopMapper;

    @Override
    public CustomerDTO contact(CustomerSaveDTO customerSaveDTO) {
        CustomerDTO result = new CustomerDTO();
        /**
         * 1.判断当前用户和客服是否存在聊天组
         * 若有：直接使用已有组
         * 若无：创建组
         */
        List<Group> groupUserList = groupMapper.listGroupAndUser(customerSaveDTO.getUserId());
        Group existedGroup = findExistedGroup(customerSaveDTO.getCustomerId(), groupUserList);
        if (ObjectUtils.isNotEmpty(existedGroup)) {
            List<Message> messageList = messageMapper.selectList(new LambdaQueryWrapper<Message>().eq(Message::getToId, existedGroup.getGroupId()));
            result.setGroup(existedGroup);
            result.setMessageList(messageList);
        } else {
            /**
             * 创建组
             */
            Group group = new Group();
            group.init(customerSaveDTO);
            groupMapper.insert(group);

            /**
             * 创建组成员
             */
            group.batchSaveGroupUser(groupUserMapper, customerSaveDTO);

            result.setGroup(group);
            result.setMessageList(new ArrayList<>());

            /**
             * 刷新客服的联系人列表
             */
            List<CustomerDTO> list = list(customerSaveDTO.getCustomerId(), null, null);
            WebSocketMsgServer.sendInfo(customerSaveDTO.getCustomerId(), JSONArray.toJSONString(list));
        }
        return result;
    }

    /**
     * 查找已存在的共同聊天组
     *
     * @param customerId
     * @param groupUserList
     * @return
     */
    private Group findExistedGroup(String customerId, List<Group> groupUserList) {
        Group existedGroup = null;
        for (Group group : groupUserList) {
            if (group.getUserIdList().contains(customerId)) {
                existedGroup = group;
                break;
            }
        }
        return existedGroup;
    }

    @Override
    public List<CustomerDTO> list(String userId, String toId, String keyWord) {
        List<Group> groupList = groupMapper.list(userId, toId);

        List<String> masterIdList = groupList.stream().map(Group::getMasterId).collect(Collectors.toList());
        boolean isUser = masterIdList.contains(userId);
        if (StringUtils.isNotBlank(keyWord)) {
            if (isUser) {
                //如果是用户，判断客服名称
                groupList = groupList.stream().filter(group -> group.getCustomerName().contains(keyWord)).collect(Collectors.toList());
            } else {
                //如果是客服，判断userName
                groupList = groupList.stream().filter(group -> group.getUserName().contains(keyWord)).collect(Collectors.toList());
            }
        }
        List<CustomerDTO> result = groupList.stream().map(group -> {
            CustomerDTO dto = new CustomerDTO();
            List<Message> messageList = messageMapper.selectList(new LambdaQueryWrapper<Message>().eq(Message::getToId, group.getGroupId()));
            dto.setGroup(group);
            dto.setMessageList(messageList);
            return dto;
        }).collect(Collectors.toList());
        return result;
    }

    @Override
    public List<ShopCustomerDTO> listShopCustomer(String merchantId) {
        return shopMapper.listShopCustomer(merchantId);
    }
}
