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.ITicketService;
import com.community.huiju.vo.TpTicketVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 工单业务 实现
 * @author weiximei
 */
@Service("iTicketService")
@Slf4j
public class TicketServiceImpl implements ITicketService {

    @Autowired
    private TpTicketMapper tpTicketMapper;

    @Autowired
    private TpTicketRecordMapper tpTicketRecordMapper;

    @Autowired
    private TpTicketRecordCommentMapper tpTicketRecordCommentMapper;

    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private TdImagesMapper tdImagesMapper;

    @Autowired
    private TpMessageMapper tpMessageMapper;

    @Autowired
    private TpannouncementTelMapper tpannouncementTelMapper;

    @Autowired
    private TaSysUserRoleMapper taSysUserRoleMapper;

    @Autowired
    private  ToCommunitiesMapper toCommunitiesMapper;

    @Autowired
    private TaUserVerifyMapper taUserVerifyMapper;

    @Override
    public ResponseBean getList(TpTicket tpTicket, Integer pageNum, Integer pageSize) {

        ResponseBean<Map<String, Object>> responseBean = new ResponseBean();
        // 最终返回值
        Map<String, Object> result = Maps.newHashMap();

        Map<String, Object> parameter = Maps.newHashMap();
        parameter.put("communityId", tpTicket.getCommunityId());
        parameter.put("taUserId", tpTicket.getTaUserId());

        //  1：投诉   2：报修 3：联系物业
        parameter.put("type", 2);
        // 报修
        Page<TpTicket> pageRepairs = PageHelper.startPage(pageNum, pageSize);
        List<TpTicket> tpTicketRepairsList = tpTicketMapper.selectByCommuniytIdAndByTaUserIdAndByType(parameter);
        List<TpTicketVO> repairsList = Lists.newArrayList();
        tpTicketVOConvert(tpTicketRepairsList, repairsList);

        // 投诉
        //  1：投诉   2：报修 3：联系物业
        parameter.put("type", 1);
        Page<TpTicket> pageComplaint = PageHelper.startPage(pageNum, pageSize);
        List<TpTicket> tpTicketComplaintList = tpTicketMapper.selectByCommuniytIdAndByTaUserIdAndByType(parameter);
        List<TpTicketVO> complaintList = Lists.newArrayList();
        tpTicketVOConvert(tpTicketComplaintList, complaintList);

        // 联系工单
        //  1：投诉   2：报修 3：联系物业
        parameter.put("type", 3);
        Page<TpTicket> pageLiaison = PageHelper.startPage(pageNum, pageSize);
        List<TpTicket> tpTicketLiaisonList = tpTicketMapper.selectByCommuniytIdAndByTaUserIdAndByType(parameter);
        List<TpTicketVO> liaisonList = Lists.newArrayList();
        tpTicketVOConvert(tpTicketLiaisonList, liaisonList);
        Long[] arr = new Long[]{pageComplaint.getTotal(), pageLiaison.getTotal(), pageRepairs.getTotal()};
        Arrays.sort(arr);
        result.put("repairs", repairsList);
        result.put("complaint", complaintList);
        result.put("liaison", liaisonList);
        result.put("total", arr[2]);

        responseBean.addSuccess(result);
        return responseBean;
    }

    /**
     * 公共方法, 获取一条数据
     *
     * @param map
     * @return
     */
    private TpTicketRecordComment getTicketRecordComment(Map map) {
        List<TpTicketRecordComment> list = tpTicketRecordCommentMapper.selectByTicketId(map);
        return null == list
                ? null : list.size() == 0
                ? null : list.get(0);
    }

