package com.kiisoo.ic.job.count;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kiisoo.ic.config.WxCpConfiguration;
import com.kiisoo.ic.employee.entity.CpUserCustomerRelationDO;
import com.kiisoo.ic.employee.entity.PrivilageCpUserDO;
import com.kiisoo.ic.employee.mapper.PrivilageCpUserDOMapper;
import com.lmax.disruptor.WorkHandler;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpService;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.UUID;

import static com.kiisoo.ic.config.WxCpConfiguration.APPLICATIONID;

@Slf4j
public class CountDTOMessageGroupConsumer implements WorkHandler<CountDTOMessage> {

    int i = 0;
    /**
     * 处理事件， 如入库操作
     *
     * @param countDtoMessage
     * @throws Exception
     */
    @Override
    public void onEvent(CountDTOMessage countDtoMessage) throws Exception {
        countDtoMessage.setId(UUID.randomUUID().toString());
        String cpUserId = countDtoMessage.getCpUserId();
        PrivilageCpUserDOMapper privilageCpUserDOMapper = countDtoMessage.getPrivilageCpUserDOMapper();
        List<String> customerStrs;

        WxCpService wxCpService = WxCpConfiguration.getCpService(APPLICATIONID);
        WxCpExternalContactService externalContactService = wxCpService.getExternalContactService();

        try {
            //获取客户联系人
            customerStrs = externalContactService.listExternalContacts(cpUserId);
        }catch (Exception e){
            return;
        }
        if (CollectionUtils.isEmpty(customerStrs)){
            return;
        }
        QueryWrapper<PrivilageCpUserDO> qw = new QueryWrapper<>();
        qw.eq("cp_user_id",cpUserId).last("limit 1");
        
        //批量添加账号
        List<String> addedCustomerUserIds = privilageCpUserDOMapper.selectCpUserCustomerRelationByCpId(cpUserId);
        for (String customerStr : customerStrs) {
            if (CollectionUtils.isEmpty(addedCustomerUserIds) || !addedCustomerUserIds.contains(customerStr)){
                privilageCpUserDOMapper.insertCpUserCustomerRelation(customerStr,cpUserId);
            }
        }
    }
}
