package com.huiju.estateagents.property.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.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.mapper.TaUserMapper;
import com.huiju.estateagents.property.common.Constant;
import com.huiju.estateagents.property.dao.*;
import com.huiju.estateagents.property.model.*;
import com.huiju.estateagents.property.service.TpTicketService;
import com.huiju.estateagents.property.vo.TpTicketVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 工单表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-02-14
 */
@Service
public class TpTicketServiceImpl extends ServiceImpl<TpTicketMapper, TpTicket> implements TpTicketService {

    @Autowired
    private  TpTicketMapper tpTicketMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TdImagesMapper tdImagesMapper;

    @Autowired
    private TpTicketRecordMapper tpTicketRecordMapper;

    @Autowired
    private TpTicketRecordCommentMapper tpTicketRecordCommentMapper;

//    @Autowired
//    private TaUserMapper taUserMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private TaUserVerifyMapper taUserVerifyMapper;

    @Override
    public ResponseBean ticketLiset(String parameter,Integer communityId) {
         ResponseBean response= new ResponseBean<>();
        TpTicket   ticket= JSONObject.parseObject(parameter, TpTicket.class);

        JSONObject object= JSONObject.parseObject(parameter);
        Integer pageNum = object.getInteger("pageNum");
        Integer pageSize = object.getInteger("pageSize");

        String UserNmae = object.getString("createUserNmae");
        String updateUserNmae = object.getString("updateUserNmae");
        Page<TpTicket> page = new Page<>();
        page.setSize(pageSize == null ? 10 : pageSize);
        page.setCurrent(pageNum == null ? 1 : pageNum);
        IPage<TpTicket> pageInfo = tpTicketMapper.ticketList(page,ticket,UserNmae,updateUserNmae,communityId);
        List<TpTicket> ticketList = pageInfo.getRecords();

        List<TpTicket> tpTicketArrayList= new ArrayList<>();

        for (TpTicket tpTicket:ticketList){
            TpTicketVO tpTicketVO= new TpTicketVO();
            BeanUtils.copyProperties(tpTicket, tpTicketVO);
            /*查询当前受理人*/
            String userName=userMapper.selectByIdUserName(tpTicket.getTpUserId());
            tpTicketVO.setTpUserNmae(userName);

            /*查询当前工单创建人*/
            TaUserVerify taUserVerify= taUserVerifyMapper.selectById(tpTicket.getCreateUser());

//            String createUserNmae=taUserMapper.selectLongNameAndcommunityId(taUserVerify.getUserId());
//            tpTicketVO.setCreateUserNmae(createUserNmae);
            tpTicketArrayList.add(tpTicketVO);
        }
        HashMap map=new HashMap<>();
        map.put("list",tpTicketArrayList);
        map.put("total", pageInfo.getTotal());
        map.put("pageNum", pageInfo.getCurrent());
        map.put("pageSize", pageInfo.getSize());
        response.addSuccess(map);
        return response;
    }

    @Override
    public ResponseBean ticketDetails(String parameter,Integer userID,Integer communityId) {
         ResponseBean response= new ResponseBean();
        JSONObject object= JSONObject.parseObject(parameter);
        Integer ticketId = object.getInteger("id");
        TpTicketVO ticketVO= tpTicketMapper.ticketDetails(ticketId);
        // 从taUserVerify里面获取userID
        TaUserVerify taUserVerify= taUserVerifyMapper.selectById(ticketVO.getCreateUser());
//        TaUser taUser= taUserMapper.selectById(taUserVerify.getUserId());
        /*发起人*/
//        ticketVO.setCreateUserNmae(taUser.getUserName());
        /*发起人手机号码*/
//        ticketVO.setLoginName(taUser.getLoginName());
        /*查询当前受理人*/
        ticketVO.setTpUserNmae(userMapper.selectByIdUserName(ticketVO.getTpUserId()));
        /*所有物业端本小区的人员*/
        ticketVO.setUserList(userMapper.getUser( userID,communityId));
        /*本人*/
        ticketVO.setCurrentUserName(userID);


        /*查询工单类容的图片*/
        QueryWrapper<TdImages> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TdImages::getUuid,ticketId);
        queryWrapper.lambda().eq(TdImages::getType, Constant.SERVICE);
        List<TdImages> tdImages= tdImagesMapper.selectList(queryWrapper);
        List<String> contentImg = new ArrayList<String>();
        for (TdImages images:tdImages){
            contentImg.add(images.getImageUrl());
        }
        ticketVO.setContentImageUrl(contentImg);