    /**
     * 数据转换,并填充数据
     *
     * @param target
     * @param source
     * @return
     */
    public void tpTicketVOConvert(List<TpTicket> source, List<TpTicketVO> target) {

        // 获取联系号码簿（物业号码）
        // List<TpannouncementTel> tpannouncementTel = tpannouncementTelMapper.getTpannouncementTel();

        // 查询参数
        Map<String, Object> lastRecordMap = Maps.newHashMap();
        // 表示查询出最新的一条
        lastRecordMap.put("size", 1);

        source.stream().forEach(e -> {
            TpTicketVO tpTicketVO = new TpTicketVO();
            BeanUtils.copyProperties(e, tpTicketVO);
            // 设置工单编号
            lastRecordMap.put("tickerId", e.getId());
            TpTicketRecordComment comment = getTicketRecordComment(lastRecordMap);
            List<TpTicketRecord> recordList = tpTicketRecordMapper.getTicketRecordByTicketId(e.getCommunityId() + "", e.getId());
            // 报修类型：0:公共区域  1: 房屋质量  2::户内设施  PS : 报修的情况下才有报修类型
            String repairType = e.getRepairType();
            String repairName = repairType == null ?
                    null : "0".equals(repairType) ?
                    "公共区域" : "1".equals(repairType) ?
                    "房屋质量" : "2".equals(repairType) ?
                    "户内设施" : null;
            tpTicketVO.setRepairName(repairName);
            tpTicketVO.setStatus(recordList.get(recordList.size() - 1).getStatus());
            tpTicketVO.setTicketStatusName(recordList.get(recordList.size() - 1).getTicketStatusName());
            tpTicketVO.setTicketRecordDate(recordList.get(recordList.size() - 1).getCreateDate());
            tpTicketVO.setTicketStatusContent(recordList.get(recordList.size() - 1).getContent());
            if (null != comment) {
                tpTicketVO.setCommentContent(comment.getContent());
                tpTicketVO.setCommentCreateDate(comment.getCreateDate());
            }

//            // 0:待分配  1:拒绝受理 2:待处理 3:正在处理 4:待评价 5:已评价 6:被终止
//
//            // 0:待分配  需要出现物业号码簿
//            if ("0".equals(e.getStatus())) {
//                Map<String, Object> map = Maps.newHashMap();
//                map.put("message","联系物业号码簿");
//                map.put("data",tpannouncementTel);
//                tpTicketVO.setContactBook(map);
//            }

            target.add(tpTicketVO);
        });
    }

    @Override
    public ResponseBean getByTypeList(TpTicket tpTicket, Integer pageNum, Integer pageSize) {

        ResponseBean response = new ResponseBean();

        Map<String, Object> parameter = Maps.newHashMap();
        parameter.put("communityId", tpTicket.getCommunityId());
        parameter.put("taUserId", tpTicket.getTaUserId());

        //  1：投诉   2：报修 3：联系物业
        parameter.put("type", tpTicket.getType());

        Page<TpTicket> pagelist = PageHelper.startPage(pageNum, pageSize);
        List<TpTicket> tpTicketList = tpTicketMapper.selectByCommuniytIdAndByTaUserIdAndByType(parameter);

        List<TpTicketVO> tpTicketVOList = Lists.newArrayList();
        tpTicketVOConvert(tpTicketList, tpTicketVOList);
        Map<String, Object> map = Maps.newHashMap();
        map.put("pagelist", tpTicketVOList);
        map.put("total", pagelist.getTotal());

        response.addSuccess(map);

        return response;
    }

