package com.community.huiju.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.community.commom.mode.ResponseBean;
import com.community.commom.session.UserElement;
import com.community.huiju.dao.*;
import com.community.huiju.model.*;
import com.community.huiju.service.ITransactionService;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 物业web端二手交易表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2018-12-29
 */
@Service
public class TransactionServiceImpl extends ServiceImpl<TpTransactionMapper, TpTransaction> implements ITransactionService {
	
	@Autowired
	private TpTransactionMapper tpTransactionMapper;
	
	@Autowired
	private TdImagesMapper tdImagesMapper;

	@Autowired
	private TransactionLikeMapper transactionLikeMapper;

	@Autowired
	private TransactionReportMapper transactionReportMapper;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private TransactionReplyMapper transactionReplyMapper;

	@Autowired
	private TaUserMapper taUserMapper;


	@Override
	public ResponseBean getTransactionList(String parameter,Integer communityId) {
		ResponseBean responseBean = new ResponseBean();
		JSONObject object= JSONObject.parseObject(parameter);
		String transactionTitle = object.getString("transactionTitle");
		String userName = object.getString("userName");
		Integer id = object.getInteger("id");
		String status = object.getString("status");
		Integer pageNum = object.getInteger("pageNum");
		Integer pageSize = object.getInteger("pageSize");
		Page<TpTicket> page = new Page<>();
		page.setSize(pageSize == null ? 10 : pageSize);
		page.setCurrent(pageNum == null ? 1 : pageNum);
		// 分页查询
		List<TpTransaction> list = tpTransactionMapper.selectListByParams(page,transactionTitle,userName,id,status,communityId);

		list = list.stream().map( e-> {

			QueryWrapper<TransactionLike> transactionLike= new QueryWrapper<>();
			transactionLike.eq("transaction_id",e.getId());
			transactionLike.eq("like_status",2);
			//不喜欢的总数
			 Integer transactionLikeCount= transactionLikeMapper.selectCount(transactionLike);
			e.setTransactionNoLikeSum(transactionLikeCount);

			QueryWrapper<TransactionReport> TransactionReport= new QueryWrapper<>();
			TransactionReport.eq("transaction_id",e.getId());
			Integer TransactionReportCount= transactionReportMapper.selectCount(TransactionReport);
			e.setReportSum(TransactionReportCount);

			return e;
		}).collect(Collectors.toList());
		Map<String, Object> map = Maps.newHashMap();
		map.put("list",list);
		map.put("total",page.getTotal());
		map.put("pageNum", page.getCurrent());
		map.put("pageSize", page.getSize());
		responseBean.addSuccess(map);
		return responseBean;
	}
	
	/**
	 * 获取交易信息详情
	 *
	 * @param id
	 * @return
	 */
	@Override
	public ResponseBean getTransactionInfo(Integer id) {
		ResponseBean responseBean = new ResponseBean();
		TpTransaction tpTransaction = tpTransactionMapper.selectById(id);
		//查询回复总数
		QueryWrapper<TransactionReply> transactionReply= new QueryWrapper<>();
		transactionReply.eq("transaction_id",tpTransaction.getId());
		transactionReply.eq("community_id",tpTransaction.getCommunityId());
		Integer report= transactionReplyMapper.selectCount(transactionReply);
		tpTransaction.setReplySum(report);

		QueryWrapper<TdImages> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("uuid", id);
		queryWrapper.eq("type", "transaction");
		List<TdImages> imagesList = tdImagesMapper.selectList(queryWrapper);
		// 转换, 只保留 imageUrl 字段·
		List<String> stringList = imagesList.stream().map(e->new String(e.getImageUrl())).collect(Collectors.toList());
		Map<String,Object> map = Maps.newHashMap();
		map.put("tpTransaction",tpTransaction);
		map.put("list",stringList);
		responseBean.addSuccess(map);
		return responseBean;
	}
	
	/**
	 * 作废二手交易
	 *
	 * @param id
	 * @return
	 */
	@Override
	public ResponseBean updateTransactionById(Integer id,Integer userId) {
		ResponseBean responseBean = new ResponseBean();
		TpTransaction tpTransaction = new TpTransaction();
		tpTransaction.setId(id);
		tpTransaction.setStatus("0");
		tpTransaction.setUpdateUser(userId);
		tpTransaction.setUpdateDate(LocalDateTime.now());
		int count = tpTransactionMapper.updateById(tpTransaction);
		if (count > 0){
			responseBean.addSuccess(count);
			return responseBean;
		}
		responseBean.addError("作废出错");
		return responseBean;
	}

