package com.kiisoo.ic.job.detail;

import com.kiisoo.ic.customer.CustomerService;
import com.kiisoo.ic.store.entity.PoiStoreStaff;
import com.kiisoo.ic.store.mapper.PoiStoreStaffDOMapper;
import com.kiisoo.ic.synchronous.entity.TurnBackDTO;
import com.kiisoo.ic.synchronous.entity.WxDataDTO;
import com.kiisoo.ic.wx.service.QWMailListManageService;
import com.lmax.disruptor.WorkHandler;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.bean.WxCpUserExternalContactInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
public class DetailDTOMessageGroupConsumer implements WorkHandler<DetailDTOMessage> {

    int i = 0;
    /**
     * 处理事件， 如入库操作
     *
     * @param detailDtoMessage
     * @throws Exception
     */
    @Override
    public void onEvent(DetailDTOMessage detailDtoMessage) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        detailDtoMessage.setId(UUID.randomUUID().toString());
        String cpUserId = detailDtoMessage.getCpUserId();
        CustomerService customerService = detailDtoMessage.getCustomerService();
        PoiStoreStaffDOMapper poiStoreStaffDOMapper = detailDtoMessage.getPoiStoreStaffDOMapper();
        QWMailListManageService qwMailListManageService = detailDtoMessage.getQwMailListManageService();
        Long storeId = detailDtoMessage.getStoreId();
        List<Map<String,Object>> tagList = poiStoreStaffDOMapper.selectStaffTagByStoreId(storeId);
        Map<String,Long> tagMap = new HashMap<>();
        for (Map<String,Object> map:tagList){
            tagMap.put((String)map.get("tag"),(Long)map.get("staffId"));
        }

        List<WxCpUserExternalContactInfo> customers = null;
        try {
            customers = qwMailListManageService.getCustomer(cpUserId);
        } catch (Exception e) {
            log.error("查询联系人失败：" + cpUserId, e);
        }
        if (CollectionUtils.isEmpty(customers)) {
            return;
        }
        for (WxCpUserExternalContactInfo customer : customers) {
            TurnBackDTO turnBackDTO = new TurnBackDTO();

            WxCpUserExternalContactInfo.ExternalContact externalContact = customer.getExternalContact();
            List<WxCpUserExternalContactInfo.FollowedUser> followedUsers = customer.getFollowedUsers();

            turnBackDTO.setEaCode("");
            if (CollectionUtils.isNotEmpty(followedUsers)) {
                for (WxCpUserExternalContactInfo.FollowedUser followedUser : followedUsers) {
                    if (cpUserId.equals(followedUser.getUserId())) {
                        String state = followedUser.getState();
                        WxCpUserExternalContactInfo.Tag[] tags = followedUser.getTags();
                        if (StringUtils.isNotBlank(state)) {
                            //判断是否有导购码
                            turnBackDTO.setEaCode(state);
                        }else if(tags != null && tags.length > 0 && tagList != null && tagList.size() > 0){
                            //判断是否有打tag
                            //todo 根据tag获取导购码
                            for (int j = 0; j < tags.length; j++) {
                                String groupName = tags[j].getGroupName();
                                if ("导购".equals(groupName)){
                                    String tagName = tags[j].getTagName();
                                    Long staffId = tagMap.get(tagName);
                                    if (staffId != null){
                                        PoiStoreStaff poiStoreStaff = poiStoreStaffDOMapper.selectById(staffId);
                                        if (poiStoreStaff!=null){
                                            turnBackDTO.setEaCode(poiStoreStaff.getStaffCode());
                                        }
                                    }else{
                                        //todo 绑定在标签导购上，后续删除
                                        turnBackDTO.setEaCode(tagName);
                                    }
                                }
                            }
                        }
                        Long joinTimeL = followedUser.getCreateTime();
                        Long time = new Long(joinTimeL);
                        String joinTime = sdf.format(time * 1000);
                        turnBackDTO.setJoinTime(joinTime);
                    }
                }
            }
            //type 1 微信，type 2 企业微信
            turnBackDTO.setType(externalContact.getType());
            turnBackDTO.setUserId(cpUserId);
            turnBackDTO.setName(externalContact.getName());
            WxDataDTO wxDataDTO = new WxDataDTO();
            wxDataDTO.setAvatarUrl(externalContact.getAvatar());
            wxDataDTO.setUserId(externalContact.getExternalUserId());
            wxDataDTO.setUnionId(externalContact.getUnionId());
            turnBackDTO.setWxData(wxDataDTO);

            customerService.turnBack(turnBackDTO);
        }
    }
}