    /**
     * 获取报修详情
     *
     * @param communityId
     * @param ticketId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TpTicket getTicketSchedule(String communityId, Integer ticketId) {
        //查看工单详情
        TpTicket ticket = tpTicketMapper.selectByTicketId(communityId, ticketId);
        if (null != ticket) {
            //工单进度
            List<TpTicketRecord> ticketRecordList = tpTicketRecordMapper.getTicketRecordByTicketId(communityId, ticketId);
            //工单回复
            ticketRecordList.stream().forEach(TpTicketRecord -> {
                List<TpTicketRecordComment> ticketRecordCommentList = tpTicketRecordCommentMapper.selectByTicketRecordId(TpTicketRecord);
                //遍历工单下每条对话信息的id去查对话图片
                for (TpTicketRecordComment tpTicketRecordComment : ticketRecordCommentList) {
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("uuid", tpTicketRecordComment.getId());
                    map.put("type", "reply");
                    List<TdImages> tdImagesList = tdImagesMapper.getByUUIDAndByType(map);
                    tpTicketRecordComment.setImgURL(tdImagesList);
                }
                TpTicketRecord.setTicketRecordCommentList(ticketRecordCommentList);
            });

            Map<String, Object> map = Maps.newHashMap();
            map.put("uuid", ticket.getId());
            map.put("type", "service");
            List<TdImages> tdImagesList = tdImagesMapper.getByUUIDAndByType(map);

            // 图片数组
            String[] imgageArr = new String[tdImagesList.size()];

            for (int i = 0; i < tdImagesList.size(); i++) {
                imgageArr[i] = tdImagesList.get(i).getImageUrl();
            }

            ticket.setTdImagesList(imgageArr);
            ticket.setTicketRecordList(ticketRecordList);

            // 把该工单的消息变为 已读
            TpMessage tpMessage = new TpMessage();
            tpMessage.setTicketId(ticket.getId());
            tpMessage.setSource("1");
            tpMessage.setModelType("1");
            tpMessage.setMessageType(ticket.getType());

            tpMessage = tpMessageMapper.selectTicketMessage(tpMessage);
            tpMessage.setReadStatus("1");

            //  变为已读
            tpMessageMapper.updateByPrimaryKeySelective(tpMessage);

        }
        return ticket;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean addAiTicketService(UserElement userElement, String parameter) throws IOException {
        ResponseBean response = new ResponseBean();
        JSONObject jsonObject = JSONObject.parseObject(parameter);
        String imageUrl = (String) jsonObject.get("imageUrl");


        TpTicket tpTicket = JSONObject.parseObject(parameter, TpTicket.class);

        /**
         * 工单表 -> 工单处理表 -> 消息表
         * 依次插入相关数据, 该工单默认的第一条数据(待分配), 是工单标题,
         */

        tpTicket.setCommunityId(userElement.getCommunityId());
        // 2.1以后为ta_user_verify为中心不再是已用户ta_user为中心
        tpTicket.setTaUserId(userElement.getUserVerifyId());
        // 默认待分配
        tpTicket.setStatus("0");
        // 2.1以后为ta_user_verify为中心不再是已用户ta_user为中心
        tpTicket.setCreateUser(userElement.getUserVerifyId());
        tpTicket.setCreateDate(new Date());
        tpTicket.setUpdateUser(userElement.getId());
        //tpTicket.setUpdateDate(new Date());
        //校验此工单是否已存在
        TpTicket tpTicketName= tpTicketMapper.selectTpTicketName(userElement.getCommunityId(),tpTicket.getType(),tpTicket.getTicketTitle());
        if (null != tpTicketName){
            response.addError("工单已存在");
            return  response;
        }
        // 插入工单
        tpTicketMapper.insertSelective(tpTicket);
        insertTdImage(tpTicket, imageUrl, userElement.getId());

        Integer id = tpTicket.getId();
        TpTicketRecord tpTicketRecord = new TpTicketRecord();
        //获取当前插入的信息，维护工单记录表
        TpTicket tpTicketReco = tpTicketMapper.selectByPrimaryKey(id);
        tpTicketRecord.setCommunityId(userElement.getCommunityId());
        tpTicketRecord.setTicketId(tpTicketReco.getId());
        // 1：投诉   2：报修 3：联系物业
        String typeName = "2".equals(tpTicket.getType()) ? "报修" : "1".equals(tpTicket.getType()) ? "投诉" : "3".equals(tpTicket.getType()) ? "联系工单" : "未知类型";
        tpTicketRecord.setContent("您的" + typeName + "正在分配物业处理人员, 若长时间无人处理, 请联系物业! 联系物业号码簿 >");
        tpTicketRecord.setStatus(tpTicketReco.getStatus());
        tpTicketRecord.setCreateUser(userElement.getId());
        tpTicketRecord.setCreateDate(new Date());
        // 插入工单处理表
        tpTicketRecordMapper.insertSelective(tpTicketRecord);


