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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.manage.api.dto.qdto.hm.WxUserAddLogQDTO;
import com.gic.haoban.manage.api.dto.qdto.hm.WxUserAddLogSearchQDTO;
import com.gic.haoban.manage.service.dao.mapper.hm.WxUserAddLogMapper;
import com.gic.haoban.manage.service.entity.hm.TabWxUserAddLog;
import com.gic.haoban.manage.service.pojo.bo.hm.HmClerkRelationBO;
import com.gic.haoban.manage.service.pojo.bo.hm.HmLinkBO;
import com.gic.haoban.manage.service.pojo.bo.hm.HmQrcodeBO;
import com.gic.haoban.manage.service.pojo.bo.hm.WxUserAddLogBO;
import com.gic.haoban.manage.service.service.MemberQueryService;
import com.gic.haoban.manage.service.service.hm.HmClerkRelationService;
import com.gic.haoban.manage.service.service.hm.HmLinkService;
import com.gic.haoban.manage.service.service.hm.HmQrcodeService;
import com.gic.haoban.manage.service.service.hm.WxUserAddLogService;
import com.gic.haoban.task.api.service.TelTaskApiService;
import com.gic.member.api.dto.es.MemberDataDTO;
import com.gic.member.tag.api.dto.MemberTagDTO;
import com.gic.member.tag.api.dto.MemberTagItemDTO;
import com.gic.member.tag.api.service.MemberTagApiService;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service("wxUserAddLogService")
public class WxUserAddLogServiceImpl implements WxUserAddLogService {

    private static org.apache.logging.log4j.Logger log = LogManager.getLogger(WxUserAddLogService.class);

    @Autowired
    private WxUserAddLogMapper wxUserAddLogMapper;
    @Autowired
    private HmLinkService hmLinkService;
    @Autowired
    private HmQrcodeService hmQrcodeService;
    @Autowired
    private MemberQueryService memberQueryService;
    @Autowired
    private MemberTagApiService memberTagApiService;
    @Autowired
    private HmClerkRelationService hmClerkRelationService;
    @Autowired
    private TelTaskApiService telTaskApiService;

    @Override
    public void save(WxUserAddLogQDTO qdto) {
        try {
            log.info("保存用户信息-add={}", JSON.toJSON(qdto));
            String externalUserid = qdto.getExternalUserid();
            TabWxUserAddLog entity = new TabWxUserAddLog();
            entity.setLogId(UniqueIdUtils.uniqueLong());
            entity.setWxEnterpriseId(qdto.getWxEnterpriseId());
            entity.setEnterpriseId(qdto.getEnterpriseId());
            entity.setExternalUserid(externalUserid);
            entity.setAddChannel(0);
            entity.setStatusFlag(1);
            entity.setStaffId(qdto.getStaffId());
            //截取成员name
            String staffName = qdto.getStaffName();
            if (null != staffName && staffName.length()>32){
                staffName = staffName.substring(0, 32);
            }
            entity.setStaffName(staffName);
            entity.setAllDelFlag(0);
            if (qdto.isDelFlag()) {
                TabWxUserAddLog logUser = this.wxUserAddLogMapper.selectNewLog(externalUserid, qdto.getStaffId());
                if(null == logUser) {
                    log.info("删除好友-无加的记录") ;
                }else {
                    entity = logUser;
                }
                entity.setLogId(UniqueIdUtils.uniqueLong());
                if(qdto.isDelClerkFlag()) {
                    entity.setStatusFlag(3);
                    entity.setAddChannel(0);
                }else {
                    entity.setStatusFlag(2);
                    // 是否所有好友删除 1是0否
                    entity.setAllDelFlag(this.isAllDel(externalUserid));
                }
            }
            if(null != qdto.getAddWay() && qdto.getAddWay().equals(202)) {
                entity.setAddChannel(3);
            }
            // 新增好友
            if (!qdto.isDelFlag()) {
                String memberLabelId = null;
                if (null != qdto.getHmId()) {
                    HmQrcodeBO hm = this.hmQrcodeService.queryById(qdto.getHmId());
                    entity.setAddChannel(2);
                    entity.setHmId(qdto.getHmId());
                    entity.setHmName(hm.getName());
                    Integer hmType = hm.getHmType();
                    if (hmType == 1) {
                        entity.setClerkId(hm.getClerkId());
                        entity.setClerkCode(hm.getClerkCode());
                        entity.setClerkName(hm.getClerkName());
                        entity.setStoreId(hm.getStoreId());
                        entity.setStoreCode(hm.getStoreCode());
                        entity.setStoreName(hm.getStoreName());
                    } else if (hmType == 2) {
                        HmClerkRelationBO hmClerkRelationBO = hmClerkRelationService.queryByHmIdAndClerkId(qdto.getHmId(), qdto.getClerkId());
                        if (hmClerkRelationBO != null) {
                            entity.setClerkId(hmClerkRelationBO.getClerkId());
                            entity.setClerkCode(hmClerkRelationBO.getClerkCode());
                            entity.setClerkName(hmClerkRelationBO.getClerkName());
                            entity.setStoreId(hmClerkRelationBO.getStoreId());
                            entity.setStoreCode(hmClerkRelationBO.getStoreCode());
                            entity.setStoreName(hmClerkRelationBO.getStoreName());
                        }
                    }

                    memberLabelId = hm.getMemberLabelId();
                }
                if (null != qdto.getLinkId()) {
                    HmLinkBO link = this.hmLinkService.getByLinkIdFormCache(qdto.getWxEnterpriseId(),
                            qdto.getEnterpriseId(), qdto.getLinkId());
                    if(null != link) {
                        entity.setAddChannel(1);
                        entity.setLinkId(qdto.getLinkId());
                        entity.setLinkName(link.getName());
                        memberLabelId = link.getMemberLabelId();
                    }
                }

                if (null != memberLabelId) {
                    entity.setMemberLabelId(memberLabelId);
                    MemberTagItemDTO dto = this.memberTagApiService.findMemberTagItem(memberLabelId);
                    if (null != dto) {
                        String tagId = dto.getTagId();
                        MemberTagDTO tag = this.memberTagApiService.getMemberTagById(tagId);
                        entity.setMemberLabelName(tag.getTagName() + "-" + dto.getTagItemName());
                    } else {
                        log.info("会员标签查询null,memberLabelId={}", memberLabelId);
                    }
                }
            }
            if (null != qdto.getMemberId()) {
                entity.setMemberId(qdto.getMemberId());
                entity = this.addMemberInfo(qdto.getEnterpriseId(), qdto.getMemberId(), entity);
            }
            if (qdto.isDelFlag()) {
                if(qdto.getDeleteByTransfer()==1) {
                    // 在职继承删除
                    entity.setAddChannel(4);
                }
            }
            entity.setQwAddTime(qdto.getQwAddTime());
            entity.setFriendClerkId(qdto.getFriendClerkId());
            entity.setFriendStoreId(qdto.getFriendStoreId());
            entity.setDelType(qdto.getDelType());
            entity.setDelIsSingle(qdto.getDelIsSingle());
            if(null != qdto.getAddWay() && qdto.getAddWay().equals(202) && null != entity.getMemberId()) {
                TabWxUserAddLog delUser = this.wxUserAddLogMapper.getForTask(externalUserid) ;
                if(null != delUser && null != delUser.getStoreId() && delUser.getStoreId().equals(entity.getStoreId())) {
                    String overClerkId = delUser.getClerkId() ;
                    this.telTaskApiService.distributeTask(qdto.getEnterpriseId(), overClerkId , Arrays.asList(entity.getMemberId()), entity.getClerkId());
                }
            }
            this.wxUserAddLogMapper.insert(entity);
        }catch(Exception e) {
            log.info("异常",e);
        }
    }