	@Override
	public ResponseBean transactionsAdd(String paramets, Integer communityId, Integer id) {
		ResponseBean response = new ResponseBean();

		JSONObject jsonobject = JSONObject.parseObject(paramets);

		TpTransaction tpTransaction = JSONObject.parseObject(paramets, TpTransaction.class);
		tpTransaction.setCommunityId(communityId);
		tpTransaction.setTaUserId(userMapper.selectById(id).getTaUserId());
		tpTransaction.setCreateDate(LocalDateTime.now());
		// 必须与ta_user表的id数据同步。
		tpTransaction.setCreateUser(userMapper.selectById(id).getTaUserId());
		tpTransaction.setViewCount(0);
		tpTransaction.setIsReported("0");
		tpTransaction.setReleaseIdentity("1");
		tpTransactionMapper.insert(tpTransaction);
		JSONArray contentImg = jsonobject.getJSONArray("contentImg");

		String[] contentImgArray = contentImg.toArray(new String[]{});
		if (tpTransaction.getTransactionTitle() == null) {
			response.addError("标题不能为空");
			return response;
		}
		if (null == tpTransaction.getTransactionContent() && null == contentImg) {
			response.addError("内容和图片必须填一个");
			return response;
		}
		for (String img : contentImgArray) {
			TdImages tdImages = new TdImages();
			tdImages.setImageUrl(img);
			tdImages.setType("transaction");
			tdImages.setUuid(tpTransaction.getId());
			tdImages.setCreateTime(LocalDateTime.now());
			tdImages.setCreateUser(id);
			tdImagesMapper.insert(tdImages);
		}
		return response;

	}

	@Override
	public ResponseBean transactionsUpdata(String paramets, Integer communityId, Integer id) {
		ResponseBean response = new ResponseBean();

		JSONObject jsonobject = JSONObject.parseObject(paramets);

		TpTransaction tpTransaction = JSONObject.parseObject(paramets, TpTransaction.class);
		tpTransaction.setCommunityId(communityId);
		tpTransaction.setTaUserId(userMapper.selectById(id).getTaUserId());
		tpTransaction.setUpdateDate(LocalDateTime.now());
		// 必须与ta_user表的id数据同步。
		tpTransaction.setUpdateUser(userMapper.selectById(id).getTaUserId());
		tpTransactionMapper.updateById(tpTransaction);
		JSONArray contentImg = jsonobject.getJSONArray("contentImg");

		String[] contentImgArray = contentImg.toArray(new String[]{});
		if (tpTransaction.getTransactionTitle() == null) {
			response.addError("标题不能为空");
			return response;
		}
		if (null == tpTransaction.getTransactionContent() && null == contentImg) {
			response.addError("内容和图片必须填一个");
			return response;
		}
		//修改图片时删除原来图片
		QueryWrapper<TdImages> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(TdImages::getUuid, tpTransaction.getId());
		queryWrapper.lambda().eq(TdImages::getType, "transaction");
		tdImagesMapper.delete(queryWrapper);

		for (String img : contentImgArray) {
			TdImages tdImages = new TdImages();
			tdImages.setImageUrl(img);
			tdImages.setType("transaction");
			tdImages.setUuid(tpTransaction.getId());
			tdImages.setCreateTime(LocalDateTime.now());
			tdImages.setCreateUser(id);
			tdImagesMapper.insert(tdImages);
		}
		return response;
	}

	@Override
	public ResponseBean transactionsDelete(String paramets, Integer communityId, Integer userId) {
		ResponseBean response = new ResponseBean();
		JSONObject parseObject = JSONObject.parseObject(paramets);

		JSONArray tpTransactionIdId = parseObject.getJSONArray("id");
		Integer[] announcementIdArray = tpTransactionIdId.toArray(new Integer[]{});
		for (Integer id : announcementIdArray) {
			TpTransaction tpTransaction = new TpTransaction();
			tpTransaction.setId(id);
			tpTransaction.setStatus("0");
			tpTransaction.setUpdateDate(LocalDateTime.now());
			tpTransaction.setUpdateUser(userId);
			tpTransactionMapper.updateById(tpTransaction);
//			//1.5版本维护消息
//			Message message= new Message();
//			message.setStatus("0");
//			message.setAnnouncementId(id);
//			message.setUpdateUser(userId);
//			message.setUpdateDate(LocalDateTime.now());
//			tdImagesMapper.updateMessage(message);
		}
		response.addSuccess("成功");
		return response;
	}

