package com.iformall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.IdWorker;
import com.iformall.domain.po.*;
import com.iformall.enums.*;
import com.iformall.mapper.*;
import com.iformall.service.WxCUserTagsService;
import com.iformall.service.WxTagsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

@Service
public class WxCUserTagsServiceImpl implements WxCUserTagsService {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
    WxCUserTagsMapper wxCUserTagsMapper;
	
	@Autowired
	WxCUserBasicInfoMapper wxCUserBasicInfoMapper;

	@Autowired
	WxCouponOrderMapper wxCouponOrderMapper;

	@Autowired
	WxCardSpendMapper wxCardSpendMapper;

	@Autowired
	WxCUserMapper wxCUserMapper;

	@Autowired
	WxTagsMapper  wxTagsMapper;

	@Autowired
	WxCUserCarMapper wxCUserCarMapper;

	@Autowired
	WxSubBusinessMapper wxSubBusinessMapper;

	@Autowired
	WxBusinessMapper wxBusinessMapper;

	@Autowired
	WxTagsService wxTagsService;



    @Override
    public PageInfo<WxCUserTags> listAsPage(WxCUserTags record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxCUserTagsMapper.findList(record));
    }

    @Override
    public WxCUserTags getById(Long id) {
        return wxCUserTagsMapper.selectById(id);
    }

    @Override
    public void saveOrUpdate(WxCUserTags record) {
        if (record.getId() == null) {
            final IdWorker idWorker = IdWorker.get();
        	record.setId(idWorker.nextId());
        	record.setCreateDate(new Date());
        	record.setUpdateDate(new Date());
            wxCUserTagsMapper.insert(record);
        } else {
			record.setUpdateDate(new Date());
            wxCUserTagsMapper.updateById(record);
        }
    }

    @Override
    public void deleteById(Long id) {
        wxCUserTagsMapper.deleteById(id);
    }


	@Override
	public long countUser(String tenantId,  Long tagId, Date startTime, Date endTime ) {
		String str = JSON.toJSONString(tagId);
		return wxCUserTagsMapper.countUser(str, tenantId, startTime, endTime);
	}


	@Override
	public List<WxTags> findTagList(String tenantId, List<Long> tagIds) {
    	if (tagIds == null || tagIds.isEmpty())
    		return new ArrayList<WxTags>();
    	WxTags wxTags =new WxTags();
    	wxTags.setIds(tagIds);
    	List<WxTags> list = wxTagsMapper.findList(wxTags);
		for (WxTags t : list) {
			t.setCount(countUser(tenantId,t.getId(),null,null));
		}
		return list;
	}