    @Override
    public void updateMemberInfo(String wxEnterpriseId, String enterpriseId, String staffId, String externalUserid,
                                 String memberId) {
        log.info("保存用户信息-update={}", memberId);
        if (StringUtils.isNotBlank(memberId)) {
            TabWxUserAddLog entity = new TabWxUserAddLog();
            entity = this.addMemberInfo(enterpriseId, memberId, entity);
            entity.setEnterpriseId(enterpriseId);
            entity.setWxEnterpriseId(wxEnterpriseId);
            entity.setExternalUserid(externalUserid);
            entity.setStaffId(staffId);
            entity.setCreateTime(new Date());
            this.wxUserAddLogMapper.updateMemberInfo(entity);
        }
    }

    // 冗余会员信息
    private TabWxUserAddLog addMemberInfo(String enterpriseId, String memberId, TabWxUserAddLog entity) {
        String returnFields = "memberId,photoUrl,name,nickName,cardNo,gradeId,gradeName,phoneNumber";
        JSONObject memberObj = this.memberQueryService.queryDataSingle(enterpriseId, memberId, returnFields);
        if (null == memberObj) {
            log.info("会员不存在,memberId={}", memberId);
            return entity;
        }
        MemberDataDTO memberDataDTO = memberObj.toJavaObject(MemberDataDTO.class);
        entity.setMemberId(memberId);
        String name = memberDataDTO.getName();
        if (name != null && name.length()>32){
            name = name.substring(0, 32);
        }
        entity.setMemberName(name);
        entity.setMemberNick(memberDataDTO.getNickName());
        entity.setMemberImage(memberDataDTO.getPhotoUrl());
        entity.setMemberPhone(memberDataDTO.getPhoneNumber());
        entity.setMemberGradeId(memberDataDTO.getGradeId());
        entity.setMemberGradeName(memberDataDTO.getGradeName());
        entity.setMemberCardNo(memberDataDTO.getCardNo());
        return entity;
    }

    private int isAllDel(String externalUserid) {
        List<TabWxUserAddLog> list = this.wxUserAddLogMapper.listAllForDel(externalUserid);
        Map<String, List<TabWxUserAddLog>> map = list.stream()
                .collect(Collectors.groupingBy(TabWxUserAddLog::getStaffId));
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        boolean exist = false;
        while (it.hasNext()) {
            String staffId = it.next();
            List<TabWxUserAddLog> itemList = map.get(staffId);
            if (itemList.size() == 1 && itemList.get(0).getStatusFlag() == 2) {
                log.info("成员={}只有1条删除的记录", staffId);
            } else {
                TabWxUserAddLog addLog = itemList.get(0);
                if (addLog.getStatusFlag() == 1) {
                    log.info("成员={}最新是添加记录", staffId);
                    if (addLog.getStaffId().equals(staffId)) {
                        log.info("成员={}本次删除", staffId);
                    } else {
                        exist = true;
                    }
                } else {
                    log.info("成员={}最新是删除记录", staffId);
                }
            }
        }
        if (exist) {
            return 0;
        }
        return 1;
    }

    @Override
    public Page<WxUserAddLogBO> page(WxUserAddLogSearchQDTO qdto, BasePageInfo pageInfo) {
        PageHelper.startPage(pageInfo);
        List<TabWxUserAddLog> list = this.wxUserAddLogMapper.listForPage(qdto);
        Page<WxUserAddLogBO> retPage = PageHelperUtils.changePageHelperToCurrentPage(list, WxUserAddLogBO.class);
        return retPage;
    }

}
