package com.community.huiju.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.community.commom.constant.Constant;
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.ITaUserService;
import com.community.huiju.service.ImageServiceI;
import com.community.huiju.service.SocialServiceI;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import com.sun.org.apache.bcel.internal.generic.NEW;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.plaf.TabbedPaneUI;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author weichaochao
 * @Title: SocialServiceImpl
 * @date 2018/10/23
 */
@Service("SocialService")
@Transactional
public class SocialServiceImpl implements SocialServiceI {

    @Autowired
    private TpAnnouncementMapper tpAnnouncementMapper;

    @Autowired
    private TpSocialViewMapper tpSocialViewMapper;

    @Autowired
    private TpActivityMapper tpActivityMapper;

    @Autowired
    private TpCarouselSettingMapper tpCarouselSettingMapper;

    @Autowired
    private TpActivitySignupMapper tpActivitySignupMapper;

    @Autowired
    private TpTransactionMapper tpTransactionMapper;

    @Autowired
    private TaSysRoleMapper taSysRoleMapper;

    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private TaSysUserRoleMapper taSysUserRoleMapper;

    @Autowired
    private TpTicketRecordMapper tpTicketRecordMapper;

    @Autowired
    private TpTicketMapper tpTicketMapper;

    @Autowired
    private TdImagesMapper tdImagesMapper;

    @Autowired
    private TpUserMapper tpUserMapper;

    @Autowired
    private TpMessageMapper tpMessageMapper;

    @Autowired
    private SysReportReasonMapper sysReportReasonMapper;

    @Autowired
    private TpTransactionReportMapper tpTransactionReportMapper;

    @Autowired
    private ToCommunitiesMapper toCommunitiesMapper;

    @Autowired
    private TpTransactionReplyMapper tpTransactionReplyMapper;

    @Autowired
    private TpTransactionLikeMapper tpTransactionLikeMapper;

    @Autowired
    private TaUserVerifyMapper taUserVerifyMapper;

    @Autowired
    private TpBuildingOwnerInfoMapper tpBuildingOwnerInfoMapper;

    @Autowired
    private TpActivitySignInMapper tpActivitySignInMapper;

    @Autowired
    private ITaUserService iTaUserService;

    @Override
    @Transactional
    public TpAnnouncement findAnnouncementDetail(Integer id, Integer communityId, Integer userId) {
        //更新此用户的查看次数操作
        Integer allViewNum = updateSocialView(userId, Constant.ANNOUNCEMENT, communityId, id);
        if (null != allViewNum) {
            tpAnnouncementMapper.updateByPrimaryKeySelective(id, allViewNum);
        }
        TpAnnouncement tpAnnouncement = tpAnnouncementMapper.selectByPrimaryKey(id, communityId);
        tpAnnouncement.setUserName(tpUserMapper.selectByPrimaryKey(tpAnnouncement.getCreateUser()).getUserName());

        Map<String, Object> map = Maps.newHashMap();
        map.put("uuid", tpAnnouncement.getId());
        map.put("type", Constant.ANNOUNCEMENT);
        // 查询图片
        List<TdImages> tdImagesList = tdImagesMapper.getByUUIDAndByType(map);
        List<String> imgList = tdImagesList.stream().map(e -> new String(e.getImageUrl())).collect(Collectors.toList());
        tpAnnouncement.setImgList(imgList);
        return tpAnnouncement;
    }

    /**
     * 分页获取公告列表
     *
     * @param communityId
     * @param title
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ResponseBean getAnnouncements(Integer communityId, String title, Integer pageNum, Integer pageSize) {
        ResponseBean responseBean = new ResponseBean();
        Map<String, Object> parameter = Maps.newHashMap();
        //使用分页插件
        Page<TpAnnouncement> pageannouncementList = PageHelper.startPage(pageNum, pageSize);
        // 获取数据
        List<TpAnnouncement> announcementList = tpAnnouncementMapper.getAnnouncements(communityId, title);
        parameter.put("total", pageannouncementList.getTotal());
        parameter.put("list", announcementList);
        responseBean.addSuccess(parameter);
        return responseBean;
    }

    /**
     * 根据当前小区ID查出轮播图
     *
     * @param communityId 当前小区ID
     * @return
     */
    @Override
    public List<TpAnnouncement> getAnnouncement(Integer communityId) {
        Integer num = tpCarouselSettingMapper.getcarouselNum(Constant.ANNOUNCEMENT, communityId);
        if (null == num) {
            num = 0;
        }
        List<TpAnnouncement> listAnnouncement = tpAnnouncementMapper.getAnnouncement(communityId, num);
        return listAnnouncement;
    }


