package com.cftech.mp.fans.controller;

import com.alibaba.fastjson.JSONObject;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.*;
import com.cftech.mp.fans.model.Fanssgroup;
import com.cftech.mp.fans.model.MpFanssEntity;
import com.cftech.mp.fans.service.FanssgroupService;
import com.cftech.mp.fans.service.MpFanssService;
import com.cftech.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.mp.api.core.exception.WexinReqException;
import org.mp.api.core.req.model.user.BatchUserTag;
import org.mp.api.wxuser.tag.JwTagAPI;
import org.mp.api.wxuser.user.JwUserAPI;
import org.mp.api.wxuser.user.model.Wxuser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 *
 * @author lisw
 *
 */
@Controller
@RequestMapping(value = "/a/managefanss")
public class MpFanssController {

	private static Logger logger = LoggerFactory
			.getLogger(MpFanssController.class);

	@Autowired
	private MpFanssService mpAccountsService;
	@Autowired
	private MpAccountsService mpAccountService;

	@Autowired
	private FanssgroupService fanssGroupService;

	@Autowired
	private MpTokenUtil tokenUtil;


	// 管理后台用户列表
	@RequestMapping(value = "/fansslist",method = {RequestMethod.POST,RequestMethod.GET})
	public String useradd(HttpServletRequest request,
			HttpServletResponse response, MpFanssEntity mpFanssEntity,
			String areaname, String startTime, String endTime, Model model) {
		model.addAttribute("areaname", areaname);
		model.addAttribute("startTime", startTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("mpFanssEntity", mpFanssEntity);
		return "managefans/fansslist";
	}

	// 管理后台用户列表
	@RequestMapping(value = "/accountsaddform",method = {RequestMethod.POST,RequestMethod.GET})
	public String accountsaddform(HttpServletRequest request,
			HttpServletResponse response) {
		return "manageaccounts/accountsadd";
	}

	// 获取数据
	@RequestMapping(value = "/fanss/fetchdata",method = {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public JSONObject getUsers(int iDisplayStart, int iDisplayLength,
			HttpServletResponse response, HttpServletRequest request,
			String areaname, String startTime, String endTime,
			MpFanssEntity mpFanssEntity) {
		Long id = UserUtils.getmpaccounts(request);
		Sort sort = new Sort("subscribetime", OrderType.DESC);
		Conds conds = new Conds();
		if (StringUtils.isNotBlank(mpFanssEntity.getSource())) {
			conds.equal("source", mpFanssEntity.getSource());
		}
		if (StringUtils.isNotBlank(mpFanssEntity.getNickname())) {
			conds.like("nickname", mpFanssEntity.getNickname());
		}
		if (StringUtils.isNotBlank(startTime)) {
			conds.greatEqual("subscribetime", startTime);
		}
		if (StringUtils.isNotBlank(endTime)) {
			conds.lessEqual("subscribetime", endTime);
		}
		conds.equal("mpaccountid", id);
		conds.equal("delflag", Constants.DEL_FLAG_0);
		JSONObject returnObj = new JSONObject();
		List<MpFanssEntity> users = null;
		int userCounts = 0;
		if (StringUtils.isNoneBlank(areaname)) {
			users = mpAccountsService.fetchSearchByPage(conds, sort,
					iDisplayStart, iDisplayLength, areaname);
			userCounts = mpAccountsService.count(conds, areaname);
		} else {
			users = mpAccountsService.fetchSearchByPage(conds, sort,
					iDisplayStart, iDisplayLength);
			userCounts = mpAccountsService.count(conds);
		}
		returnObj.put("iTotalRecords", userCounts);
		returnObj.put("iTotalDisplayRecords", userCounts);
		returnObj.put("aaData",users);
		return returnObj;
//		OutputJSONUtil.convertoJSONStream(response, returnObj.toString());
	}

	// 粉丝列表导出
	@RequestMapping(value = "/fanss/export",method = {RequestMethod.POST,RequestMethod.GET})
	public void export(HttpServletResponse response,
			HttpServletRequest request, MpFanssEntity mpFanssEntity,
			String areaname, String startTime, String endTime) {
		Long id = UserUtils.getmpaccounts(request);
		Sort sort = new Sort("t.subscribetime", OrderType.DESC);
		Conds conds = new Conds();
		if (StringUtils.isNotBlank(mpFanssEntity.getNickname())) {
			conds.like("t.nickname", mpFanssEntity.getNickname());
		}
		if (StringUtils.isNotBlank(startTime)) {
			conds.greatEqual("t.subscribetime", startTime);
		}
		if (StringUtils.isNotBlank(endTime)) {
			conds.lessEqual("t.subscribetime", endTime);
		}
		conds.equal("mpaccountid", id);
		conds.equal("delflag", Constants.DEL_FLAG_0);
		try {
			List<MpFanssEntity> users = null;
			if (StringUtils.isNoneBlank(areaname)) {
				users = mpAccountsService.fetchSearchByPageStore(conds, sort, 0, 0,
						areaname);
			} else {
				users = mpAccountsService.fetchSearchByPageStore(conds, sort, 0, 0,
						null);
			}
			// 参数
			ExcelUtils.export(request, response,
					"粉丝列表-" + DateUtils.formatDate(new Date(), "yyyy-MM-dd"),
					users, "fans");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 修改账户
	@RequestMapping(value = "/updateaccounts",method = {RequestMethod.POST})
	public JSONObject updateaccounts(MpFanssEntity accounts,
			HttpServletResponse response) {
		JSONObject returnObj = new JSONObject();
		accounts.setUpdatetime(new Date());
		returnObj.put("errorCode", 0);
		mpAccountsService.updateByPrimaryKey(accounts);
//		OutputJSONUtil.convertoJSONStream(response, returnObj.toString());
		return returnObj;
	}

	// 修改账户
	@RequestMapping(value = "/deleteaccounts",method = {RequestMethod.POST})
	public JSONObject deleteaccounts(MpFanssEntity accounts,
			HttpServletResponse response) {
		JSONObject returnObj = new JSONObject();
		returnObj.put("errorCode", 0);
		mpAccountsService.deleteByPrimaryKey(accounts.getId());
//		OutputJSONUtil.convertoJSONStream(response, returnObj.toString());
		return returnObj;
	}


	// 获取详细信息
	@RequestMapping(value = "/getaccountdetail",method = {RequestMethod.POST,RequestMethod.GET})
	public String getaccountdetail(Long id, HttpServletResponse response,
			Model model) {
		MpFanssEntity accountsEntity = mpAccountsService.getDetail(id);
		model.addAttribute("accountsEntity", accountsEntity);
		return "manageaccounts/detail";
	}

	// 根据当前微信公众号， 同步所有用户
	@ResponseBody
	@RequestMapping(value = "/synAllFans",method = {RequestMethod.POST})
	public JSONObject synAllFans(HttpServletRequest request)
			throws WexinReqException {
		JSONObject rtnJosn = new JSONObject();
		try {
			Long id = UserUtils.getmpaccounts(request);

			String accessToken = tokenUtil.getToken(id);
			// 根据账号查询所有粉丝
			if (id != null) {
				List<Wxuser> users = JwUserAPI.getAllWxuser(accessToken, null);// 得到微信官方实际的关注粉丝
				MpFanssEntity fannsIsexits = null;
				List<String> fanssList = mpAccountsService.getAllWxUser(id
						.toString());
				for (Wxuser user : users) {
					try {
						MpFanssEntity fannsEntity = new MpFanssEntity();
						fannsEntity.setHeadimgurl(user.getHeadimgurl());
						fannsEntity.setCity(user.getCity());
						fannsEntity.setProvince(user.getProvince());
						fannsEntity.setNickname(user.getNickname());
						fannsEntity.setMpaccountid(id);
						fannsEntity.setOpenid(user.getOpenid());
						fannsEntity.setSex(user.getSex());
						fannsEntity.setSubscribetime(new Date(Long
								.parseLong(user.getSubscribe_time()) * 1000));
						fannsEntity.setUnionid(user.getUnionid());
						String tags = "";
						if(user.getTagid_list()!=null && user.getTagid_list().size()>0){
							tags=StringUtils.join(user.getTagid_list(), ",")+",";
						}
						fannsEntity.setTaglist(tags);
						fannsIsexits = mpAccountsService.getWxUser(user.getOpenid());
						if (fannsIsexits != null) {// 修改
							mpAccountsService.updateByOpenId(fannsEntity);
							fanssList.remove(user.getOpenid());
						} else {// 插入
							fannsEntity.setSource("0");
							mpAccountsService.insert(fannsEntity);
							fanssList.remove(user.getOpenid());
						}
					} catch (Exception e) {
						e.printStackTrace();
						logger.info(user.getNickname());
					}
				}
				// 如果存在取消关注的粉丝，则删除数据库中的粉丝
				if (fanssList != null && !fanssList.isEmpty()) {
					for (String s : fanssList) {
						mpAccountsService.deleteByOpenId(s);
					}
				}
			}
			rtnJosn.put("errorCode", 0);
		} catch (Exception e) {
			e.printStackTrace();
			rtnJosn.put("errorCode", 1);
		}
		return rtnJosn;
	}

	@RequestMapping(value="/batchFanss",method=RequestMethod.POST)
	@ResponseBody
	public JSONObject batchFanss(MultipartFile file,HttpServletRequest request){
		JSONObject rtnJson = new JSONObject();
		StringBuffer errorBuffer = new StringBuffer();
		if(file!=null){
			try {
				List<List<Object>> list = ImportExcelUtil.getBankListByExcel(file.getInputStream(),file.getOriginalFilename());
				for(int i =0;i<list.size();i++){
					List<Object> objList = list.get(i);
					String openId=null;
					String tag=null;
					if(objList==null || objList.size()==0)errorBuffer.append("第"+(i+1)+"条数据为空");
					if(objList.get(0)==null || StringUtils.isBlank(objList.get(0).toString())){//openid为空
						errorBuffer.append("第"+(i+1)+"条数据,粉丝openId为空");
						continue;
					}else{
						openId=objList.get(0).toString();
					}
					if(objList.get(1)==null || StringUtils.isBlank(objList.get(1).toString())){//标签为空
						errorBuffer.append("第"+(i+1)+"条数据,标签为空");
						continue;
					}else{
						tag=objList.get(1).toString();
					}
					String [] newtags = tag.split(",");//新标签
					Conds fanssConds = new Conds();
					fanssConds.equal("delflag", 0);
					fanssConds.equal("openid", openId);
					fanssConds.equal("mpaccountid", UserUtils.getmpaccounts(request));
					MpFanssEntity fanss=mpAccountsService.fetchSearchByConds(fanssConds);
					if(fanss!=null){
						if(fanss.getTaglist()==null){
							fanss.setTaglist("");
						}
						String [] tags = fanss.getTaglist().split(",");//此粉丝旧标签
						Conds conds = new Conds();
						conds.equal("delflag", 0);
						conds.equal("accountsid", UserUtils.getmpaccounts(request));
						conds.in("name", newtags);
						List<Fanssgroup> groupList =  fanssGroupService.fetchSearchByPage(conds, null, 0, 0);
						String groups="";
						for(Fanssgroup g : groupList){
							groups+=g.getGroupid()+",";
						}
						if((tags.length+newtags.length)>20){
	//						fanss.setTaglist(groups);
							errorBuffer.append("第"+(i+1)+"条数据,粉丝标签超过20，openId为:"+openId);
							continue;
						}else{//如果此粉丝标签加上本次的新标签未超过20个,追加旧标签
							groups=fanss.getTaglist()+groups;
						}
						List<String> result = Arrays.asList(groups.split(","));

						Set<String> set = new HashSet<String>();
						set.addAll(result);
						groups = StringUtils.join(set, ",")+",";

						Map<String,Object> params = new HashMap<String, Object>();
						params.put("openid", openId);
						params.put("taglist", groups);
						params.put("accountsId", UserUtils.getmpaccounts(request));
						try {
							mpAccountsService.updateLabelByid(params);
							errorBuffer.append("第"+(i+1)+"条数据导入成功,openId:"+openId+",标签:"+tag);
						} catch (Exception e) {
							errorBuffer.append("第"+(i+1)+"条数据发生异常,异常信息:"+e.getMessage());
							continue;
						}
					}else{
						errorBuffer.append("第"+(i+1)+"条数据,OpenId为找到粉丝信息");
					}
					//fanssGroupService
				}
				System.out.println(list);
			} catch (IOException e) {
				rtnJson.put("errorNo","2");//未找到文件
				// TODO Auto-generated catch block
				e.printStackTrace();
				return rtnJson;
			} catch (Exception e) {
				rtnJson.put("errorNo","2");//未找到文件
				// TODO Auto-generated catch block
				e.printStackTrace();
				return rtnJson;
			}
		}else{
			rtnJson.put("errorNo","2");//未找到文件
			return rtnJson;
		}
		rtnJson.put("errorNo","0");
		rtnJson.put("errorMsg", "导入成功");
		logger.info(errorBuffer.toString());
		return rtnJson;
	}

//
//    @RequestMapping(value = "/batchFanssNew", method = RequestMethod.POST)
//    @ResponseBody
//    public JSONObject batchFanss(MultipartFile file, HttpServletRequest request) {
//        JSONObject rtnJson = new JSONObject();
//        StringBuffer errorBuffer = new StringBuffer();
//        Map<Long, List<String>> submitFanss = new HashMap<Long, List<String>>();
//        Map<String, Long> tagsMap = new HashMap<String, Long>();
//        if (file != null) {
//            try {
//                List<List<Object>> list = ImportExcelUtil.getBankListByExcel(file.getInputStream(), file.getOriginalFilename());
//                for (int i = 0; i < list.size(); i++) {
//                    List<Object> objList = list.get(i);
//                    String openId = null;
//                    String tag = null;
//                    if (objList == null || objList.size() == 0) errorBuffer.append("第" + (i + 1) + "条数据为空");
//                    if (objList.get(0) == null || StringUtils.isBlank(objList.get(0).toString())) {//openid为空
//                        errorBuffer.append("第" + (i + 1) + "条数据,粉丝openId为空");
//                        continue;
//                    } else {
//                        openId = objList.get(0).toString();
//                    }
//                    if (objList.get(1) == null || StringUtils.isBlank(objList.get(1).toString())) {//标签为空
//                        errorBuffer.append("第" + (i + 1) + "条数据,标签为空");
//                        continue;
//                    } else {
//                        tag = objList.get(1).toString();
//                    }
//                    String[] newtags = tag.split(",");//新标签
//                    for(String str : newtags){
//                        if(!tagsMap.containsKey(str)){
//                            Conds conds = new Conds();
//                            conds.equal("delflag", 0);
//                            conds.equal("accountsid", UserUtils.getmpaccounts(request));
//                            conds.equal("name", str);
//                            Fanssgroup fanssgroup =  fanssGroupService.fetchSearchByConds(conds);
//                            if(fanssgroup!=null){
//                                tagsMap.put(str,fanssgroup.getGroupid());
//                            }
//                        }else{
//                            Long tagId = tagsMap.get(str);
//                            if(submitFanss.containsKey(tagsMap.get(str))){
//                               List<String> openIds = submitFanss.get(tagId);
//                                openIds.add(openId);
//                                submitFanss.put(tagId, openIds);
//                               if(openIds.size()==50){
//                                 Integer result =  mpAccountsService.updateBatchLabelByTags((String [])openIds.toArray(),UserUtils.getmpaccounts(request),tagId.intValue());
//                                 if(result==0){
//                                     openIds = new ArrayList<String>();
//                                     submitFanss.put(tagId, openIds);
//                                 }else{
//
//                                 }
//                               }
//                            }else{
//                                submitFanss.put(tagId,new ArrayList<>());
//                            }
//                        }
//                    }
//                }
//                System.out.println(list);
//            } catch (IOException e) {
//                rtnJson.put("errorNo", "2");//未找到文件
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//                return rtnJson;
//            } catch (Exception e) {
//                rtnJson.put("errorNo", "2");//未找到文件
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//                return rtnJson;
//            }
//        } else {
//            rtnJson.put("errorNo", "2");//未找到文件
//            return rtnJson;
//        }
//        rtnJson.put("errorNo", "0");
//        rtnJson.put("errorMsg", "导入成功");
//        logger.info(errorBuffer.toString());
//        return rtnJson;
//    }

	//改变粉丝标签
	@RequestMapping(value = "/editlabel",method = {RequestMethod.POST})
	@RequiresPermissions(value = PermissionSign.FANSS_EDIT)
	@ResponseBody
	public JSONObject addlabel(HttpServletRequest request,
			HttpServletResponse response, Model model,String taglist,Long id){
		JSONObject result = new JSONObject();
		result.put("errorNo",1);
		Map<String,Object> map = new HashMap<String, Object>();
		Long accountsId = UserUtils.getmpaccounts(request);
		map.put("taglist", taglist+",");
		map.put("accountsId", accountsId);
		//String openid = mpAccountsService.findopenidById(id);
		MpFanssEntity fanssEntity = mpAccountsService.getDetail(id);
//		if(fanssEntity.getTaglist()!=null){
//			String [] tags = fanssEntity.getTaglist().split(",");
//			for(String str : tags){
//				if(StringUtils.isNotBlank(str)){
//					BatchUserTag batchUserTag = new BatchUserTag();
//					batchUserTag.setOpenid_list(new String[]{fanssEntity.getOpenid()});
//					batchUserTag.setTagid(Integer.valueOf(str));
//					JwTagAPI.batchunTagging(batchUserTag, tokenUtil.getToken(UserUtils.getmpaccounts(request)));
//				}
//			}
//		}
		map.put("openid", fanssEntity.getOpenid());
		try {
			if(fanssEntity.getOpenid()!=null){
				boolean flag = mpAccountsService.updateLabelByid(map);
				if(flag){
					result.put("errorNo",0);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("errorNo",1);
		}
		return result;
	}
}
