package com.huiju.estateagents.property.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.center.taUser.mapper.TaUserMapper;
import com.huiju.estateagents.property.common.Constant;
import com.huiju.estateagents.property.common.UserElement;
import com.huiju.estateagents.property.dao.*;
import com.huiju.estateagents.property.model.*;
import com.huiju.estateagents.property.service.IMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.swagger2.mappers.ModelMapper;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 物业端消息表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-03-05
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {
    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private BillMapper tpBillMapper;

    @Autowired
    private TpTicketMapper tpTicketMapper;

    @Autowired
    private TpTransactionMapper tpTransactionMapper;

    @Autowired
    private TaUserVerifyMapper taUserVerifyMapper;

    @Autowired
    private TpAnnouncementMapper tpAnnouncementMapper;

    @Autowired
    private  TpActivityMapper tpActivityMapper;

    @Autowired
    private  TpShopMapper tpShopMapper;

    @Override
    public ResponseBean messageLiset(String parameter, Integer orgId,Integer user) {
        ResponseBean response= new  ResponseBean();
        JSONObject object = JSONObject.parseObject(parameter);
        //待办消息类型(-1:论坛，-2:工单，-3:缴费)
        String  messageType = object.getString("messageType");
        //0:无效，1:有效
        String  status = object.getString("status");
        Date createDate = object.getDate("createDate");

        String  messageContent = object.getString("messageContent");
        Integer pageNum = object.getInteger("pageNum");
        Integer pageSize = object.getInteger("pageSize");

        Page<Message> page = new Page<>();
        page.setSize(pageSize == null ? 10 : pageSize);
        page.setCurrent(pageNum == null ? 1 : pageNum);
        IPage<Message> pageInfo = messageMapper.messageLiset(page,messageType,status,createDate,messageContent,user);
        List<Message> ticketList = pageInfo.getRecords();
        HashMap map=new HashMap<>();
        map.put("list",ticketList);
        map.put("total", pageInfo.getTotal());
        map.put("pageNum", pageInfo.getCurrent());
        map.put("pageSize", pageInfo.getSize());
        response.addSuccess(map);
        return response;
    }

    @Override
    public ResponseBean myMessageList(String parameter, Integer orgId, Integer user) {
        ResponseBean response= new  ResponseBean();
        JSONObject object = JSONObject.parseObject(parameter);
        //待办消息类型(-1:论坛，-2:工单，-3:缴费)
        String  messageType = object.getString("messageType");
        //0:无效，1:有效
        String  readStatus = object.getString("readStatus");
        Date createDate = object.getDate("createDate");

        String  messageContent = object.getString("messageContent");
        Integer pageNum = object.getInteger("pageNum");
        Integer pageSize = object.getInteger("pageSize");

        Page<Message> page = new Page<>();
        page.setSize(pageSize == null ? 10 : pageSize);
        page.setCurrent(pageNum == null ? 1 : pageNum);
        IPage<Message> pageInfo = messageMapper.myMessageList(page,messageType,readStatus,createDate,messageContent,user);
        List<Message> ticketList = pageInfo.getRecords();
        HashMap map=new HashMap<>();
        map.put("list",ticketList);
        map.put("total", pageInfo.getTotal());
        map.put("pageNum", pageInfo.getCurrent());
        map.put("pageSize", pageInfo.getSize());
        response.addSuccess(map);
        return response;
    }

    @Override
    public ResponseBean delectRead(String parameter, Integer userID) {
        ResponseBean response = new ResponseBean();
        JSONObject parseObject = JSONObject.parseObject(parameter);

        JSONArray message = parseObject.getJSONArray("id");
        Integer[] messageListID = message.toArray(new Integer[]{});
        for (Integer id : messageListID) {
            Message mes= new Message();
                    mes.setId(id);
                    mes.setReadStatus("1");
                    mes.setUpdateDate(LocalDateTime.now());
                    mes.setUpdateUser(userID);
                    messageMapper.updateById(mes);
        }
                response.addSuccess("成功");
                return response;
    }



    /**
     * 获取消息数量
     * @param orgId
     * @return
     */
    @Override
    public Map<String, Object> getMessageTotal(Integer orgId, Integer verifyId) {
        return messageMapper.getMessageTotal(verifyId,orgId);
    }

    /**
     * 分页获取消息或待办
     * @param orgId
     * @param pageNum
     * @param pageSize
     * @param modelType
     * @return
     */
    @Override
    public Map<String,Object> getMessages(Integer orgId, Integer pageNum, Integer pageSize,Integer modelType, Integer verifyId) {
        //使用分页插件
        Page<Message> page = new Page(pageNum, pageSize);
        // 获取数据
        IPage<Message> messagePage = messageMapper.getMessages(page,verifyId,orgId, modelType);
        List<Message> messageList = messagePage.getRecords();
        // 查找标题
        for (Message tpMessage:messageList){
            // 工单
            if (Constant.MESSAGE_UUID_TYPE_TICKET.equals(tpMessage.getMessageUuidType())) {
                TpTicket tpTicket = tpTicketMapper.selectById(tpMessage.getMessageUuid());
                tpMessage.setContent(tpTicket.getTicketTitle());
            }
            // 话题
            if (Constant.MESSAGE_UUID_TYPE_TRANSACTION.equals(tpMessage.getMessageUuidType())){
                TpTransaction tpTransaction = tpTransactionMapper.selectByPrimaryKey(tpMessage.getMessageUuid(),tpMessage.getOrgId());
                tpMessage.setContent(tpTransaction.getTransactionTitle());
            }
            // 公告
            if (Constant.MESSAGE_UUID_TYPE_ANNOUNCEMENT.equals(tpMessage.getMessageUuidType())){
                TpAnnouncement tpAnnouncement = tpAnnouncementMapper.selectByPrimaryKey(tpMessage.getMessageUuid(),tpMessage.getOrgId());
                tpMessage.setContent(tpAnnouncement.getAnnouncementTitle());
            }
            // 活动
            if (Constant.MESSAGE_UUID_TYPE_ACTIVITY.equals(tpMessage.getMessageUuidType())){
                TpActivity tpActivity = tpActivityMapper.selectById(tpMessage.getMessageUuid());
                tpMessage.setContent(tpActivity.getActivityTitle());
            }
            // 收费组名称
            if (Constant.MESSAGE_UUID_TYPE_BILL.equals(tpMessage.getMessageUuidType())){
                Bill tpBill = tpBillMapper.selectById(tpMessage.getMessageUuid());
                tpMessage.setContent(tpBill.getBillName());
            }
            // 商铺
            if (Constant.MESSAGE_UUID_TYPE_SHOP.equals(tpMessage.getMessageUuidType())){
                TpShop tpShop = tpShopMapper.selectById(tpMessage.getMessageUuid());
                tpMessage.setContent(tpShop.getShopName());
            }

            //活动被作废
            if (Constant.MESSAGE_UUID_TYPE_ACTIVITY.equals(tpMessage.getMessageUuidType())){
                Message message = messageMapper.selectById(tpMessage.getId());
                if(Constant.ACTIVITY_CANCELLED.equals(message.getMessageType())) {
                    tpMessage.setMessageDetailUrl(null);
                    tpMessage.setContent(null);
                }
            }
            //话题被作废
            if(Constant.MESSAGE_UUID_TYPE_TRANSACTION.equals(tpMessage.getMessageUuidType())){
                Message message = messageMapper.selectById(tpMessage.getId());
                if(Constant.THREAD_CANCELLED.equals(message.getMessageType())){
                    tpMessage.setMessageDetailUrl(null);
                    tpMessage.setContent(null);
                }
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("list",messageList);
        map.put("total",page.getTotal());
        return map;
    }

    /**
     * 消息全部已读
     */
    @Override
    public void updateMessageReadStatus(Integer orgId, Integer userId) {
        messageMapper.updateReadStatus(orgId, userId);
    }

    @Override
    public ResponseBean updateMessageByIdReadStatus(TaUser userElement, Integer messageId) {
        ResponseBean responseBean = new ResponseBean();

        Message tpMessage = messageMapper.selectById(messageId);
        if (null == tpMessage) {
            responseBean.addError("消息不存在!");
            return responseBean;
        }
        tpMessage.setReadStatus("1");
        tpMessage.setUpdateDate(LocalDateTime.now());
        tpMessage.setUpdateUser(userElement.getUserId());
        int row = messageMapper.updateById(tpMessage);
        if (row > 0) {
            responseBean.addSuccess("操作成功!");
            return responseBean;
        }
        responseBean.addError("操作失败!");
        return responseBean;
    }

    /**
     * 根据消息ID 查询详情数据
     *
     * @param orgId
     * @param messageId
     * @return
     */
    @Override
    public ResponseBean getMessageById(Integer orgId, Integer messageId) {
        ResponseBean responseBean = new ResponseBean();
        Message tpMessage = messageMapper.selectById(messageId);
        if (null != tpMessage){
            // 设置当前工单类型
            if (Constant.MESSAGE_UUID_TYPE_TICKET.equals(tpMessage.getMessageUuidType())){
                TpTicket tpTicket= tpTicketMapper.selectById(tpMessage.getMessageUuid());
                tpMessage.setTicketType(tpTicket.getType());
            }
            // 当前发帖人是否存在(app发帖)
            if (Constant.MESSAGE_UUID_TYPE_TRANSACTION.equals(tpMessage.getMessageUuidType())){
                TpTransaction tpTransaction = tpTransactionMapper.selectByPrimaryKey(tpMessage.getMessageUuid(),tpMessage.getOrgId());
                if ("app".equals(tpTransaction.getUuidType())){
                    TaUserVerify taUserVerify = taUserVerifyMapper.selectById(tpTransaction.getUuid());
                    if (null == taUserVerify){
                        responseBean.addError("此贴已丢失，无法查看");
                        return  responseBean;
                    }
                }
            }
            responseBean.addSuccess(tpMessage);
            return responseBean;
        }
        responseBean.addError("不存在的ID");
        return responseBean;
    }
}