//**************************************************自动打标逻辑代码 *************************************************************

	//打标
	private List<WxTags> assign(WxCUserBasicInfo user, EnumTag tag){
		if (tag == null || user == null)
			return null;
		WxCUserTags record = new WxCUserTags();
		record.setUserId(user.getId());
		record.setTenantId(user.getTenantId());
		List<WxCUserTags> cUserTagsList = wxCUserTagsMapper.findList(record);
		if (cUserTagsList.size() > 0) {
			record.setId(cUserTagsList.get(0).getId());
			record.setTags(cUserTagsList.get(0).getTags());
		}
		String tags = record.getTags();

		List<Long> tagIdList;
		if (tags == null)
			tagIdList = new ArrayList<Long>();
		else
			tagIdList = JSON.parseArray(tags, Long.class);

		Iterator<Long> it = tagIdList.iterator();
		if (tag.getType().getFlag() == EnumTagTypeFlag.FLAG_SINGLE){
			while(it.hasNext()){
				Long id = it.next();
				if(null!=EnumTag.getEnum(id) && EnumTag.getEnum(id).getType() == tag.getType()){
					it.remove();
				}
			}
		} else {
			while(it.hasNext()){
				Long id = it.next();
				if(id.equals(tag.getCode())){
					it.remove();
				}
			}
		}

		tagIdList.add(tag.getCode());
		record.setTags(JSON.toJSONString(tagIdList));
		saveOrUpdate(record);
		if (user.getTagId() == null ||
				!user.getTagId().equals(record.getId())) {
			user.setTagId(record.getId());
            wxCUserBasicInfoMapper.updateById(user);
		}
		WxTags wxTags = new WxTags();
		wxTags.setIds(tagIdList);
		return wxTagsMapper.findList(wxTags);
	}

	//去标
	private List<WxTags>  resign(WxCUserBasicInfo user, EnumTag tag){
		if (tag == null || user == null)
			return null;
		WxCUserTags record = new WxCUserTags();
		record.setUserId(user.getId());
		record.setTenantId(user.getTenantId());
		List<WxCUserTags> cUserTagsList = wxCUserTagsMapper.findList(record);
		if (cUserTagsList.size() > 0) {
			record.setId(cUserTagsList.get(0).getId());
		} else return null;
		String tags = record.getTags();
		List<Long> tagIdList = JSON.parseArray(tags, Long.class);
		Iterator<Long> it = tagIdList.iterator();
		while(it.hasNext()){
			if(it.next().equals(tag.getCode())){
				it.remove();
			}
		}
		record.setTags(JSON.toJSONString(tagIdList));
		saveOrUpdate(record);

		WxTags wxTags = new WxTags();
		wxTags.setIds(tagIdList);
		return wxTagsMapper.findList(wxTags);

	}

	//类型打标
	private List<WxTags>  assignTypeId1(WxCUserBasicInfo user, Integer sex) {
		List<WxTags> resList = null;
		if (sex.equals(EnumCUserBaseInfoSex.MALE.getCode()))
			resList = assign(user, EnumTag.ID_1);
		if (sex.equals(EnumCUserBaseInfoSex.FEMALE.getCode()))
			resList = assign(user, EnumTag.ID_2);
		return resList;
	}

	private List<WxTags>  assignTypeId2(WxCUserBasicInfo user, Date date) {
		List<WxTags> resList = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			if (date.after(sdf.parse("2000-01-01")))
				resList = assign(user, EnumTag.ID_3);
			else if (date.after(sdf.parse("1990-01-01")))
				resList = assign(user, EnumTag.ID_4);
			else if (date.after(sdf.parse("1980-01-01")))
				resList = assign(user, EnumTag.ID_5);
			else if (date.after(sdf.parse("1970-01-01")))
				resList = assign(user, EnumTag.ID_6);
			else if (date.after(sdf.parse("1960-01-01")))
				resList = assign(user, EnumTag.ID_7);
		} catch (Exception e) {
			return null;
		}
		return resList;
	}

	private List<WxTags>  assignTypeId3(WxCUserBasicInfo user, Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int year = cal.get(Calendar.YEAR);
		if (year > 1900) {
			EnumTag[] years = new EnumTag[]{EnumTag.ID_8,
				EnumTag.ID_9,
				EnumTag.ID_10,
				EnumTag.ID_11,
				EnumTag.ID_12,
				EnumTag.ID_13,
				EnumTag.ID_14,
				EnumTag.ID_15,
				EnumTag.ID_16,
				EnumTag.ID_17,
				EnumTag.ID_18,
				EnumTag.ID_19
			};
			return assign(user, years[(year - 1900) % years.length]);
		}
		return null;
	}

	private List<WxTags>  assignTypeId4(WxCUserBasicInfo user, Date date) {
		final int[] dayArr = new int[]{
			20, 19, 21, 20,
			21, 22, 23, 23,
			23, 24, 23, 22};
		final EnumTag[] constellation = new EnumTag[]{
			EnumTag.ID_29,
			EnumTag.ID_30,
			EnumTag.ID_31,
			EnumTag.ID_20,
			EnumTag.ID_21,
			EnumTag.ID_22,
			EnumTag.ID_23,
			EnumTag.ID_24,
			EnumTag.ID_25,
			EnumTag.ID_26,
			EnumTag.ID_27,
			EnumTag.ID_28,
			EnumTag.ID_29,
		};
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int month = cal.get(Calendar.MONTH);
		int day = cal.get(Calendar.DAY_OF_MONTH);

		return assign(user, day < dayArr[month] ? constellation[month]
				: constellation[month + 1]);
	}

	private List<WxTags>  assignTypeId5(WxCUserBasicInfo user, boolean online) {
		if (online)
			return assign(user, EnumTag.ID_32);
		else
			return assign(user, EnumTag.ID_33);
	}

	private List<WxTags>  assignTypeId6(WxCUserBasicInfo user, String education) {
		List<WxTags> resList = null;
		if (education.contains(EnumTag.ID_38.getMessage()))
			resList = assign(user, EnumTag.ID_38);
		else if (education.contains(EnumTag.ID_37.getMessage()))
			resList = assign(user, EnumTag.ID_37);
		else if (education.contains(EnumTag.ID_36.getMessage()))
			resList = assign(user, EnumTag.ID_36);
		else if (education.contains(EnumTag.ID_35.getMessage()))
			resList = assign(user, EnumTag.ID_35);
		else if (education.contains(EnumTag.ID_34.getMessage()))
			resList = assign(user, EnumTag.ID_34);
		return resList;
	}

	private List<WxTags>  assignTypeId7(WxCUserBasicInfo user, String phone) {

		List<WxTags> resList = null;
		/**
		 * 中国电信号码格式验证 手机段： 133,153,180,181,189,177,1700,173,199
		 **/
		final String CHINA_TELECOM_PATTERN = "(^1(33|53|77|73|99|8[019])\\d{8}$)|(^1700\\d{7}$)";

		/**
		 * 中国联通号码格式验证 手机段：130,131,132,155,156,185,186,145,176,1709
		 **/
		final String CHINA_UNICOM_PATTERN = "(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";

		/**
		 * 中国移动号码格式验证
		 * 手机段：134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
		 **/
		final String CHINA_MOBILE_PATTERN = "(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";

		if (Pattern.matches(CHINA_MOBILE_PATTERN, phone))
			resList = assign(user, EnumTag.ID_39);
		if (Pattern.matches(CHINA_UNICOM_PATTERN, phone))
			resList = assign(user, EnumTag.ID_40);
		if (Pattern.matches(CHINA_TELECOM_PATTERN,phone))
			resList = assign(user, EnumTag.ID_41);
		return resList;
	}

	private List<WxTags>  assignTypeId9(WxCUserBasicInfo user, String extraInfo) {
		List<WxTags> resList = null;
		JSONObject extraInfoJson = JSONObject.parseObject(extraInfo);
		if (extraInfoJson == null) return null;
		JSONObject systemInfoJson = extraInfoJson.getJSONObject("systemInfo");
		if (systemInfoJson == null) return null;
		String brand = systemInfoJson.getString("brand");
		if(brand == null) return null;
		brand = brand.toUpperCase();
		if (brand.equals("IPHONE"))
			resList = assign(user, EnumTag.ID_49);
		else if (brand.equals("HUAWEI") || brand.equals("HONOR"))
			resList = assign(user, EnumTag.ID_50);
		else if (brand.equals("VIVO") || brand.toUpperCase().equals("OPPO"))
			resList = assign(user, EnumTag.ID_51);
		else if (brand.equals("SAMSUNG"))
			resList = assign(user, EnumTag.ID_52);
		else if (brand.equals("XIAOMI"))
			resList = assign(user, EnumTag.ID_53);
		else
			resList = assign(user, EnumTag.ID_54);
    	return resList;
	}

	private List<WxTags>  assignTypeId11(WxCUserBasicInfo user) {
		return assign(user, EnumTag.ID_58);
	}


	private List<WxTags>  assignTypeId14(WxCUserBasicInfo user, WxCUser param)
	{
		List<WxTags> resList = null;
		Calendar endC = Calendar.getInstance();
		Calendar startC = Calendar.getInstance();
		endC.setTime(new Date());
		startC.setTime(new Date());
		startC.add(Calendar.DAY_OF_YEAR, -30);
		WxCouponOrder wxCouponOrder = new WxCouponOrder();
		wxCouponOrder.setCUserId(param.getId());
		wxCouponOrder.setCouponOrderStatus(EnumCouponOrderStatus.COUPON_ORDER_USED.getCode());
		wxCouponOrder.setStartTime(startC.getTime());
		wxCouponOrder.setEndTime(endC.getTime());

		WxCardSpend wxCardSpend = new WxCardSpend();
		wxCardSpend.setOwnerId(param.getId());
		wxCardSpend.setStartdate(startC.getTime());
		wxCardSpend.setEnddate(endC.getTime());

		WxBusiness business = new WxBusiness();
		List<WxBusiness> list = wxBusinessMapper.findList(business);

		List<Map<String, Object>> cardSpendCountList = wxCardSpendMapper.getCountByBusinessId(wxCardSpend);
		List<Map<String, Object>> cardOrderCountList = wxCouponOrderMapper.getCountByBusinessId(wxCouponOrder);

		list.stream().forEach(b->{
			int count = 0;
			if(cardSpendCountList.size() > 0) {
				for (Map<String, Object> cardSpendCount : cardSpendCountList) {
					if (cardSpendCount.get("businessId").equals(b.getId().toString())) {
						count += (Integer) cardSpendCount.get("buCount");
					}
				}
			}
			if(cardOrderCountList.size() > 0) {
				for (Map<String, Object> cardOrderCount : cardOrderCountList) {
					if (cardOrderCount.get("business").equals(b.getId().toString())) {
						count += (Integer) cardOrderCount.get("buCount");
					}
				}
			}
			if (count > 0) {
				EnumTag tag = null;
				if (b.getId().intValue() >= EnumBusiness.BUSINESS_ID1.getCode() &&
						b.getId().intValue() <= EnumBusiness.BUSINESS_ID5.getCode()){
					tag = EnumTag.getEnum(EnumTag.ID_68.getCode()
							+ (b.getId().intValue() - EnumBusiness.BUSINESS_ID1.getCode()));
				}

				if (b.getId().intValue() >= EnumBusiness.BUSINESS_ID7.getCode() &&
						b.getId().intValue() <= EnumBusiness.BUSINESS_ID10.getCode()){
					tag = EnumTag.getEnum(EnumTag.ID_73.getCode()
							+ (b.getId().intValue() - EnumBusiness.BUSINESS_ID7.getCode()));
				}
				if (b.getId().intValue() == EnumBusiness.BUSINESS_ID11.getCode()){
					tag = EnumTag.ID_145;
				}
				resList.clear();
				resList.addAll(assign(user, tag));
			}
		});

		return resList;
	}

	private List<WxTags>  assignTypeId17(WxCUserBasicInfo user, WxCUser param)
	{
		List<WxTags> resList = null;
		Calendar endC = Calendar.getInstance();
		Calendar startC = Calendar.getInstance();
		endC.setTime(new Date());
		startC.setTime(new Date());
		startC.add(Calendar.DAY_OF_YEAR, -30);
		WxCouponOrder wxCouponOrder = new WxCouponOrder();
		wxCouponOrder.setCUserId(param.getId());
		wxCouponOrder.setCouponOrderStatus(EnumCouponOrderStatus.COUPON_ORDER_USED.getCode());
		wxCouponOrder.setStartTime(startC.getTime());
		wxCouponOrder.setEndTime(endC.getTime());
		wxCouponOrder.setBusinessId(EnumBusiness.BUSINESS_ID1.getCode());

		WxCardSpend wxCardSpend = new WxCardSpend();
		wxCardSpend.setOwnerId(param.getId());
		wxCardSpend.setStartdate(startC.getTime());
		wxCardSpend.setEnddate(endC.getTime());
		wxCardSpend.setBusinessId(EnumBusiness.BUSINESS_ID1.getCode());

		WxSubBusiness subBusiness = new WxSubBusiness();
		subBusiness.setBusinessId(EnumBusiness.BUSINESS_ID1.getCode());
		List<WxSubBusiness> list = wxSubBusinessMapper.findList(subBusiness);

		List<Map<String, Object>> cardSpendCountList = wxCardSpendMapper.getCountBySubBusinessId(wxCardSpend);
		List<Map<String, Object>> cardOrderCountList = wxCouponOrderMapper.getCountBySubBusinessId(wxCouponOrder);

		list.stream().forEach(sb->{
			int count = 0;
			if(cardSpendCountList.size() > 0) {
				for (Map<String, Object> cardSpendCount : cardSpendCountList) {
					Long subBusinessId = (Long)cardSpendCount.get("subBusinessId");
					if (subBusinessId != null && subBusinessId.equals(sb.getId())) {
						count += (Integer) cardSpendCount.get("buCount");
					}
				}
			}
			if(cardOrderCountList.size() > 0) {
				for (Map<String, Object> cardOrderCount : cardOrderCountList) {
					Long subBusinessId = (Long)cardOrderCount.get("subBusiness");
					if (subBusinessId != null && subBusinessId.equals(sb.getId())) {
						count += (Integer) cardOrderCount.get("buCount");
					}
				}
			}
			if (count > 0) {
				EnumTag tag = null;
				if (sb.getId().intValue() >= EnumSubBusiness.SUB_BUSINESS_ID1.getCode() &&
						sb.getId().intValue() <= EnumSubBusiness.SUB_BUSINESS_ID5.getCode()){
					tag = EnumTag.getEnum(EnumTag.ID_92.getCode()
							+ (sb.getId().intValue() - EnumSubBusiness.SUB_BUSINESS_ID1.getCode()));
				}

				if (sb.getId().intValue() >= EnumSubBusiness.SUB_BUSINESS_ID6.getCode() &&
						sb.getId().intValue() <= EnumSubBusiness.SUB_BUSINESS_ID21.getCode()){
					tag = EnumTag.getEnum(EnumTag.ID_129.getCode()
							+ (sb.getId().intValue() - EnumSubBusiness.SUB_BUSINESS_ID6.getCode()));
				}
				resList.clear();
				resList.addAll(assign(user, tag));
			}
		});

		return resList;
	}

	private List<WxTags>  assignTypeId18(WxCUserBasicInfo user, WxCUser param) {
		List<WxTags> resList = null;

		final int WORK_DAY = 0;
		final int WORK_NIGHT = 1;
		final int WEEKEND_DAY = 2;
		final int WEEKEND_NIGHT = 3;

		int workDayCount = 0;
		int workNightCount = 0;
		int WeekendDayCount = 0;
		int WeekendNightCount = 0;

		Calendar endC = Calendar.getInstance();
		Calendar startC = Calendar.getInstance();
		endC.setTime(new Date());
		startC.setTime(new Date());
		startC.add(Calendar.DAY_OF_YEAR, -30);

		WxCouponOrder wxCouponOrder = new WxCouponOrder();
		wxCouponOrder.setCUserId(param.getId());
        wxCouponOrder.setCouponOrderStatus(EnumCouponOrderStatus.COUPON_ORDER_USED.getCode());
		wxCouponOrder.setStartTime(startC.getTime());
		wxCouponOrder.setEndTime(endC.getTime());

        WxCardSpend wxCardSpend = new WxCardSpend();
		wxCardSpend.setOwnerId(param.getId());
		wxCardSpend.setStartdate(startC.getTime());
		wxCardSpend.setEnddate(endC.getTime());

		wxCardSpend.setTimeSlot(WORK_DAY);
		wxCouponOrder.setTimeSlot(WORK_DAY);
		workDayCount = wxCardSpendMapper.findCount(wxCardSpend);
		workDayCount += wxCouponOrderMapper.findCount(wxCouponOrder);

		wxCardSpend.setTimeSlot(WORK_NIGHT);
		wxCouponOrder.setTimeSlot(WORK_NIGHT);
		workNightCount = wxCardSpendMapper.findCount(wxCardSpend);
		workNightCount += wxCouponOrderMapper.findCount(wxCouponOrder);

		wxCardSpend.setTimeSlot(WEEKEND_DAY);
		wxCouponOrder.setTimeSlot(WEEKEND_DAY);
		WeekendDayCount = wxCardSpendMapper.findCount(wxCardSpend);
		WeekendDayCount += wxCouponOrderMapper.findCount(wxCouponOrder);

		wxCardSpend.setTimeSlot(WEEKEND_NIGHT);
		wxCouponOrder.setTimeSlot(WEEKEND_NIGHT);
		WeekendNightCount = wxCardSpendMapper.findCount(wxCardSpend);
		WeekendNightCount += wxCouponOrderMapper.findCount(wxCouponOrder);

		if (workDayCount > WeekendDayCount
				&& workDayCount > workNightCount
				&& workDayCount > WeekendNightCount)
			resList = assign(user, EnumTag.ID_97);
		else if (workNightCount > workDayCount
				&& workNightCount > WeekendDayCount
				&& workNightCount > WeekendNightCount)
			resList = assign(user, EnumTag.ID_98);
		else if (WeekendDayCount > workDayCount
				&& WeekendDayCount > workNightCount
				&& WeekendDayCount > WeekendNightCount)
			resList = assign(user, EnumTag.ID_99);
		else if (WeekendNightCount > workDayCount
				&& WeekendNightCount > workNightCount
				&& WeekendNightCount > WeekendDayCount)
			resList = assign(user, EnumTag.ID_100);
		return resList;
	}

	private List<WxTags>  assignTypeId21(WxCUserBasicInfo user, WxCUser param) {
		List<WxTags> resList = null;
		Calendar startC = Calendar.getInstance();
		startC.setTime(new Date());
		startC.add(Calendar.DAY_OF_YEAR, -30);

		WxCouponOrder wxCouponOrder = new WxCouponOrder();
		wxCouponOrder.setCUserId(param.getId());
		wxCouponOrder.setStartTime(startC.getTime());
		wxCouponOrder.setEndTime(new Date());

		int count = wxCouponOrderMapper.findCount(wxCouponOrder);

		float verifiedRate = (float)count/30;
		if (verifiedRate > 1F/4)
			resList = assign(user, EnumTag.ID_109);
		else if (verifiedRate > 1F/7)
			resList = assign(user, EnumTag.ID_108);
		else if (verifiedRate > 1F/30)
			resList = assign(user, EnumTag.ID_107);

		return resList;
	}

    private List<WxTags>  assignTypeId22(WxCUserBasicInfo user, WxCUser param) {
        List<WxTags> resList = null;
        int days = (int) ((new Date().getTime() - param.getCreateDate().getTime()) / (1000*3600*24));

        float loginRate = (float)param.getLoginCount()/days;
        if (loginRate > 1F/4)
            resList = assign(user, EnumTag.ID_112);
        else if (loginRate > 1F/7)
            resList = assign(user, EnumTag.ID_111);
        else if (loginRate > 1F/30)
            resList = assign(user, EnumTag.ID_110);
        return resList;
    }

	//打标接口
	@Override
	public List<WxTags> assignTags(List<Long> tagIdList, WxCUserBasicInfo user) {
		List<WxTags> resList = null;
		for (Long tagId : tagIdList) {
			resList = assign(user, EnumTag.getEnum(tagId));
		}
		return resList;
	}

	//打标触发
	@Override
	public List<WxTags> triggerAssignTags(EnumAssignTagsTrigger trigger, Object obj) {
		if (obj == null)
			return null;

		List<WxTags> resList = null;
		try {
			switch (trigger) {
				case ASSIGN_TAGS_TRIGGER_IMPORT: {
					WxCUserBasicInfo param = (WxCUserBasicInfo) obj;
                    WxCUserBasicInfo user = wxCUserBasicInfoMapper.selectById(param.getId());
					if (user != null) {
						if (param.getSex() != null) {
							//性别
							resList = assignTypeId1(user, param.getSex());
						}
						if (param.getBirthdate() != null) {
							//X0后
							resList = assignTypeId2(user, param.getBirthdate());
							//生肖
							resList = assignTypeId3(user, param.getBirthdate());
							//星座
							resList = assignTypeId4(user, param.getBirthdate());
						}
						if (param.getPhone() != null) {
							//来源
							resList = assignTypeId5(user, false);
							//运营商
							resList = assignTypeId7(user, param.getPhone());
						}
						if (param.getEducation() != null) {
							//学历
							resList = assignTypeId6(user, param.getEducation());
						}
					}
				}
				break;
				case ASSIGN_TAGS_TRIGGER_CAR:{
                    Long param = (Long) obj;
                    WxCUserBasicInfo user = wxCUserBasicInfoMapper.selectById(param);
					if (user != null) {
						//车
						resList = assignTypeId11(user);
					}
				}
				break;
				case ASSIGN_TAGS_TRIGGER_PHONE: {
					WxCUser param = (WxCUser) obj;
                    WxCUserBasicInfo user = wxCUserBasicInfoMapper.selectById(param.getId());
					if (user != null) {
						if (param.getPhone() != null) {
							//来源
							resList = assignTypeId5(user, true);
							//运营商
							resList = assignTypeId7(user, param.getPhone());
						}
					}
				}
				break;
				case ASSIGN_TAGS_TRIGGER_BUY:{
					WxCUser param = (WxCUser) obj;
                    WxCUserBasicInfo user = wxCUserBasicInfoMapper.selectById(param.getId());
					if (user != null) {
						//消费类别
						resList = assignTypeId14(user, param);
						//饮食偏好
						resList = assignTypeId17(user, param);
						//消费时段
						resList = assignTypeId18(user, param);
						//消费频度
						resList = assignTypeId22(user, param);
					}
				}
				break;
				case ASSIGN_TAGS_TRIGGER_USE:
					break;

				case ASSIGN_TAGS_TRIGGER_LOGIN: {
					WxCUser param = (WxCUser) obj;
                    WxCUserBasicInfo user = wxCUserBasicInfoMapper.selectById(param.getId());
					if (user != null) {
						if (param.getGender() != null) {
							//性别
							resList = assignTypeId1(user, param.getGender());
						}
						if (param.getExtraInfo() != null) {
							//手机品牌
							resList = assignTypeId9(user, param.getExtraInfo());
						}
						if (param.getPhone() != null) {
							//来源
							resList = assignTypeId5(user, true);
							//运营商
							resList = assignTypeId7(user, param.getPhone());
						}
						//活跃
						resList = assignTypeId21(user, param);
					}
				}
				break;
				case ASSIGN_TAGS_TRIGGER_SCAN: {
					WxCUserBasicInfo user = (WxCUserBasicInfo) obj;
                    WxCUser param = wxCUserMapper.selectById(user.getId());
					if (user != null) {

						if (user.getSex() != null) {
							//性别
							resList = assignTypeId1(user, user.getSex());
						}
						if (user.getBirthdate() != null) {
							//X0后
							resList = assignTypeId2(user, user.getBirthdate());
							//生肖
							resList = assignTypeId3(user, user.getBirthdate());
							//星座
							resList = assignTypeId4(user, user.getBirthdate());
						}
						if (user.getPhone() != null) {
							//运营商
							resList = assignTypeId7(user, user.getPhone());
						}
						if (user.getEducation() != null) {
							//学历
							resList = assignTypeId6(user, user.getEducation());
						}

						if (param != null) {
							//消费类别
							resList = assignTypeId14(user, param);
							//饮食偏好
							resList = assignTypeId17(user, param);

							//消费时段
							resList = assignTypeId18(user, param);
							//消费频度
							resList = assignTypeId22(user, param);
							//活跃
							resList = assignTypeId21(user, param);

							//车
							WxCUserCar wxCUserCar = new WxCUserCar();
							wxCUserCar.setCUserId(param.getId());
							if (wxCUserCarMapper.countList(wxCUserCar) > 0) {
								resList = assignTypeId11(user);
							}
						}
					}
				}
				break;
				default:
					return null;

			}
		}catch (Exception e) {
			logger.error("triggerAssignTags Failed:" + trigger.getMessage() + e.getMessage());
		}

		return resList;
	}

	@Override
	public void updateTagByUserId(Long cUserId, List<Long> tags) {
		WxCUserBasicInfo wxCUserBasicInfo = wxCUserBasicInfoMapper.selectById(cUserId);
		WxCUserTags userTags = getById(wxCUserBasicInfo.getTagId());
		List<Long> tagList = JSONArray.parseArray(userTags.getTags(), Long.class);
        //先从现有标签中查看用户是否有 服饰尺码 和 鞋码 类别 有 删除
        Long tagId = 0L;
        WxTags wxTags = new WxTags();
        wxTags.setTypeId(EnumTagType.ID_27.getCode());
        tagId = getTagId(tagList, tagId, wxTags);
        if (!tagId.equals(0L)) {
            tagList.remove(tagId);
        }
        wxTags.setTypeId(EnumTagType.ID_28.getCode());
        tagId = getTagId(tagList, tagId, wxTags);
        if (!tagId.equals(0L)) {
            tagList.remove(tagId);
        }
        //添加新的标签
        tagList.addAll(tags);
        String tagStr = JSONArray.toJSONString(tagList);
		userTags.setTags(tagStr);
		userTags.setUpdateDate(new Date());
		wxCUserTagsMapper.updateById(userTags);
	}

    public Long getTagId(List<Long> tagList, Long id, WxTags wxTags) {
        List<WxTags> list = wxTagsMapper.findList(wxTags);
        for (WxTags tag : list) {
            boolean flag = false;
            for (Long tagId : tagList) {
                if (tag.getId().equals(tagId)) {
                    id = tagId;
                    flag = true;
                    break;
                }
            }
            if (flag) {
                break;
            }
        }
        return id;
    }


}
