package com.cftech.mp.fans.service.impl;

import com.cftech.core.feature.orm.mybatis.Page;
import com.cftech.core.generic.GenericDao;
import com.cftech.core.generic.GenericServiceImpl;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.mp.fans.dao.MpFanssMapper;
import com.cftech.mp.fans.model.MpFanssEntity;
import com.cftech.mp.fans.service.MpFanssService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.mp.api.core.req.model.user.BatchUserTag;
import org.mp.api.core.req.model.user.TagOperate;
import org.mp.api.wxuser.tag.JwTagAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MpFanssServiceImpl extends GenericServiceImpl<MpFanssEntity>
		implements MpFanssService {

	@Autowired
	private MpFanssMapper accountsMapper;

	@Autowired
	private MpTokenUtil tokenUtil;


	@Override
	public List<MpFanssEntity> getMpFans(Long userid) {
		return accountsMapper.getMpFans(userid);
	}


	@Override
	public long insert(MpFanssEntity model) {
		long fansId = accountsMapper.insert(model);
		return fansId;
	}

	@Override
	public void updateByPrimaryKey(MpFanssEntity mpAccounts) {
		accountsMapper.updateByPrimaryKey(mpAccounts);
	}

	@Override
	public int deleteByPrimaryKey(Long id) {
		return accountsMapper.deleteByPrimaryKey(id);
	}

	@Override
	public MpFanssEntity getDetail(Long id) {
		return accountsMapper.getDetail(id);
	}

	@Override
	public List<MpFanssEntity> getAllMpAccounts() {
		return null;
	}

	@Override
	public List<MpFanssEntity> getMpFansAndPage(Page<MpFanssEntity> page,
			@Param("userid") Long userid) {
		return accountsMapper.getMpFansAndPage(page, userid);
	}

	@Override
	public Long selectFannscounts(Long userid) {
		return accountsMapper.selectFannscounts(userid);
	}

	@Override
	protected GenericDao<MpFanssEntity> getGenericMapper() {
		return accountsMapper;
	}


	@Override
	public MpFanssEntity getWxUser(String openid) {
		return accountsMapper.getWxUser(openid);
	}


	@Override
	public void updateByOpenId(MpFanssEntity mpAccounts) {
		accountsMapper.updateByOpenId(mpAccounts);
	}


	@Override
	public List<String> getAllWxUser(String AccountId) {
		return accountsMapper.getAllWxUser(AccountId);
	}


	@Override
	public int deleteByOpenId(String openid) {
		return accountsMapper.deleteByOpenId(openid);
	}


	@Override
	public List<String> fannsByArea(String areaName,String accountsid,String sex,String tags,String storeIds) {
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("areaName",areaName);
		params.put("accountsid",accountsid);
		params.put("tags",tags);
		params.put("storeIds",storeIds);
		return accountsMapper.fannsByArea(params);
	}


	@Override
	public List<MpFanssEntity> fetchSearchByPage(Conds conds, Sort sort,
												 int iDisplayStart, int iDisplayLength, String areaname) {
		 Map<String, Object> params = new HashMap<String, Object>();
	        params.put("conds", conds);
	        params.put("offset", iDisplayStart > 0 ? iDisplayStart : 0);
	        params.put("limit", iDisplayLength > 0 ? iDisplayLength : 0);
	        params.put("sort", sort);
	        params.put("areaname", "%"+areaname+"%");
	        return getGenericMapper().fetchSearchByPage(params);
	}


	@Override
	public int count(Conds conds, String areaname) {
		 Map<String, Object> params = new HashMap<String, Object>();
	        params.put("conds", conds);
	        params.put("areaname", "%"+areaname+"%");
	        return getGenericMapper().count(params);
	}


	@Override
	public List<MpFanssEntity> fetchSearchByPageStore(Conds conds, Sort sort, int page, int pageSize,String areaName) {
		   Map<String, Object> params = new HashMap<String, Object>();
	        params.put("conds", conds);
	        params.put("offset", page > 0 ? page : 0);
	        params.put("limit", pageSize > 0 ? pageSize : 0);
	        params.put("sort", sort);
			if(StringUtils.isNoneBlank()){
				params.put("areaname", "%"+areaName+"%");
			}else{
				params.put("areaname", null);
			}

	        return accountsMapper.fetchSearchByPageStore(params);
	}


	@Override
	public boolean updateLabelByid(Map<String, Object> params) {
		BatchUserTag but=new BatchUserTag(); 
		String openid=(String) params.get("openid");
		String[] openids = {openid};
		if(params.get("taglist")!=null && StringUtils.isNotBlank(params.get("taglist").toString())){
			String taglist = (String) params.get("taglist");
//			String taglist="109";
			String[] taglistarray=taglist.split(",");
			Long accountsid=(Long) params.get("accountsId");
			//查询access_token
			String mae=tokenUtil.getToken(accountsid);
			for (String string : taglistarray) {
				but.setOpenid_list(openids);
				but.setTagid(Integer.parseInt(string));
				TagOperate to=JwTagAPI.batchTagging(but,mae);
				/**
				 * 返回编码
				 * -1		系统繁忙
				 * 45157	标签名非法，请注意不能和其他标签重名
				 * 45158	标签名长度超过30个字节
				 * 45058	不能修改0/1/2这三个系统默认保留的标签
				 */
				Integer[] errcodes={-1,45157,45158,45058};
				boolean b=Arrays.asList(errcodes).contains(to.getErrcode());
				if(b){
					throw new NullPointerException("");
				}
			}
			return accountsMapper.updateLabelByid(params);
		} 
		return false;
	}

	@Override
	public String findopenidById(Long id) {
		// TODO Auto-generated method stub
		return accountsMapper.findopenidById(id);
	}

	@Override
	public Integer updateBatchLabelByTags(String [] openIds, Long accountsId, Integer tagsId) {
		String mae=tokenUtil.getToken(accountsId);
		BatchUserTag but=new BatchUserTag();
		but.setOpenid_list(openIds);
		but.setTagid(tagsId);
		TagOperate to=JwTagAPI.batchTagging(but,mae);
		/**
		 * 返回编码
		 * -1		系统繁忙
		 * 40032	每次传入的openid列表个数不能超过50个
		 * 45159	非法的标签
		 * 45059	有粉丝身上的标签数已经超过限制，即超过20个
		 * 40003	传入非法的openid
		 * 49003	传入的openid不属于此AppID
		 */
		Integer[] errcodes={-1,40032,45159,45059,40003,49003};
		boolean b=Arrays.asList(errcodes).contains(to.getErrcode());
		if(to.getErrcode()==0){
			Map<String,Object> params = new HashMap<>();
			params.put("tagId",tagsId);
			params.put("openIds",openIds);
		}
		return to.getErrcode();
	}
}