    /**
     * 分页获取活动列表
     *
     * @param communityId
     * @param title
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ResponseBean getActivitys(Integer communityId, String title, Integer pageNum, Integer pageSize) {
        ResponseBean responseBean = new ResponseBean();
        Map<String, Object> result = Maps.newHashMap();
        //使用分页插件
        Page<TpActivity> pageactivityList = PageHelper.startPage(pageNum, pageSize);
        // 获取数据
        List<TpActivity> activityList = tpActivityMapper.getActivitys(communityId, title);
        result.put("list", activityList);
        result.put("total", pageactivityList.getTotal());
        responseBean.addSuccess(result);
        return responseBean;
    }

    /**
     * 获取活动帖子详情
     *
     * @param activityId
     * @param communityId
     * @return
     */
    @Override
    public TpActivity findActivityDetail(Integer activityId, Integer communityId, Integer userId) {
        //更新查看次数
        Integer allViewNum = updateSocialView(userId, Constant.ACTIVITY, communityId, activityId);
        if (null != allViewNum) {
            TpActivity activity = new TpActivity();
            activity.setId(activityId);
            activity.setViewCount(allViewNum);
            tpActivityMapper.updateByPrimaryKeySelective(activity);
        }

        TpActivity tpActivity = tpActivityMapper.selectByPrimaryKey(activityId, communityId);
        TpUser tpUser = tpUserMapper.selectByPrimaryKey(tpActivity.getCreateUser());
        if (null != tpUser) {
            tpActivity.setUserName(tpUser.getUserName());
        }
        //查看当前人是否签到
        TpActivitySignIn tpActivitySignIn = tpActivitySignInMapper.selectSing(activityId, userId);
        Integer signType = tpActivitySignIn == null ? 0 : 1;
        tpActivity.setSignType(signType);

        //返回报名状态
        Integer signNum = tpActivitySignupMapper.findTpActivetitySignByUserId(tpActivity.getId(), communityId, userId);
        String signStatus = signNum != 0 ? Constant.STATUS_SIGNED : Constant.STATUS_UNSIGN;
        tpActivity.setSignStatus(signStatus);

        Map<String, Object> map = Maps.newHashMap();
        map.put("uuid", tpActivity.getId());
        map.put("type", Constant.ACTIVITY);
        // 查询图片
        List<TdImages> tdImagesList = tdImagesMapper.getByUUIDAndByType(map);
        List<String> imgList = tdImagesList.stream().map(e -> new String(e.getImageUrl())).collect(Collectors.toList());
        tpActivity.setImgList(imgList);

        return tpActivity;
    }

    /**
     * 更新此用户的查看次数操作
     *
     * @param userId
     * @param socialType
     * @param communityId
     * @param uuid
     */
    private Integer updateSocialView(Integer userId, String socialType, Integer communityId, Integer uuid) {
        //检查是否查看过这个帖子
        TpSocialView tpSocialView = new TpSocialView();
        tpSocialView.setTaUserId(userId);
        tpSocialView.setSocialType(socialType);
        tpSocialView.setCommunityId(communityId);
        tpSocialView.setUuid(uuid);
        Integer viewNum = tpSocialViewMapper.selectViewNum(tpSocialView);

        //查看过的话查看次数加一
        if (viewNum == 0) {
            tpSocialView.setCreateDate(new Date());
            tpSocialViewMapper.insertSelective(tpSocialView);
            tpSocialView.setTaUserId(null);
            Integer allViewNum = tpSocialViewMapper.selectViewNum(tpSocialView);
            return allViewNum;
        }
        return null;
    }

    @Override
    public ResponseBean findTaUserInfo(UserElement userElement, Integer activityId, Integer communityId, String remark) {
        ResponseBean responseBean = new ResponseBean();
        TpActivity tpActivity = tpActivityMapper.selectByPrimaryKey(activityId, communityId);
        //判断是否已经过了报名截至时间
        Date registrEndTime = tpActivity.getRegistrationEndTime();
        if (registrEndTime.compareTo(new Date()) < 0) {
            responseBean.addError("9997", "已过报名截止时间");
            return responseBean;
        }

        //报名是否超过人数上限
        Integer signUpNum = tpActivitySignupMapper.sumActivitySignUpNum(activityId, communityId);
        if (signUpNum >= tpActivity.getSignUpMax() && tpActivity.getSignUpMax().intValue() != 0) {
            responseBean.addError("9998", "报名人数已满");
            return responseBean;
        }

        //判断身份是否为业主且状态为已停用
        TaUser taUser = taUserMapper.selectByPrimaryKey(userElement.getId());
        if (taUser.getId().intValue() == -1) {
            responseBean.addError("9996", "游客不能报名");
            return responseBean;
        }

        // 校验用户
        iTaUserService.checkBlacklistStatusUser(taUser);

        return insertActivitySignUp(userElement, tpActivity, communityId, remark);
    }