        /*工单状态*/
        QueryWrapper<TpTicketRecord> RecordWrapper = new QueryWrapper<>();
        RecordWrapper.lambda().eq(TpTicketRecord::getTicketId,ticketId);
        List<TpTicketRecord> ticketRecordList= tpTicketRecordMapper.selectList(RecordWrapper);
        ticketVO.setRecordList(ticketRecordList);



       for(TpTicketRecord ticketRecord:ticketRecordList){
            /*对话详情*/
           QueryWrapper<TpTicketRecordComment> RecordCommentWrapper = new QueryWrapper<>();
           RecordCommentWrapper.lambda().eq(TpTicketRecordComment::getTicketId,ticketId);
           RecordCommentWrapper.lambda().eq(TpTicketRecordComment::getTicketRecordId,ticketRecord.getId());
           List<TpTicketRecordComment> tpTicketRecordCommentList= tpTicketRecordCommentMapper.selectList(RecordCommentWrapper);
           ticketRecord.setStatusContent(tpTicketRecordCommentList);
           /* 遍历当前对话信息组装图片*/
           for(TpTicketRecordComment tpTicketRecordComment:tpTicketRecordCommentList){
               QueryWrapper<TdImages> RecordCommentImg = new QueryWrapper<>();
               RecordCommentImg.lambda().eq(TdImages::getUuid,tpTicketRecordComment.getId());
            /*注意reply用于标记工单回复类的图片*/
               RecordCommentImg.lambda().eq(TdImages::getType,"reply");
               List<TdImages> ticketRecordCommentImages= tdImagesMapper.selectList(RecordCommentImg);
               tpTicketRecordComment.setImgURL(ticketRecordCommentImages);
           }
       }
        /*根据状态得到相应的步骤名称*/
        for(TpTicketRecord tpTicketRecord:ticketRecordList){
            String statusName= tpTicketRecordMapper.statusName(tpTicketRecord.getStatus());
            tpTicketRecord.setStatusName(statusName);
        }
        response.addSuccess(ticketVO);
        return response;
    }

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

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

        /*根据工单Id和状态查出工单记录ID*/
        TpTicket  tpTicket= tpTicketMapper.selectById(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(id);
        tpTicketRecordComment.setUserType("0");
        tpTicketRecordComment.setUserName(userName);
        tpTicketRecordComment.setCreateDate(LocalDateTime.now());
        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(LocalDateTime.now());
                tdImages.setCreateUser(id);
                tdImagesMapper.insert(tdImages);
            }
        }
        //1.5维护工单对话推送到app消息
        Message message = new Message();
        message.setCommunityId(communityId);
        message.setMessageType(tpTicket.getType());
        message.setTicketId(tpTicket.getId());
        message.setAdviceType("1");
        message.setUuid(tpTicket.getCreateUser());
        message.setModelType("1");
        message.setUuidType("1");
        message.setSource("2");
        message.setMessageContent("物业回复您:"+content);
        message.setStatus("1");
        message.setReadStatus("0");
        message.setCreateUser(tpTicket.getCreateUser());
        message.setCreateDate(LocalDateTime.now());
        message.setTicketId(ticketId);
        response.addSuccess("成功");
        messageMapper.insert(message);
        return response;
    }

    @Override
    public ResponseBean addRecord(String parameter, Integer user, Integer communityId) {
        ResponseBean response=new ResponseBean();

        JSONObject object= JSONObject.parseObject(parameter);
        Integer  ticketId = object.getInteger("ticketId");
        /*当前处理人ID */
        String  status = object.getString("status");
        Integer  userID = object.getInteger("id");
        User userName= userMapper.selectById(userID);

        TpTicket tpTicket= new TpTicket();
        tpTicket.setId(ticketId);
        tpTicket.setStatus("3");
        tpTicket.setTpUserId(userID);
        tpTicket.setUpdateDate(LocalDateTime.now());
        tpTicketMapper.updateById(tpTicket);

        TpTicketRecord tpTicketRecord= new TpTicketRecord();
        tpTicketRecord.setCommunityId(communityId);
        tpTicketRecord.setTicketId(ticketId);
        tpTicketRecord.setContent("您的联系单已经分配给物业处理人员" + userName.getUserName()+",联系方式:" + userName.getLoginName());
        tpTicketRecord.setStatus("3");
        tpTicketRecord.setCreateUser(user);
        tpTicketRecord.setCreateDate(LocalDateTime.now());
        tpTicketRecordMapper.insert(tpTicketRecord);

        //待办模板
        QueryWrapper<TpTicket> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", ticketId);
        queryWrapper.eq("community_id", communityId);
       TpTicket ticket = tpTicketMapper.selectOne(queryWrapper);
        Message message = new Message();
        message.setCommunityId(communityId);
        message.setMessageType(ticket.getType());
        message.setTicketId(ticket.getId());
        message.setAdviceType("4");
        message.setUuid(userID);
        message.setModelType("2");
        message.setUuidType("2");
        message.setSource("2");
        message.setMessageContent("工单“" + ticket.getTicketTitle() + "”已被分配给您，点击查看并处理");
        message.setStatus("1");
        message.setReadStatus("0");
        message.setCreateUser(user);
        message.setCreateDate(LocalDateTime.now());
        message.setTicketId(ticketId);
        messageMapper.insert(message);
        //如果分配给本人维护消息模板
        if (null!=userID&userID.equals(user)){
            message.setModelType("1");
            messageMapper.insert(message);
        }
        //分配成功后推送app
        message.setUuidType("1");
        message.setUuid(ticket.getCreateUser());
        message.setMessageContent("工单“" + ticket.getTicketTitle() + "”已被分配给:"+userName.getUserName());
        message.setAdviceType("1");
        messageMapper.insert(message);
        response.addSuccess("成功");
        return response;
    }

    @Override
    public ResponseBean updateTicketStatus(String parameter, Integer id,Integer communityId,String userName,String LoginName) {
        /*拒绝处理仅在待分配的情况下修改，由前台控制拒绝处理的按钮是否显示*/
        ResponseBean response=  new ResponseBean();
        JSONObject object= JSONObject.parseObject(parameter);
        Integer  ticketId = object.getInteger("ticketId");
        String  textContent = object.getString("textContent");
        TpTicket tpTicket= new TpTicket();
        tpTicket.setId(ticketId);
        tpTicket.setStatus("1");
        tpTicket.setUpdateUser(id);
        tpTicket.setUpdateDate(LocalDateTime.now());
        tpTicketMapper.updateById(tpTicket);
        /*查询当前处理人的名字*/

        TpTicketRecord tpTicketRecord= new TpTicketRecord();
        tpTicketRecord.setTicketId(ticketId);
        tpTicketRecord.setContent("您的报修被物业人员"+userName+"拒绝接受理，原因:"+textContent+",有问题可以联系"+userName+":联系方式:"+LoginName);
        tpTicketRecord.setCommunityId(communityId);
        tpTicketRecord.setStatus("1");
        tpTicketRecord.setCreateUser(id);
        tpTicketRecord.setCreateDate(LocalDateTime.now());
        tpTicketRecordMapper.insert(tpTicketRecord);
        /*把内容添加到对话中*/
        TpTicketRecordComment ticketRecordComment= new TpTicketRecordComment();
        ticketRecordComment.setCommunityId(communityId);
        ticketRecordComment.setTicketId(ticketId);
        ticketRecordComment.setTicketRecordId(tpTicketRecord.getId());
        ticketRecordComment.setUuid(id);
        ticketRecordComment.setUserType("0");
        ticketRecordComment.setContent("拒绝受理，原因——"+textContent);
        ticketRecordComment.setUserName(userName);
        ticketRecordComment.setCreateDate(LocalDateTime.now());
        tpTicketRecordCommentMapper.insert(ticketRecordComment);

        //维护1.5版本
        Message message = new Message();
//        message.setTicketId(ticketId);
//        message.setUpdateUser(id);
//        message.setUpdateDate(LocalDateTime.now());
//        message.setStatus("0");
//        messageMapper.updateTicketMessage(message);

        QueryWrapper<TpTicket> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", ticketId);
        queryWrapper.eq("community_id", communityId);
        TpTicket ticket = tpTicketMapper.selectOne(queryWrapper);
        message.setCommunityId(communityId);
        message.setMessageType(ticket.getType());
        message.setTicketId(ticket.getId());
        message.setAdviceType("1");
        message.setUuid(ticket.getCreateUser());
        message.setModelType("1");
        message.setUuidType("1");
        message.setSource("2");
        message.setMessageContent("您的工单“" + ticket.getTicketTitle() + "”已被拒绝受理");
        message.setStatus("1");
        message.setReadStatus("0");
        message.setCreateUser(id);
        message.setCreateDate(LocalDateTime.now());
        message.setTicketId(ticketId);
        messageMapper.insert(message);
        response.addSuccess("成功");
        return response;
    }

    @Override
    public ResponseBean updateTicket(String parameter, Integer id, Integer communityId, String userName,String longName) {
        ResponseBean response=new ResponseBean();
        JSONObject object= JSONObject.parseObject(parameter);
        String  content = object.getString("content");
        Integer  ticketId = object.getInteger("ticketId");
        TpTicket tpTicket= new TpTicket();
                 tpTicket.setId(ticketId);
                 tpTicket.setStatus("4");
                 tpTicket.setUpdateDate(LocalDateTime.now());
                 tpTicketMapper.updateById(tpTicket);
                 /**维护工单处理表**/
       TpTicketRecord tpTicketRecord = new TpTicketRecord();
        tpTicketRecord.setCommunityId(communityId);
        tpTicketRecord.setTicketId(ticketId);
       TpTicket tpTicketUserID= tpTicketMapper.selectById(ticketId);
        User userNameTpUserId= userMapper.selectById(tpTicketUserID.getTpUserId());
        tpTicketRecord.setContent("物业工作人员"+userName+"已经处理结束,如果没有问题请给好评,联系方式:"+longName);
        tpTicketRecord.setStatus("4");
        tpTicketRecord.setCreateUser(id);
        tpTicketRecord.setCreateDate(LocalDateTime.now());
        tpTicketRecordMapper.insert(tpTicketRecord);
        /*维护对话*/
        TpTicketRecordComment tpTicketRecordComment= new TpTicketRecordComment();
        tpTicketRecordComment.setCommunityId(communityId);
        tpTicketRecordComment.setTicketId(ticketId);
        tpTicketRecordComment.setTicketRecordId(tpTicketRecord.getId());
        tpTicketRecordComment.setUuid(id);
        tpTicketRecordComment.setUserType("0");
        tpTicketRecordComment.setContent("处理结果如下____"+content);
        tpTicketRecordComment.setUserName(userName);
        tpTicketRecordComment.setCreateDate(LocalDateTime.now());
        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(Constant.REPLY);
                tdImages.setUuid(tpTicketRecordComment.getId());
                tdImages.setCreateTime(LocalDateTime.now());
                tdImages.setCreateUser(id);
                tdImagesMapper.insert(tdImages);
            }
        }
        //分配成功后这只messgae消息表status为无效
        messageMapper.updateTickMessageStatus(ticketId);

        // 处理完成后推送app
        QueryWrapper<TpTicket> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", ticketId);
        queryWrapper.eq("community_id", communityId);
        TpTicket ticket = tpTicketMapper.selectOne(queryWrapper);
        Message message= new Message();
        message.setCommunityId(communityId);
        message.setMessageType(ticket.getType());
        message.setTicketId(ticket.getId());
        message.setAdviceType("1");
        message.setUuid(ticket.getCreateUser());
        message.setModelType("1");
        message.setUuidType("1");
        message.setSource("2");
        message.setMessageContent("您的工单“" + ticket.getTicketTitle() + "”已处理完成，请查看详情");
        message.setStatus("1");
        message.setReadStatus("0");
        message.setCreateUser(id);
        message.setCreateDate(LocalDateTime.now());
        message.setTicketId(ticketId);
        messageMapper.insert(message);
        response.addSuccess("成功");
        return response;
    }
}
