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

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

import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.enterprise.api.service.ScreeningDetailService;
import com.gic.haoban.manage.api.dto.hm.HmLinkChatDTO;
import com.gic.haoban.manage.api.dto.qdto.hm.HmLinkChatQDTO;
import com.gic.haoban.manage.service.dao.mapper.hm.HmLinkChatMapper;
import com.gic.haoban.manage.service.entity.hm.TabHmLink;
import com.gic.haoban.manage.service.entity.hm.TabHmLinkChat;
import com.gic.haoban.manage.service.service.chat.GroupChatHmService;
import com.gic.haoban.manage.service.service.hm.HmLinkChatService;
import com.github.pagehelper.PageHelper;

@Service("hmLinkChatService")
public class HmLinkChatServiceImpl implements HmLinkChatService {

    private static org.apache.logging.log4j.Logger log = LogManager.getLogger(HmLinkChatService.class);
    @Autowired
    private HmLinkChatMapper hmLinkChatMapper;
    @Autowired
    private GroupChatHmService groupChatHmService;
    @Autowired
    private ScreeningDetailService screeningDetailService;

    @Override
    public List<HmLinkChatDTO> listByLinkId(String wxEnterpriseId, String enterpriseId, Long linkId) {
        List<HmLinkChatDTO> list = this.hmLinkChatMapper.listByLinkId(wxEnterpriseId, enterpriseId, linkId);
        list.forEach(dto -> {
            dto.setEsId(HmLinkChatService.ES_ID + dto.getLinkChatId());
        });
        return list;
    }

    @Override
    public int save(String wxEnterpriseId,String enterpriseId,Long linkId, List<HmLinkChatDTO> list, Long otherHmId, TabHmLink oldLink) {
        log.info("保存群链接={}", JSON.toJSONString(list));
        List<HmLinkChatDTO> oldList = this.hmLinkChatMapper.listByLinkId(wxEnterpriseId, enterpriseId, linkId) ;
        if(CollectionUtils.isEmpty(list)) {
            log.info("删除关联群活码={},{}", linkId, null);
            this.hmLinkChatMapper.delete(linkId, null , 0);
        }
        if(CollectionUtils.isNotEmpty(list)) {
            List<HmLinkChatDTO> updateList = list.stream().filter(dto -> null != dto.getLinkChatId()).collect(Collectors.toList());
            List<Long> notDelIdList = updateList.stream().map(dto -> dto.getLinkChatId()).collect(Collectors.toList());
            log.info("不删除关联群活码={},{}", linkId, notDelIdList);
            this.hmLinkChatMapper.delete(linkId, notDelIdList , 0);
            if (CollectionUtils.isNotEmpty(updateList)) {
                for (HmLinkChatDTO item : updateList) {
                    TabHmLinkChat entity = EntityUtil.changeEntityByJSON(TabHmLinkChat.class, item);
                    this.hmLinkChatMapper.update(entity);
                    if (item.getMemberType() == 0) {
                        screeningDetailService.save(HmLinkChatService.ES_ID + entity.getLinkChatId(), item.getSearchJson());
                    }
                }
            }
            List<HmLinkChatDTO> addList = list.stream().filter(dto -> null == dto.getLinkChatId())
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(addList)) {
                for (HmLinkChatDTO dto : addList) {
                    TabHmLinkChat entity = EntityUtil.changeEntityByJSON(TabHmLinkChat.class, dto);
                    entity.setLinkChatId(UniqueIdUtils.uniqueLong());
                    entity.setLinkId(linkId);
                    this.hmLinkChatMapper.insert(entity);
                    if (dto.getMemberType() == 0) {
                        screeningDetailService.save(HmLinkChatService.ES_ID + entity.getLinkChatId(), dto.getSearchJson());
                    }
                }
            }
        }
        // 更新其他链接
        List<Long> chatHmIdList = list.stream().map(dto -> dto.getChatHmId()).collect(Collectors.toList());
        chatHmIdList.add(otherHmId);
        boolean addOther = false;
        if (null != oldLink) {
            chatHmIdList.add(oldLink.getOtherChatHmId());
            if (!otherHmId.equals(oldLink.getOtherChatHmId())) {
                this.hmLinkChatMapper.delete(linkId, Arrays.asList(oldLink.getOtherChatHmId()) , 1);
                addOther = true;
            }
        } else {
            addOther = true;
        }

        if (addOther) {
            TabHmLinkChat other = new TabHmLinkChat();
            other.setOtherFlag(1);
            other.setWxEnterpriseId(wxEnterpriseId);
            other.setEnterpriseId(enterpriseId);
            other.setLinkId(linkId);
            other.setChatHmId(otherHmId);
            other.setMemberType(0);
            other.setFilterJson("{}");
            other.setSortNum(0);
            other.setLinkChatId(UniqueIdUtils.uniqueLong());
            this.hmLinkChatMapper.insert(other);
        }
        // 统计活码关联的链接数量
        for (HmLinkChatDTO old : oldList) {
            chatHmIdList.add(old.getChatHmId());
        }
        log.info("群id={}",chatHmIdList);
        this.groupChatHmService.updateLinkCount(wxEnterpriseId, chatHmIdList);
        return 0;
    }

    @Override
    public Page<HmLinkChatDTO> listPage(HmLinkChatQDTO qdto, BasePageInfo basePageInfo) {
        PageHelper.startPage(basePageInfo);
        List<HmLinkChatDTO> list = this.hmLinkChatMapper.listPage(qdto);
        Page<HmLinkChatDTO> retPage = PageHelperUtils.changePageHelperToCurrentPage(list, HmLinkChatDTO.class);
        return retPage;
    }

    @Override
    public List<HmLinkChatDTO> getLinkCountForHm(String wxEnterpriseId, List<Long> chatHmIdList) {
        return this.hmLinkChatMapper.getLinkCountForHm(wxEnterpriseId, chatHmIdList);
    }

}