        // 把工单信息添加到消息表
//        insertTicketMessage(tpTicket, userId);
        //1.5版本维护消息推送
        TpMessage message = new TpMessage();
        message.setCommunityId(userElement.getCommunityId());
        message.setTicketId(tpTicket.getId());
        message.setModelType("1");
        message.setMessageType(tpTicket.getType());
        message.setAdviceType("4");
        message.setUuidType("2");
        message.setSource("1");
        //当前插入为超级管理员
         Integer uuserID= toCommunitiesMapper.selectAndmin(userElement.getCommunityId());
         message.setUuid(uuserID);

        TaUserVerify userVerify = taUserVerifyMapper.selectByPrimaryKey(userElement.getUserVerifyId());
        TaUser taUser = taUserMapper.selectByPrimaryKey(userElement.getId());

        String userName = null;
         if (null != userVerify) {
             if(1 == userVerify.getRoleId().intValue()){userName="业主"; }
             if(2 == userVerify.getRoleId().intValue()){userName="家属" ;}
             if(3 == userVerify.getRoleId().intValue()){userName="租客" ;}
             message.setMessageContent(userName+ taUser.getUserName()+"发起了一个工单“"+tpTicket.getTicketTitle()+"”，点击受理分配给合适的人处理");
             message.setStatus("1");
             message.setReadStatus("0");
             // 以房产ID为中心
             message.setCreateUser(userElement.getUserVerifyId());
             message.setCreateDate(new Date());
             tpMessageMapper.insert(message);
         }