    @Override
    public ResponseBean findAllTransaction(Integer communityId, String transactionTitle, String type, Integer pageNum, Integer paeSize) {
        Map<String, Object> parameter = Maps.newHashMap();
        ResponseBean responseBean = new ResponseBean();
        Page<TpTransaction> pageList = PageHelper.startPage(pageNum, paeSize);
        List<TpTransaction> tpTransactions = tpTransactionMapper.findAllTransaction(communityId, transactionTitle, type);

        tpTransactions.stream().forEach(e -> {
            if (null != e.getTaUserVerifyId()) {
                TaSysRole taSysRole = taSysRoleMapper.selectByPrimaryKey(e.getTaUserVerifyId());
                e.setRoleId(taSysRole.getId());
                e.setRoleName(taSysRole.getRoleName());
            }
            TaUser taUser = taUserMapper.selectByPrimaryKey(e.getTaUserId());
            e.setCreateUserName(taUser.getUserName());
        });

        parameter.put("list", tpTransactions);
        parameter.put("total", pageList.getTotal());
        responseBean.addSuccess(parameter);
        return responseBean;

    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseBean addAllTransaction(UserElement userElement, String paramets) {
        ResponseBean response = new ResponseBean();
        JSONObject jsonObject = JSONObject.parseObject(paramets);
        String transactionTitle = jsonObject.getString("title");
        String transactionContent = jsonObject.getString("content");
        String type = jsonObject.getString("type");
        String imageUrl = jsonObject.getString("imageUrl");

        TaUser user = taUserMapper.selectByPrimaryKey(userElement.getId());
        TpTransaction tpTransaction = new TpTransaction();
        tpTransaction.setTransactionTitle(transactionTitle);
        tpTransaction.setTransactionContent(transactionContent);
        tpTransaction.setType(type);
        tpTransaction.setCommunityId(userElement.getCommunityId());
        tpTransaction.setTaUserId(userElement.getId());
        tpTransaction.setCreateUser(userElement.getId());
        tpTransaction.setStatus("1");
        tpTransaction.setCreateDate(new Date());
        tpTransaction.setUpdateUser(userElement.getId());
        tpTransaction.setUpdateDate(new Date());
        TaUserVerify taUserVerify= taUserVerifyMapper.selectByPrimaryKey(userElement.getUserVerifyId());
        tpTransaction.setTaUserVerifyId(taUserVerify.getRoleId());
        tpTransaction.setRoomNoName(taUserVerify.getRoomNoName());
        tpTransaction.setIsReported("0");
        // 发布者身份  0 APP  1 物业
        tpTransaction.setReleaseIdentity("0");
        tpTransaction.setViewCount(0);
        tpTransaction.setSort("1");

        //判断身份状态是否为已停用
        iTaUserService.checkBlacklistStatusUser(user);

        tpTransactionMapper.insertSelective(tpTransaction);
        insertTdImage(tpTransaction, imageUrl, userElement.getId(), Constant.TRANSACTION);
        response.addSuccess(tpTransaction);
        return response;

    }

    /**
     * 图片入库
     *
     * @param tpTransaction
     * @param imageUrl      多个图片都好分割
     * @param userId
     * @param type          服务：service, 公告：announcement , 活动：activity  租赁 ： transaction
     * @throws IOException
     */
    private void insertTdImage(TpTransaction tpTransaction, String imageUrl, Integer userId, String type) {
        if (null == imageUrl || "".equals(imageUrl)) {
            return;
        }
        String[] imgArr = imageUrl.split(",");
        for (String url : imgArr) {
            TdImages tdImages = new TdImages();
            Integer uuId = tpTransaction.getId();
            tdImages.setImageUrl(url);
            tdImages.setType(type);
            tdImages.setUuid(uuId);
            tdImages.setCreateUser(userId);
            tdImages.setCreateTime(new Date());
            tdImagesMapper.insertSelective(tdImages);
        }
    }

    @Override
    public ResponseBean selectAllTransaction(UserElement userElement, Integer pageNum, Integer paeSize, Integer type) {
        ResponseBean responseBean = new ResponseBean();
        TaUser user = taUserMapper.selectByPrimaryKey(userElement.getId());

        //判断状态是否为已停用
        iTaUserService.checkBlacklistStatusUser(user);

        Map<String, Object> parameter = Maps.newHashMap();
        Page<TpTransaction> pageLsit = PageHelper.startPage(pageNum, paeSize);
        List<TpTransaction> tpTransactions = tpTransactionMapper.selectTransaction(userElement.getId(), userElement.getCommunityId(), type);

        tpTransactions.stream().forEach(e -> {
            // 角色
            TaUserVerify userVerify = taUserVerifyMapper.selectByPrimaryKey(userElement.getUserVerifyId());
            TaSysRole taSysRole = taSysRoleMapper.selectByPrimaryKey(userVerify.getRoleId());
            e.setRoleId(taSysRole.getId());
            e.setRoleName(taSysRole.getRoleName());
            e.setCreateUserName(user.getUserName());
        });

        parameter.put("list", tpTransactions);
        parameter.put("total", pageLsit.getTotal());
        responseBean.addSuccess(parameter);

        return responseBean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean updateTransaction(String paramets, Integer userId, Integer id) {
        ResponseBean response = new ResponseBean();
        JSONObject jsonObject = JSONObject.parseObject(paramets);
        String imageUrl = jsonObject.getString("imageUrl");

        TpTransaction tpTransaction = JSONObject.parseObject(paramets, TpTransaction.class);
        TpTransaction transaction = tpTransactionMapper.getById(id);
        transaction.setTransactionTitle(tpTransaction.getTransactionTitle());
        transaction.setTransactionContent(tpTransaction.getTransactionContent());


        if (null != transaction && userId.equals(transaction.getTaUserId())) {
            tdImagesMapper.deleteTdImages(Integer.valueOf(id), Constant.TRANSACTION);

            insertTdImage(transaction, imageUrl, userId, Constant.TRANSACTION);
            tpTransactionMapper.updateTransaction(Integer.valueOf(id), transaction.getTransactionTitle(), transaction.getTransactionContent(), userId);
            response.addSuccess("修改成功");
            return response;
        }
        response.addError("操作失败");
        return response;
    }

    @Override
    public ResponseBean deleteransaction(Integer id, UserElement userElement) {
        ResponseBean responseBean = new ResponseBean();
        TpTransaction tpTransaction = tpTransactionMapper.getById(Integer.valueOf(id));
        if (null != tpTransaction && userElement.getId().equals(tpTransaction.getTaUserId())) {
            tpTransaction.setStatus("0");
            tpTransaction.setUpdateDate(new Date());
            tpTransactionMapper.updateByPrimaryKeySelective(tpTransaction);
            responseBean.addSuccess("删除成功");


            // 把消息变为无效
            Map<String, Object> map = new HashMap<>();
            map.put("communityId", tpTransaction.getCommunityId());
            map.put("messageType", "9");
            map.put("adviceType", "4");
            map.put("uuidType", "2");
            map.put("source", "1");
            map.put("status", "1");
            map.put("modelType", "1");
            map.put("transactionId", tpTransaction.getId());
            TpMessage tpMessage = tpMessageMapper.selectConditionsTpMessage(map);
            if (null != tpMessage) {
                tpMessage.setStatus("0");
                tpMessageMapper.updateByPrimaryKeySelective(tpMessage);
            }


        } else {
            responseBean.addSuccess("当前ID不存在");
        }
        return responseBean;
    }

    /**
     * 获取举报原因列表
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> getReportReasons() {
        return tpTransactionMapper.getReportReasons();
    }

    /**
     * 举报二手交易帖子
     *
     * @param userId
     * @param paramets
     * @return
     */
    @Override
    public ResponseBean reportTransaction(Integer userId, Integer communityId, String paramets) {
        ResponseBean responseBean = new ResponseBean();
        JSONObject jsonObject = JSONObject.parseObject(paramets);
        Integer transactionId = jsonObject.getInteger("transactionId");
        String reportReasonId = jsonObject.getString("reportReasonId");
        //校验举报的帖子存不存在
        TpTransaction tpTransaction = tpTransactionMapper.selectByPrimaryKey(transactionId, communityId);
        if (null == tpTransaction) {
            responseBean.addError("举报的交易不存在");
            return responseBean;
        }
        // 举报原因
        TpTransactionReport tpTransactionReport = tpTransactionReportMapper.selectByCommunityIdAndTransactionId(userId, communityId, tpTransaction.getId());
        if (null != tpTransactionReport) {
            responseBean.addError("您已举报了该帖子!");
            return responseBean;
        }
        //插入举报表
        tpTransactionMapper.saveReportReason(userId, communityId, transactionId, reportReasonId,new Date());
        //更新交易表的举报状态为被举报
        TpTransaction record = new TpTransaction();
        record.setId(transactionId);
        record.setIsReported("1");
        Integer size = tpTransactionMapper.updateByPrimaryKeySelective(record);
        if (size > 0) {

            // 举报人
            TaUser taUser = taUserMapper.selectByPrimaryKey(userId);
            // 发帖人
            TaUser createUser = taUserMapper.selectByPrimaryKey(tpTransaction.getCreateUser());

            // 举报原因
            //TpTransactionReport tpTransactionReport = tpTransactionReportMapper.selectByCommunityIdAndTransactionId(communityId, tpTransaction.getId());
            SysReportReason sysReportReason = sysReportReasonMapper.selectByPrimaryKey(Integer.valueOf(reportReasonId));


            // 插入消息表
            TpMessage message = new TpMessage();
            message.setCommunityId(communityId);
            message.setMessageType("9");
            message.setAdviceType("4");
            message.setModelType("1");
            //超级管理员
            Integer userID = toCommunitiesMapper.selectAndmin(communityId);
            message.setUuid(userID);
            message.setModelType("1");
            message.setUuidType("2");
            message.setSource("1");
            message.setMessageContent("{" + taUser.getUserName() + "}举报了{" + createUser.getUserName() + "}发布的帖子：{" + tpTransaction.getTransactionTitle() + "}，举报原因：{" + sysReportReason.getReason() + "}，点击责令发布人修改或直接作废帖子");
            message.setStatus("1");
            message.setReadStatus("0");
            message.setTransactionId(transactionId);
            message.setCreateDate(new Date());
            message.setCreateUser(userId);
            tpMessageMapper.insertSelective(message);


            responseBean.addSuccess(size);
            return responseBean;
        }
        responseBean.addError("举报出错");
        return responseBean;
    }

    @Override
    public ResponseBean addTransactionReply(String paramets, UserElement userElement) {
        ResponseBean response = new ResponseBean();
        JSONObject object = JSONObject.parseObject(paramets);
        JSONArray array = object.getJSONArray("imgArr");
        String[] reply = null;
        if (null != array) {
            reply = array.toArray(new String[]{});
        }
        TpTransactionReply tpTransactionReply = JSONObject.parseObject(paramets, TpTransactionReply.class);
        tpTransactionReply.setCommunityId(userElement.getCommunityId());
        tpTransactionReply.setTaUserId(userElement.getId());
        tpTransactionReply.setTaUserName(userElement.getUserName());

            // 由于评论帖子和评论对话是同一个接口，当tpTransactionReply.getReplyTaUserId()为空时查询Ta_user里面的名字
        TpTransaction tpTransaction= tpTransactionMapper.getById(tpTransactionReply.getTransactionId());
        TaUser taUser= taUserMapper.selectByPrimaryKey(tpTransaction.getTaUserId());

        tpTransactionReply.setReplyTaUserName(tpTransactionReply.getReplyTaUserId()==null?taUser.getUserName():taUserMapper.selectByPrimaryKey(tpTransactionReply.getReplyTaUserId()).getUserName());
        //  评论帖子取 TpTransaction 的创建人，回复对话取传过来的值
        tpTransactionReply.setReplyTaUserId(tpTransactionReply.getReplyTaUserId()==null?tpTransaction.getCreateUser():tpTransactionReply.getReplyTaUserId());
        tpTransactionReply.setReleaseIdentity("0");
        TaUserVerify taUserVerify= taUserVerifyMapper.selectByPrimaryKey(userElement.getUserVerifyId());
        tpTransactionReply.setTaUserVerifyId(taUserVerify.getRoleId());
        tpTransactionReply.setRoomNoName(taUserVerify.getRoomNoName());
        tpTransactionReply.setCreateDate(new Date());
        tpTransactionReplyMapper.insert(tpTransactionReply);

        if (null != array) {
            for (String img : reply) {
                TdImages tdImages = new TdImages();
                tdImages.setImageUrl(img);
                tdImages.setType("reply");
                tdImages.setUuid(tpTransactionReply.getId());
                tdImages.setCreateTime(new Date());
                tdImages.setCreateUser(userElement.getId());
                tdImagesMapper.insert(tdImages);
            }
        }
        response.addSuccess("成功");
        return response;
    }

    @Override
    public ResponseBean addTransactionLike(String paramets, UserElement userElement) {
        ResponseBean response = new ResponseBean();
        TpTransactionLike tpTransactionLike = JSONObject.parseObject(paramets, TpTransactionLike.class);
        tpTransactionLike.setCommunityId(userElement.getCommunityId());
        tpTransactionLike.setTaUserId(userElement.getId());
        tpTransactionLike.setCreateDate(new Date());
        TpTransactionLike isUser = tpTransactionLikeMapper.getinvitationId(tpTransactionLike.getTransactionId(), userElement.getCommunityId(), userElement.getId());
        if (null != isUser) {
            response.addError("您已点赞或踩");
            return response;
        }
        tpTransactionLikeMapper.insert(tpTransactionLike);
        response.addSuccess("成功");
        return response;
    }

    @Override
    public ResponseBean userActivityList(UserElement userElement, Integer pageNum, Integer paeSize) {
        ResponseBean responseBean = new ResponseBean();
        Map<String, Object> parameter = Maps.newHashMap();
        Page<TpActivity> pageList = PageHelper.startPage(pageNum, paeSize);
        List<TpActivity> tpActivity = tpActivityMapper.selecttpActivity(userElement.getId(), userElement.getCommunityId());
        parameter.put("list", tpActivity);
        parameter.put("total", pageList.getTotal());
        responseBean.addSuccess(parameter);
        return responseBean;
    }

    @Override
    public ResponseBean userTransactionList(UserElement userElement, Integer pageNum, Integer paeSize) {
        ResponseBean responseBean = new ResponseBean();
        //拿到我自己所有的帖子
        Map<String, Object> parameter = Maps.newHashMap();
        Page<TpTransaction> pageList = PageHelper.startPage(pageNum, paeSize);
        List<TpTransaction> tpTransactionList = tpTransactionMapper.getUserTransactionList(userElement.getId(), userElement.getCommunityId());

        parameter.put("list", tpTransactionList);
        parameter.put("total", pageList.getTotal());
        responseBean.addSuccess(parameter);
        return responseBean;
    }

    @Override
    public ResponseBean tpActivitySignInAdd(String paramets, UserElement userElement) {
        ResponseBean responseBean = new ResponseBean();
        Integer activityId = JSONObject.parseObject(paramets).getInteger("activityId");
        TpActivitySignIn tpActivitySignIn = new TpActivitySignIn();
        tpActivitySignIn.setActivityId(activityId);
        tpActivitySignIn.setCommunityId(userElement.getCommunityId());

        TaUserVerify taUserVerify = taUserVerifyMapper.selectByPrimaryKey(userElement.getUserVerifyId());

        String description = taSysRoleMapper.selectByPrimaryKey(taUserVerify.getRoleId()).getDescription();
        tpActivitySignIn.setUserRole(description);
        tpActivitySignIn.setUserName(userElement.getUserName());
        //期/栋/单/层/户
        String bu = taUserVerify.getPhaseName() + "期" + taUserVerify.getBuildingName() + "栋" + taUserVerify.getUnitName() + "单" + taUserVerify.getLevelName() + "层" + taUserVerify.getRoomNoName() + "户";
        tpActivitySignIn.setBuildingInfo(bu);
        tpActivitySignIn.setTaUserId(userElement.getId());
        tpActivitySignIn.setUserTel(userElement.getLoginName());
        tpActivitySignIn.setCreateDate(new Date());
        tpActivitySignInMapper.insert(tpActivitySignIn);

        responseBean.addSuccess("成功");

        return responseBean;
    }

    @Override
    public ResponseBean replyAdd(String paramets, UserElement userElement) {
        ResponseBean response = new ResponseBean();

        JSONObject object = JSONObject.parseObject(paramets);
        Integer transactionId = object.getInteger("transactionId");
        String replyContent = object.getString("replyContent");
        Integer replyUserId = object.getInteger("replyUserId");
        String[] imgArr = object.getJSONArray("imgArr").toArray(new String[]{});

        String userName = taUserMapper.selectByPrimaryKey(replyUserId).getUserName();
        TpTransactionReply tpTransactionReply = new TpTransactionReply();
        tpTransactionReply.setCommunityId(userElement.getCommunityId());
        tpTransactionReply.setTransactionId(transactionId);
        tpTransactionReply.setTaUserId(userElement.getId());
        tpTransactionReply.setTaUserName(userElement.getUserName());
        tpTransactionReply.setReleaseIdentity("0");
        tpTransactionReply.setReplyContent(replyContent);
        tpTransactionReply.setReplyTaUserId(replyUserId);
        tpTransactionReply.setReplyTaUserName(userName);
        tpTransactionReply.setCreateDate(new Date());
        response.addSuccess("成功");
        tpTransactionReplyMapper.insert(tpTransactionReply);
        //添加评论图片
        for (String img : imgArr) {
            TdImages tdImages = new TdImages();
            tdImages.setImageUrl(img);
            tdImages.setType("reply");
            tdImages.setUuid(tpTransactionReply.getId());
            tdImages.setCreateTime(new Date());
            tdImages.setCreateUser(userElement.getId());
            tdImagesMapper.insert(tdImages);
        }
        return response;
    }


    @Override
    public void accessTicket(Integer communityId, TpTicket tpTicket, String ticketId, Integer userId) {
        //修改工单内容和评分
        tpTicket.setId(Integer.valueOf(ticketId));
        tpTicket.setStatus("5");
        tpTicketMapper.updateByPrimaryKeySelective(tpTicket);
        //根据1.4版本需要被终止时，清空当前工单受理人
        tpTicketMapper.updateTpUserId(Integer.valueOf(ticketId));
        //工单处理表新增评分记录
        TpTicketRecord record = new TpTicketRecord();
        record.setCommunityId(communityId);
        record.setTicketId(Integer.valueOf(ticketId));
        record.setStatus("5");
        record.setContent(tpTicket.getComment());
        record.setCreateUser(userId);
        record.setCreateDate(new Date());
        tpTicketRecordMapper.insertSelective(record);

        //1.5版本推送消息message
        TpMessage message = new TpMessage();
        message.setCommunityId(communityId);
        message.setTicketId(tpTicket.getId());
        TpTicket tic = tpTicketMapper.selectByTicketId(String.valueOf(communityId), Integer.valueOf(ticketId));
        message.setMessageType(tic.getType());
        message.setAdviceType("4");
        message.setModelType("1");
        Integer createUser = tpTicketMapper.selectRecordStatus(communityId, tpTicket.getId());
        message.setUuid(createUser);
        message.setUuidType("2");
        message.setSource("2");
        message.setMessageContent("工单“" + tic.getTicketTitle() + "”已经验收并评价，点击查看评分");
        message.setStatus("1");
        message.setReadStatus("0");
        message.setCreateUser(userId);
        message.setCreateDate(new Date());
        tpMessageMapper.insert(message);
    }

    @Override
    public List<TpActivity> getActivity(Integer communityId) {
        Integer num = tpCarouselSettingMapper.getcarouselNum(Constant.ACTIVITY, communityId);
        if (null == num) {
            num = 0;
        }
        List<TpActivity> listActivity = tpActivityMapper.getActivity(communityId, num);
        return listActivity;
    }

    /**
     * 取消报名接口
     *
     * @param activityId
     * @param communityId
     * @param userId
     * @return
     */
    @Override
    public ResponseBean cancelSignActivity(Integer activityId, Integer communityId, Integer userId) {
        ResponseBean responseBean = new ResponseBean();
        TpActivitySignup tpActivitySignup = new TpActivitySignup();
        tpActivitySignup.setActivityId(activityId);
        tpActivitySignup.setCommunityId(communityId);
        tpActivitySignup.setTaUserId(userId);
        tpActivitySignupMapper.deleteSignUp(tpActivitySignup);
        //更新报名人数
        updateActivitySignUpNum(communityId, activityId);
        responseBean.addSuccess("取消报名成功");
        return responseBean;
    }


    public ResponseBean insertActivitySignUp(UserElement userElement, TpActivity tpActivity, Integer communityId, String remark) {
        ResponseBean responseBean = new ResponseBean();
        //判断是否已经报名
        Integer signNum = tpActivitySignupMapper.findTpActivetitySignByUserId(tpActivity.getId(), communityId, userElement.getId());
        if (signNum != 0) {
            responseBean.addError("9996", "您已报名，请勿重复报名");
            return responseBean;
        }

        TpActivitySignup tpActivitySignup = new TpActivitySignup();
        tpActivitySignup.setActivityId(tpActivity.getId());
        tpActivitySignup.setCommunityId(communityId);
        tpActivitySignup.setTaUserId(userElement.getId());
        tpActivitySignup.setSignUpTime(new Date());
        tpActivitySignup.setRemark(remark);

        TaUserVerify userVerify = taUserVerifyMapper.selectByPrimaryKey(userElement.getUserVerifyId());
        TaSysRole sysRole = taSysRoleMapper.selectByPrimaryKey(userVerify.getRoleId());

        tpActivitySignup.setAddress(userVerify.getPhaseName() + userVerify.getBuildingName() + userVerify.getUnitName() + userVerify.getLevelName() + userVerify.getRoomNoName());
        tpActivitySignup.setUserRole(sysRole.getRoleName());

        tpActivitySignupMapper.insertSelective(tpActivitySignup);
        //更新报名人数
        updateActivitySignUpNum(communityId, tpActivity.getId());
        responseBean.addSuccess("报名成功");
        return responseBean;
    }

    /**
     * 更新报名人数
     *
     * @param communityId
     * @param activityId
     * @return
     */
    private Integer updateActivitySignUpNum(Integer communityId, Integer activityId) {
        TpActivitySignup tpActivitySignup = new TpActivitySignup();
        tpActivitySignup.setActivityId(activityId);
        tpActivitySignup.setCommunityId(communityId);
        Integer signNum = tpActivitySignupMapper.selectSignNum(tpActivitySignup);
        TpActivity updateActivity = new TpActivity();
        updateActivity.setId(activityId);
        updateActivity.setSignUpCount(signNum);
        tpActivityMapper.updateByPrimaryKeySelective(updateActivity);
        return signNum;
    }

    @Transactional
    @Override
    public TpTransaction findUsedDetails(Integer activityId, Integer communityId, Integer userId) {
        Integer num = updateSocialView(userId, Constant.LEASE, communityId, activityId);
        if (null != num) {
            TpTransaction transaction = new TpTransaction();
            transaction.setId(activityId);
            transaction.setViewCount(num);
            tpTransactionMapper.updateByPrimaryKeySelective(transaction);
        }

        TpTransaction tpTransaction = tpTransactionMapper.selectByPrimaryKey(activityId, communityId);
        TaUser taUser = taUserMapper.selectByPrimaryKey(tpTransaction.getTaUserId());
        tpTransaction.setTelephone(taUser.getLoginName());
        tpTransaction.setCreateUserName(taUser.getUserName());

        Map<String, Object> map = Maps.newHashMap();
        map.put("uuid", tpTransaction.getId());
        map.put("type", Constant.TRANSACTION);
        // 查询图片
        List<TdImages> tdImagesList = tdImagesMapper.getByUUIDAndByType(map);
        List<String> imgList = tdImagesList.stream().map(e -> new String(e.getImageUrl())).collect(Collectors.toList());
        tpTransaction.setImgList(imgList);

        /**
         * 查询点赞和踩的次数
         */


        //统计点赞人数的次数
        Integer likeCount = tpTransactionLikeMapper.likeCount(activityId, communityId);
        //不喜欢的人数
        Integer noLikeCount = tpTransactionLikeMapper.nolikeCount(activityId, communityId);
        tpTransaction.setLikeCount(likeCount == null ? 0 : likeCount);
        tpTransaction.setNoLikeCount(noLikeCount == null ? 0 : noLikeCount);

        // 查询是 点赞 还是 踩
        TpTransactionLike isUser = tpTransactionLikeMapper.getinvitationId(activityId, communityId, userId);
        if (null != isUser) {
            tpTransaction.setBel(isUser.getLikeStatus());
        }

        return tpTransaction;

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseBean updateActivtiySignUp(Integer activityId, Integer communityId, Integer userId, String remark) {
        ResponseBean responseBean = new ResponseBean();
        TpActivitySignup tpActivitySignup = tpActivitySignupMapper.selectTpActivetitySignByUserId(activityId, communityId, userId);
        if (null == tpActivitySignup) {
            responseBean.addError("9996", "您未报名!");
            return responseBean;
        }

        tpActivitySignup.setCommunityId(communityId);
        tpActivitySignup.setTaUserId(userId);
        tpActivitySignup.setRemark(remark);
        tpActivitySignupMapper.updateByPrimaryKey(tpActivitySignup);
        responseBean.addSuccess("操作成功!");
        return responseBean;
    }

    @Override
    public ResponseBean getActivtiySignUp(Integer activityId, Integer communityId, Integer userId) {

        ResponseBean responseBean = new ResponseBean();
        TpActivitySignup tpActivitySignup = tpActivitySignupMapper.selectTpActivetitySignByUserId(activityId, communityId, userId);
        if (null == tpActivitySignup) {
            responseBean.addError("9996", "您未报名!");
            return responseBean;
        }

        responseBean.addSuccess(tpActivitySignup);

        return responseBean;
    }

    @Override
    public ResponseBean findUsedDetailsReply(Integer transactionId, UserElement userElement, String order, Integer pageNum, Integer pageSize, Integer type) {
        ResponseBean responseBean = new ResponseBean();
        //拿到当前帖子的创建人
        TpTransaction tpTransaction= tpTransactionMapper.getById(transactionId);

        PageHelper.startPage(pageNum, pageSize, "create_date " + order);
        //房间号
         TaUserVerify taUserVerify= taUserVerifyMapper.selectByPrimaryKey(userElement.getUserVerifyId());
        List<TpTransactionReply> replies = tpTransactionReplyMapper.getCommunityIdAndTransactionId(userElement.getCommunityId(), transactionId, userElement.getId(), tpTransaction.getCreateUser(),type,taUserVerify.getRoomNoName());
        for (TpTransactionReply tpTransactionReply : replies) {
            List<TdImages> tdImagesList = tdImagesMapper.selectImages(tpTransactionReply.getId(), "reply");
            List<String> list = new ArrayList<>();
            for (TdImages imageUrl : tdImagesList) {
                list.add(imageUrl.getImageUrl());
                tpTransactionReply.setImgList(list);
            }
        }

        responseBean.addSuccess(replies);
        return responseBean;
    }
}