	@Override
	public ResponseBean transactionReplyList(String paramets, Integer communityId, Integer userID) {
		ResponseBean responseBean = new ResponseBean();
		JSONObject object= JSONObject.parseObject(paramets);
		Integer transactionId = object.getInteger("id");
		/*回复*/
		String replyTaUserName = object.getString("replyTaUserName");
		/*被回复*/
		String taUserName = object.getString("taUserName");
		Integer status = object.getInteger("status");
		Date createDate = object.getDate("createDate");

		Integer pageNum = object.getInteger("pageNum");
		Integer pageSize = object.getInteger("pageSize");
		Page<TransactionReply> page = new Page<>();
		page.setSize(pageSize == null ? 10 : pageSize);
		page.setCurrent(pageNum == null ? 1 : pageNum);
		// 获得aap的id
		Integer taUserId= userMapper.selectById(userID).getTaUserId();
		// 分页查询
		List<TransactionReply> TransactionReplylList = transactionReplyMapper.transactionReplyList(page,transactionId,taUserId,status,taUserName,createDate,replyTaUserName);
		//查询帖子评论所带图片

		for (TransactionReply transactionReply:TransactionReplylList){
			QueryWrapper<TdImages> tdImagesList = new QueryWrapper<>();
			tdImagesList.eq("uuid",transactionReply.getId());
			tdImagesList.eq("type","reply");
			List<TdImages> tdImages= tdImagesMapper.selectList(tdImagesList);
			List<String> list= new ArrayList<>();
			for (TdImages imageUrl:tdImages){
				list.add(imageUrl.getImageUrl());
				transactionReply.setTdImagesLists(list);
			}

		}

		Map<String, Object> map = Maps.newHashMap();
		map.put("list",TransactionReplylList);
		map.put("total",page.getTotal());
		map.put("pageNum", page.getCurrent());
		map.put("pageSize", page.getSize());
		responseBean.addSuccess(map);
		return responseBean;
	}

	@Override
	public ResponseBean deleteReply(String paramets) {
		ResponseBean responseBean= new ResponseBean();
		 JSONObject object= JSONObject.parseObject(paramets);
	 	JSONArray array= object.getJSONArray("id");
	 	Integer[]	reply= array.toArray(new Integer[]{});
	 	for (Integer id:reply){
			transactionReplyMapper.deleteById(id);
		}
	 	responseBean.addSuccess("成功");
		return responseBean;
	}

	@Override
	public ResponseBean transactionReplyAdd(String paramets, UserElement userElement) {
		ResponseBean response= new ResponseBean();
		 JSONObject object= JSONObject.parseObject(paramets);
		 Integer id= object.getInteger("id");
		 String replyContent= object.getString("replyContent");
		 JSONArray array= object.getJSONArray("contentImg");
		// 根据此状态判断是回复帖子，还是回复人(共用一个接口)
		Integer replyType= object.getInteger("replyType")==null?0:1;

		 // 查询帖子信息
		TpTransaction tpTransaction= tpTransactionMapper.selectById(id);
		// 查询评论信息
		TransactionReply  Reply= transactionReplyMapper.selectById(id);
		TransactionReply transactionReply= new TransactionReply();
		// 查询回复的ta_userID
		 User user= userMapper.selectById(userElement.getId());
		int Type=replyType.intValue();
		if (Type==1) {
			transactionReply.setCommunityId(userElement.getCommunityId())
					.setTransactionId(id)
					.setTaUserId(user.getTaUserId())
					.setTaUserName(userElement.getUserName())
					.setReplyContent(replyContent)
					.setReplyTaUserId(tpTransaction.getCreateUser())
					.setReleaseIdentity("1")
					.setReplyTaUserName(taUserMapper.selectById(tpTransaction.getTaUserId()).getUserName())
					.setCreateDate(LocalDateTime.now());
		}
		if (Type!=1) {
			transactionReply.setCommunityId(userElement.getCommunityId())
					.setTransactionId(Reply.getTransactionId())
					.setTaUserId(userElement.getId())
					.setTaUserName(userElement.getUserName())
					.setReplyContent(replyContent)
					.setReplyTaUserId(Reply.getTaUserId())
					.setReleaseIdentity("1")
					.setReplyTaUserName(Reply.getTaUserName())
					.setCreateDate(LocalDateTime.now());
		}
		transactionReplyMapper.insert(transactionReply);
		String[] replyImg = array.toArray(new String[]{});
		for (String img:replyImg){
			 TdImages tdImages= new TdImages();
			tdImages.setImageUrl(img);
			tdImages.setType("reply");
			tdImages.setUuid(transactionReply.getId());
			tdImages.setCreateTime(LocalDateTime.now());
			tdImages.setCreateUser(userElement.getId());
			tdImagesMapper.insert(tdImages);
		}
		response.addSuccess("成功");
		return response;
	}

	@Override
	public ResponseBean transactionReportList(String paramets, UserElement userElement) {
		ResponseBean response= new ResponseBean();
			JSONObject object= JSONObject.parseObject(paramets);
			String reportUserNmae= object.getString("reportUserNmae");
			String reportPhone= object.getString("reportPhone");
			Integer transactionId= object.getInteger("transactionId");

			Integer pageNum = object.getInteger("pageNum");
			Integer pageSize = object.getInteger("pageSize");
			Page<TransactionReport> page = new Page<>();
			page.setSize(pageSize == null ? 10 : pageSize);
			page.setCurrent(pageNum == null ? 1 : pageNum);
			// 分页查询
			List<TransactionReport> list = transactionReportMapper.transactionReportList(page,reportUserNmae,reportPhone,transactionId);

			Map<String, Object> map = Maps.newHashMap();
			map.put("list",list);
			map.put("total",page.getTotal());
			map.put("pageNum", page.getCurrent());
			map.put("pageSize", page.getSize());
			response.addSuccess(map);
			return response;
	}
}