        response.addSuccess(tpTicketReco);
        return response;
    }

    /**
     * 存入图片
     *
     * @param tpTicket
     * @param imageUrl
     * @param userId
     * @throws IOException
     */
    private void insertTdImage(TpTicket tpTicket, String imageUrl, Integer userId) {
        if (null == imageUrl || "".equals(imageUrl)) {
            return;
        }
        String[] imgArr = imageUrl.split(",");
        for (String img : imgArr) {
            TdImages tdImages = new TdImages();
            Integer uuId = tpTicket.getId();
            tdImages.setImageUrl(img);
            tdImages.setType(Constant.SERVICE);
            tdImages.setUuid(uuId);
            tdImages.setCreateUser(userId);
            tdImages.setCreateTime(new Date());
            tdImagesMapper.insertSelective(tdImages);
        }

    }


    /**
     * 回复工单
     *
     * @param tpTicketRecordComment
     * @return
     */
    @Override
    public Integer updateTicketsReply(TpTicketRecordComment tpTicketRecordComment, Integer userId) {
        //查询用户名
        TaUser taUser = taUserMapper.selectByPrimaryKey(userId);

       TpTicket  tpTicket= tpTicketMapper.selectByPrimaryKey(tpTicketRecordComment.getTicketId());
       TpTicketRecord ticketRecord= tpTicketRecordMapper.selectTpTicketRecord(tpTicketRecordComment.getTicketId(), Integer.valueOf(tpTicket.getStatus()));

        tpTicketRecordComment.setUserName(taUser.getUserName());
        tpTicketRecordComment.setParentId(tpTicketRecordComment.getTicketRecordCommentId());
        tpTicketRecordComment.setUuid(userId);
        tpTicketRecordComment.setTicketRecordId(ticketRecord.getId());
        tpTicketRecordComment.setUserType(Constant.TICKET_USER_TYPE);
        tpTicketRecordComment.setCreateDate(new Date());
        //插入回复数据
        return tpTicketRecordCommentMapper.insertSelective(tpTicketRecordComment);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean updateTicketContent(Integer ticketId, String parameter, Integer userId) {
        ResponseBean responseBean = new ResponseBean();

        JSONObject jsonObject = JSONObject.parseObject(parameter);
        String imageUrl = (String) jsonObject.get("imageUrl");


        TpTicket tpTicket = JSONObject.parseObject(parameter, TpTicket.class);

        // 删除旧图片链接
        Map<String, Object> map = Maps.newHashMap();
        map.put("uuid", ticketId);
        map.put("type", "service");
        tdImagesMapper.deleteByUuidAndType(map);

        insertTdImage(tpTicket, imageUrl, userId);

        TpTicket ticket = tpTicketMapper.selectByPrimaryKey(ticketId);
        ticket.setTicketTitle(tpTicket.getTicketTitle());
        ticket.setTicketContent(tpTicket.getTicketContent());

        tpTicketMapper.updateByPrimaryKeySelective(ticket);
        // 维护1.5版本消息
        Integer messageTicket= tpMessageMapper.selectTicket(ticketId);
        if (!"".equals(messageTicket)) {
            TpMessage tpMessage = new TpMessage();
            tpMessage.setTicketId(ticketId);
            tpMessage.setMessageContent("工单“" + tpTicket.getTicketTitle() + "”已被分配给您，点击查看并处理");
            tpMessage.setUpdateDate(new Date());
            tpMessage.setUpdateUser(userId);
            tpMessageMapper.updateTickMessage(tpMessage);
        }
        responseBean.addSuccess("操作成功!");
        return responseBean;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseBean stopTpTicketRecord(Integer communityId, Integer ticketId, Integer userId) {
        ResponseBean responseBean = new ResponseBean();
        try {
            TpTicket tpTicket = new TpTicket();
            tpTicket.setStatus("6");
            tpTicket.setId(ticketId);
            tpTicketMapper.updateByPrimaryKeySelective(tpTicket);
            //根据1.4版本需要被终止时，清空当前工单受理人
            tpTicketMapper.updateTpUserId(ticketId);

            TpTicketRecord tpTicketRecord = new TpTicketRecord();
            tpTicketRecord.setStatus("6");
            tpTicketRecord.setTicketId(ticketId);
            tpTicketRecord.setCommunityId(communityId);

            tpTicketRecord.setContent("您的联系单已被您自己终止，如果仍有问题，可以在服务页新增一个报修/投诉/联系单");
            tpTicketRecord.setCreateUser(userId);
            tpTicketRecord.setCreateDate(new Date());
            tpTicketRecordMapper.insertSelective(tpTicketRecord);
            //1.5版本需求推送消息
            TpMessage tpMessage= new TpMessage();
                      tpMessage.setTicketId(ticketId);
                      tpMessage.setStatus("0");
                      tpMessage.setUpdateUser(userId);
                      tpMessage.setUpdateDate(new Date());
                      tpMessageMapper.updateTickMessage(tpMessage);

            //1.5版本推送消息message
            TpMessage message = new TpMessage();
            message.setCommunityId(communityId);
            message.setModelType("1");
            TpTicket tic= tpTicketMapper.selectByTicketId(String.valueOf(communityId),Integer.valueOf(ticketId));
            message.setMessageType(tic.getType());
            message.setAdviceType("4");
            message.setUuid(userId);
            message.setUuidType("2");
            message.setSource("2");
            message.setModelType("1");
            message.setMessageContent("工单“"+tic.getTicketTitle() +"”被住户终止了，点击查看详情");
            message.setStatus("1");
            message.setReadStatus("0");
            message.setCreateUser(userId);
            message.setCreateDate(new Date());
            tpMessageMapper.insert(message);
            return responseBean;
        } catch (Exception e) {
            e.printStackTrace();
            responseBean.addError("服务器异常");
            return responseBean;
        }
    }

    /**
     * 公共方法
     * 把工单插入消息表
     *
     * @param tpTicket 工单
     * @param userId   用户id
     */
    private TpMessage insertTicketMessage(TpTicket tpTicket, Integer userId) {

        TpMessage tpMessage = new TpMessage();
        tpMessage.setCommunityId(tpTicket.getCommunityId());
        tpMessage.setTicketId(tpTicket.getId());
        // 消息类型  1：投诉   2：报修 3：联系物业  4： 访客  5:公告  6:系统通知  7:账单 8:活动
        tpMessage.setMessageType(tpTicket.getType());
        // 通知方式: APP 内通知
        tpMessage.setAdviceType("1");
        // 模板类型为 消息模板
        tpMessage.setModelType("1");
        tpMessage.setUuid(userId);
        // 接收人类型: APP用户
        tpMessage.setUuidType("1");
        // 来源: APP 端用户
        tpMessage.setSource("1");
        // 这里的消息内容对应, 工单标题
        tpMessage.setMessageContent(tpTicket.getTicketTitle());
        tpMessage.setStatus("1");
        // 阅读状态: 0未阅读
        tpMessage.setReadStatus("0");
        tpMessage.setCreateUser(userId);
        tpMessage.setCreateDate(new Date());
        tpMessage.setUpdateUser(userId);
        tpMessage.setUpdateDate(new Date());

        tpMessageMapper.insertSelective(tpMessage);

        return tpMessage;

    }
    @Override
    public ResponseBean addRecordComment(String parameter, Integer verifyId,Integer communityId,String userName) {
        ResponseBean response=new ResponseBean();
        JSONObject object= JSONObject.parseObject(parameter);

        String  content = object.getString("content");
        Integer  ticketId = object.getInteger("ticketId");

        /*根据工单Id和状态查出工单记录ID*/
        TpTicket  tpTicket= tpTicketMapper.selectByPrimaryKey(ticketId);
        TpTicketRecord ticketRecord= tpTicketRecordMapper.selectTpTicketRecord(ticketId, Integer.valueOf(tpTicket.getStatus()));
        TpTicketRecordComment tpTicketRecordComment= new TpTicketRecordComment();
        tpTicketRecordComment.setCommunityId(communityId);
        tpTicketRecordComment.setContent(content);
        tpTicketRecordComment.setTicketId(ticketId);
        tpTicketRecordComment.setTicketRecordId(ticketRecord.getId());
        tpTicketRecordComment.setUuid(verifyId);
        tpTicketRecordComment.setUserType("1");
        tpTicketRecordComment.setUserName(userName);
        tpTicketRecordComment.setCreateDate(new Date());
        tpTicketRecordCommentMapper.insert(tpTicketRecordComment);
        JSONArray contentImg = object.getJSONArray("imageUrl");
        if (null!=contentImg){
            String[] contentImgArray = contentImg.toArray(new String[]{});

            for (String img : contentImgArray) {
                TdImages tdImages = new TdImages();
                tdImages.setImageUrl(img);
                /*注意reply用于标记工单回复类的图片*/
                tdImages.setType("reply");
                tdImages.setUuid(tpTicketRecordComment.getId());
                tdImages.setCreateTime(new Date());
                tdImages.setCreateUser(verifyId);
                tdImagesMapper.insert(tdImages);
            }
        }
        //1.5版本推送消息message
        //工单消息回复最最后一个物业人员

        TpMessage message = new TpMessage();
        message.setTicketId(ticketId);
        message.setCommunityId(communityId);
        message.setModelType("1");
        message.setMessageType(tpTicket.getType());
        message.setAdviceType("4");
        //查询当前工单水处理
        TpTicket ticket= tpTicketMapper.getTicketTpUserId(ticketId,communityId);
        //考虑到工单没有分配，物业人员没有追问，只能塞本小区超级管理员ID
        TpTicketRecordComment recordComment= tpTicketRecordCommentMapper.getUuID(communityId,ticketId);
        Integer uuserID= toCommunitiesMapper.selectAndmin(communityId);
        
        message.setUuid(recordComment==null?uuserID:recordComment.getUuid());
        message.setUuidType("2");
        message.setSource("2");
        message.setMessageContent("工单“"+ tpTicket.getTicketTitle()+"”发起人发来消息："+content+"，点击查看并处理");
        message.setStatus("1");
        message.setReadStatus("0");
        message.setCreateUser(verifyId);
        message.setCreateDate(new Date());
        tpMessageMapper.insert(message);
        response.addSuccess("成功");
        return response;
    }
}
