package com.huiju.estateagents.property.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.google.common.collect.Lists;
import com.google.common.collect.Maps;
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.entity.TaPerson;
import com.huiju.estateagents.mapper.TaPersonMapper;
import com.huiju.estateagents.property.common.Constant;
import com.huiju.estateagents.property.dao.*;
import com.huiju.estateagents.property.entity.TpRepairType;
import com.huiju.estateagents.property.exception.WisdomException;
import com.huiju.estateagents.property.mapper.TpRepairTypeMapper;
import com.huiju.estateagents.property.model.*;
import com.huiju.estateagents.property.service.TpTicketService;
import com.huiju.estateagents.property.vo.TpTicketVO;
import com.huiju.estateagents.service.ISysSmsEventService;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
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.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

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

    @Autowired
    private  TpTicketMapper tpTicketMapper;

    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private TdImagesMapper tdImagesMapper;

    @Autowired
    private TpTicketRecordMapper tpTicketRecordMapper;

    @Autowired
    private TpTicketRecordCommentMapper tpTicketRecordCommentMapper;

    @Autowired
    private TpRepairTypeMapper repairTypeMapper;

//    @Autowired
//    private MessageMapper messageMapper;

    @Autowired
    private TaUserVerifyMapper taUserVerifyMapper;

    @Autowired
    private TaPersonMapper taPersonMapper;
    /** 缴费项表 **/
    @Autowired
    private BillMapper billMapper;

    /** 缴费单 **/
    @Autowired
    private BillInvoiceMapper billInvoiceMapper;

    @Autowired
    private ISysSmsEventService sysSmsEventService;

    @Override
    public ResponseBean ticketLiset(String parameter,Integer orgId) {
         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,orgId);
        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);
            TaUser taUser = taUserMapper.selectById(tpTicket.getTpUserId());
            if (null != taUser) {
                tpTicketVO.setTpUserNmae(taUser.getUserName());
            }

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

            TaPerson person =taPersonMapper.selectById(tpTicket.getCreateUser());
            tpTicketVO.setCreateUserNmae(StringUtils.isNotEmpty(person.getName()) ? person.getName() : person.getNickname());
            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 orgId) {
         ResponseBean response= new ResponseBean();
        JSONObject object= JSONObject.parseObject(parameter);
        Integer ticketId = object.getInteger("id");
        TpTicketVO ticketVO= tpTicketMapper.ticketDetails(ticketId);
        // 从taUserVerify里面获取userID
        TaPerson taPerson = taPersonMapper.selectById(ticketVO.getPersonId());
        /*发起人*/
        ticketVO.setCreateUserNmae(StringUtils.isNotEmpty(taPerson.getName()) ? taPerson.getName() : taPerson.getNickname());
        /*发起人手机号码*/
        ticketVO.setLoginName(taPerson.getPhone());
        /*查询当前受理人*/
        TaUser taUser = taUserMapper.selectById(ticketVO.getTpUserId());
        if (null != taUser){
            ticketVO.setTpUserNmae(taUser.getUserName());
        }

        /*所有物业端本小区的人员*/
        QueryWrapper<TaUser> taUserQueryWrapper =new QueryWrapper<>();
        taUserQueryWrapper.eq("org_id",orgId);
//        taUserQueryWrapper.ne("user_id",userID);
        List<String> typeList = new ArrayList<>();
        typeList.add("life-consultant");
        typeList.add("worker");
        taUserQueryWrapper.in("type",typeList);
        ticketVO.setTpUsersList(taUserMapper.selectList(taUserQueryWrapper));
        /*本人*/
        if (null != userID){
            ticketVO.setCurrentUserName(userID.toString());
        }


        /*查询工单类容的图片*/
        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);
        }

        // 是否缴费
        ticketVO.setIsPay(false);
        BillInvoice billInvoice = billInvoiceMapper.selectById(ticketVO.getBillInvoiceId());
        if (null!= billInvoice && "1".equals(billInvoice.getBillStatus())){
            ticketVO.setIsPay(true);
        }
        // 当前提单人的相关信息
        LambdaQueryWrapper<TaUserVerify> lambdaQueryWrapper = new LambdaQueryWrapper<TaUserVerify>();
        lambdaQueryWrapper.eq(TaUserVerify::getPersonId,taPerson.getPersonId());
        lambdaQueryWrapper.eq(TaUserVerify::getVerifyStatus,"1");
        List<TaUserVerify> taUserVerifies = taUserVerifyMapper.selectList(lambdaQueryWrapper);
        ticketVO.setUserVerifyList(taUserVerifies);
        response.addSuccess(ticketVO);
        return response;
    }

    public ResponseBean addRecordComment(String parameter, Integer id,Integer orgId,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.setOrgId(orgId);
        tpTicketRecordComment.setContent(content);
        tpTicketRecordComment.setTicketId(ticketId);
        tpTicketRecordComment.setTicketRecordId(ticketRecord.getId());
        tpTicketRecordComment.setUuid(id.toString());
        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.toString());
                tdImagesMapper.insert(tdImages);
            }
        }
        //1.5维护工单对话推送到app消息
        Message message = new Message();
        message.setOrgId(orgId);
        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 orgId) {
        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");
        TaUser taUser = taUserMapper.selectById(userID);

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

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

        //待办模板
        QueryWrapper<TpTicket> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", ticketId);
        queryWrapper.eq("org_id", orgId);
        TpTicket ticket = tpTicketMapper.selectOne(queryWrapper);
        Message message = new Message();
        message.setOrgId(orgId);
        message.setMessageType(ticket.getType());
        message.setTicketId(ticket.getId());
        message.setAdviceType("4");
        message.setUuid(userID.toString());
        message.setModelType("2");
        message.setUuidType("2");
        message.setSource("2");
        message.setMessageContent("工单“" + ticket.getTicketTitle() + "”已被分配给您，点击查看并处理");
        message.setStatus("1");
        message.setReadStatus("0");
        message.setCreateUser(user.toString());
        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() + "”已被分配给:"+taUser.getUserName());
        message.setAdviceType("1");
//        messageMapper.insert(message);
        response.addSuccess("成功");
        return response;
    }

    @Override
    public ResponseBean addWxRecord(String parameter, Integer user, Integer orgId) {
        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);
        TaUser taUser = taUserMapper.selectById(userID);

        TpTicket tpTicket= new TpTicket();
        tpTicket.setId(ticketId);
        tpTicket.setWorkerId(userID);
        tpTicket.setWorkerName(taUser.getUserName());
        tpTicket.setUpdateDate(LocalDateTime.now());
        tpTicketMapper.updateById(tpTicket);

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

        // 发送短信给维修工人
        TpTicket tpTicketDetail = tpTicketMapper.selectById(ticketId);
        TaPerson taPerson = taPersonMapper.selectById(tpTicketDetail.getPersonId());
        TaUser lifeUser = taUserMapper.selectById(tpTicketDetail.getTpUserId());
        sysSmsEventService.sendSMSOfRepairTicket(taUser.getPhone(),lifeUser.getUserName(),lifeUser.getPhone(),taPerson.getPhone());

        //待办模板
        QueryWrapper<TpTicket> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", ticketId);
        queryWrapper.eq("org_id", orgId);
       TpTicket ticket = tpTicketMapper.selectOne(queryWrapper);
        Message message = new Message();
        message.setOrgId(orgId);
        message.setMessageType(ticket.getType());
        message.setTicketId(ticket.getId());
        message.setAdviceType("4");
        message.setUuid(userID.toString());
        message.setModelType("2");
        message.setUuidType("2");
        message.setSource("2");
        message.setMessageContent("工单“" + ticket.getTicketTitle() + "”已被分配给您，点击查看并处理");
        message.setStatus("1");
        message.setReadStatus("0");
        message.setCreateUser(user.toString());
        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() + "”已被分配给:"+taUser.getUserName());
        message.setAdviceType("1");
//        messageMapper.insert(message);
        response.addSuccess("成功");
        return response;
    }

    @Override
    public ResponseBean updateTicketStatus(String parameter, Integer id,Integer orgId,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.toString());
        tpTicket.setUpdateDate(LocalDateTime.now());
        tpTicketMapper.updateById(tpTicket);
        /*查询当前处理人的名字*/

        TpTicketRecord tpTicketRecord= new TpTicketRecord();
        tpTicketRecord.setTicketId(ticketId);
        tpTicketRecord.setContent("您的报修被物业人员"+userName+"拒绝接受理，原因:"+textContent+",有问题可以联系"+userName+":联系方式:"+LoginName);
        tpTicketRecord.setOrgId(orgId);
        tpTicketRecord.setStatus("1");
        tpTicketRecord.setCreateUser(id.toString());
        tpTicketRecord.setCreateDate(LocalDateTime.now());
        tpTicketRecordMapper.insert(tpTicketRecord);
        /*把内容添加到对话中*/
        TpTicketRecordComment ticketRecordComment= new TpTicketRecordComment();
        ticketRecordComment.setOrgId(orgId);
        ticketRecordComment.setTicketId(ticketId);
        ticketRecordComment.setTicketRecordId(tpTicketRecord.getId());
        ticketRecordComment.setUuid(id.toString());
        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("org_id", orgId);
        TpTicket ticket = tpTicketMapper.selectOne(queryWrapper);
        message.setOrgId(orgId);
        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.toString());
        message.setCreateDate(LocalDateTime.now());
        message.setTicketId(ticketId);
//        messageMapper.insert(message);
        response.addSuccess("成功");
        return response;
    }

    @Override
    public ResponseBean updateTicket(String parameter, Integer id, Integer orgId, 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.setOrgId(orgId);
        tpTicketRecord.setTicketId(ticketId);
       TpTicket tpTicketUserID= tpTicketMapper.selectById(ticketId);
//        User userNameTpUserId= userMapper.selectById(tpTicketUserID.getTpUserId());
//        TaUser taUser = taUserMapper.selectById(tpTicketUserID.getTaUserId());
        tpTicketRecord.setContent("物业工作人员"+userName+"已经处理结束,如果没有问题请给好评,联系方式:"+longName);
        tpTicketRecord.setStatus("4");
        tpTicketRecord.setCreateUser(id.toString());
        tpTicketRecord.setCreateDate(LocalDateTime.now());
        tpTicketRecordMapper.insert(tpTicketRecord);
        /*维护对话*/
        TpTicketRecordComment tpTicketRecordComment= new TpTicketRecordComment();
        tpTicketRecordComment.setOrgId(orgId);
        tpTicketRecordComment.setTicketId(ticketId);
        tpTicketRecordComment.setTicketRecordId(tpTicketRecord.getId());
        tpTicketRecordComment.setUuid(id.toString());
        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.toString());
                tdImagesMapper.insert(tdImages);
            }
        }
        //分配成功后这只messgae消息表status为无效
//        messageMapper.updateTickMessageStatus(ticketId);

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


    @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("orgId", tpTicket.getOrgId());
        parameter.put("personId", tpTicket.getPersonId());

        //  1：投诉   2：报修 3：联系物业
        parameter.put("type", 2);
        // 报修
        Page<TpTicket> pageRepairs = new Page(pageNum, pageSize);
        IPage<TpTicket> tpTicketIPage = tpTicketMapper.selectByCommuniytIdAndByTaUserIdAndByType(pageRepairs, tpTicket.getType(),tpTicket.getPersonId(),tpTicket.getOrgId());
        List<TpTicket> tpTicketRepairsList = tpTicketIPage.getRecords();
        List<TpTicketVO> repairsList = Lists.newArrayList();
        tpTicketVOConvert(tpTicketRepairsList, repairsList);

        // 投诉
        //  1：投诉   2：报修 3：联系物业
        parameter.put("type", 1);
        Page<TpTicket> pageComplaint = new Page(pageNum, pageSize);
        IPage<TpTicket> tpTicketIPageComplaint = tpTicketMapper.selectByCommuniytIdAndByTaUserIdAndByType(pageComplaint, tpTicket.getType(), tpTicket.getPersonId(),tpTicket.getOrgId());
        List<TpTicket> tpTicketComplaintList = tpTicketIPageComplaint.getRecords();
        List<TpTicketVO> complaintList = Lists.newArrayList();
        tpTicketVOConvert(tpTicketComplaintList, complaintList);

        // 联系工单
        //  1：投诉   2：报修 3：联系物业
        parameter.put("type", 3);
        Page<TpTicket> pageLiaison = new Page(pageNum, pageSize);
        IPage<TpTicket> tpTicketIPageLiaison = tpTicketMapper.selectByCommuniytIdAndByTaUserIdAndByType(pageLiaison, tpTicket.getType(),tpTicket.getPersonId(),tpTicket.getOrgId());
        List<TpTicket> tpTicketLiaisonList = tpTicketIPageLiaison.getRecords();
        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.getOrgId() + "", e.getId());
            // 报修类型：0:公共区域  1: 房屋质量  2::户内设施  PS : 报修的情况下才有报修类型
            String repairType = e.getRepairType();
            TpRepairType tpRepairType = repairTypeMapper.selectById(repairType);
            if (null != tpRepairType){
                String repairName =  tpRepairType.getTypeName();
                tpTicketVO.setRepairName(repairName);
            }
            tpTicketVO.setStatus(recordList.get(recordList.size() - 1).getStatus());
            tpTicketVO.setTicketStatusName(recordList.get(recordList.size() - 1).getTicketStatusName());
            tpTicketVO.setTicketRecordDate(Date.from(recordList.get(recordList.size() - 1).getCreateDate().atZone(ZoneId.systemDefault()).toInstant()));
            tpTicketVO.setTicketStatusContent(recordList.get(recordList.size() - 1).getContent());
            if (null != comment) {
                tpTicketVO.setCommentContent(comment.getContent());
                tpTicketVO.setCommentCreateDate(Date.from(comment.getCreateDate().atZone(ZoneId.systemDefault()).toInstant()));
            }

//            // 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);
//            }
            // 当前提单人的相关信息
            LambdaQueryWrapper<TaUserVerify> lambdaQueryWrapper = new LambdaQueryWrapper<TaUserVerify>();
            lambdaQueryWrapper.eq(TaUserVerify::getPersonId,e.getPersonId());
            lambdaQueryWrapper.eq(TaUserVerify::getVerifyStatus,"1");
            List<TaUserVerify> taUserVerifies = taUserVerifyMapper.selectList(lambdaQueryWrapper);
            tpTicketVO.setUserVerifyList(taUserVerifies);

            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("orgId", tpTicket.getOrgId());
        parameter.put("taUserId", tpTicket.getPersonId());

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

        Page<TpTicket> pagelist = new Page<>(pageNum, pageSize);
        IPage<TpTicket> tpTicketIPage = tpTicketMapper.selectByCommuniytIdAndByTaUserIdAndByType(pagelist, tpTicket.getType(),tpTicket.getPersonId(),tpTicket.getOrgId());
        List<TpTicket> tpTicketList = tpTicketIPage.getRecords();

        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 orgId
     * @param ticketId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TpTicket getTicketSchedule(String orgId, Integer ticketId) {
        //查看工单详情
        TpTicket ticket = tpTicketMapper.selectById(ticketId);
        if (null != ticket) {
            //工单进度
            List<TpTicketRecord> ticketRecordList = tpTicketRecordMapper.getTicketRecordByTicketId(orgId, 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);
            // 报修类型：0:公共区域  1: 房屋质量  2::户内设施  PS : 报修的情况下才有报修类型
            String repairType = ticket.getRepairType();
            TpRepairType tpRepairType = repairTypeMapper.selectById(repairType);
            if (null != tpRepairType){
                String repairName = tpRepairType.getTypeName();
                ticket.setRepairName(repairName);
            }

//            // 把该工单的消息变为 已读
//            TpMessage tpMessage = new TpMessage();
//            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(String personId, 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);

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


        tpTicket.setOrgId(taPerson.getOrgId());
        // 2.1以后为ta_user_verify为中心不再是已用户ta_user为中心
        tpTicket.setPersonId(personId);
        // 默认待分配
        tpTicket.setStatus("0");
        // 2.1以后为ta_user_verify为中心不再是已用户ta_user为中心
        tpTicket.setCreateUser(personId);
        tpTicket.setCreateDate(LocalDateTime.now());
        tpTicket.setUpdateUser(personId);
        //tpTicket.setUpdateDate(new Date());
        //校验此工单是否已存在
        TpTicket tpTicketName= tpTicketMapper.selectTpTicketName(1,tpTicket.getType(),tpTicket.getTicketTitle());
        if (null != tpTicketName){
            response.addError("工单已存在");
            return  response;
        }
        // 插入工单
        tpTicketMapper.insert(tpTicket);
        insertTdImage(tpTicket, imageUrl, personId);

        Integer id = tpTicket.getId();
        TpTicketRecord tpTicketRecord = new TpTicketRecord();
        //获取当前插入的信息，维护工单记录表
        TpTicket tpTicketReco = tpTicketMapper.selectById(id);
        tpTicketRecord.setOrgId(taPerson.getOrgId());
        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(personId);
        tpTicketRecord.setCreateDate(LocalDateTime.now());
        // 插入工单处理表
        tpTicketRecordMapper.insert(tpTicketRecord);
        // 推物业端，推这个小区下的所有管理员
//        List<TpUser> tpUserList= tpUserMapper.selectCommunityId(userElement.getOrgId());
//        for (TpUser tpUser:tpUserList) {
//            Map<String, Object> mapProp = new HashMap<>();
//            mapProp.put("communityId", userElement.getOrgId());
//            mapProp.put("createUserId", userElement.getUserVerifyId());
//            mapProp.put("ticketId", tpTicket.getId());
//            mapProp.put("title", tpTicket.getTicketTitle());
//            mapProp.put("name", userElement.getUserName());
//            mapProp.put("tpUserId", tpUser.getId());
//            applicationContext.publishEvent(new MessageEvent(mapProp, Constant.TICKET_ADD, mapProp));
//        }


        response.addSuccess(tpTicketReco);
        return response;
    }

    /**
     * 存入图片
     *
     * @param tpTicket
     * @param imageUrl
     * @param pesonId
     * @throws IOException
     */
    private void insertTdImage(TpTicket tpTicket, String imageUrl, String pesonId) {
        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(pesonId);
            tdImages.setCreateTime(LocalDateTime.now());
            tdImagesMapper.insert(tdImages);
        }

    }


    /**
     * 回复工单
     *
     * @param tpTicketRecordComment
     * @return
     */
    @Override
    public Integer updateTicketsReply(TpTicketRecordComment tpTicketRecordComment, String personId) {
        //查询用户名
//        User taUser = userMapper.selectById(userId);
        TaPerson  taPerson = taPersonMapper.selectById(personId);

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

        tpTicketRecordComment.setUserName(taPerson.getName());
        tpTicketRecordComment.setParentId(tpTicketRecordComment.getId());
        tpTicketRecordComment.setUuid(personId);
        tpTicketRecordComment.setTicketRecordId(ticketRecord.getId());
        tpTicketRecordComment.setUserType(Constant.TICKET_USER_TYPE);
        tpTicketRecordComment.setCreateDate(LocalDateTime.now());
        //插入回复数据
        return tpTicketRecordCommentMapper.insert(tpTicketRecordComment);

    }

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

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


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

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

        insertTdImage(tpTicket, imageUrl, personId);

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

        tpTicketMapper.updateById(ticket);
        // 维护1.5版本消息
//        Integer messageTicket= tpMessageMapper.selectTicket(ticketId);
//        if (!"".equals(messageTicket)) {
//            TpMessage tpMessage = new TpMessage();
//            tpMessage.setMessageContent("工单“" + tpTicket.getTicketTitle() + "”已被分配给您，点击查看并处理");
//            tpMessage.setUpdateDate(new Date());
//            tpMessage.setUpdateUser(userElement.getUserVerifyId());
//            tpMessageMapper.updateTickMessage(tpMessage);
//        }
        // 修改消息以后推送物业端
        // 推物业端，推这个小区下的所有管理员
//        List<TpUser> tpUserList= tpUserMapper.selectCommunityId(ticket.getOrgId());
//        for (TpUser tpUser:tpUserList) {
//            Map<String, Object> mapProp = new HashMap<>();
//            mapProp.put("communityId", ticket.getOrgId());
//            mapProp.put("createUserId", userElement.getUserVerifyId());
//            mapProp.put("ticketId", ticketId);
//            mapProp.put("title", tpTicket.getTicketTitle());
//            mapProp.put("name", userElement.getUserName());
//            mapProp.put("tpUserId", tpUser.getId());
//            applicationContext.publishEvent(new MessageEvent(mapProp, Constant.TICKET_UPDATE, mapProp));
//        }
        responseBean.addSuccess("操作成功!");
        return responseBean;
    }

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

            TpTicketRecord tpTicketRecord = new TpTicketRecord();
            tpTicketRecord.setStatus("6");
            tpTicketRecord.setTicketId(ticketId);
            tpTicketRecord.setOrgId(orgId);

            tpTicketRecord.setContent("您的联系单已被您自己终止，如果仍有问题，可以在服务页新增一个报修/投诉/联系单");
            tpTicketRecord.setCreateUser(personId);
            tpTicketRecord.setCreateDate(LocalDateTime.now());
            tpTicketRecordMapper.insert(tpTicketRecord);
            // 终止后维护tp_ticket_record_comment对话
            String createUser= tpTicketMapper.selectById(ticketId).getCreateUser();
//            TaUserVerify taUserVerify= taUserVerifyMapper.selectById(createUser);

//            User taUser= userMapper.selectById(taUserVerify.getPersonId());
            TaUser taUser = taUserMapper.selectById(createUser);
            TpTicketRecordComment tpTicketRecordComment = new TpTicketRecordComment();
            tpTicketRecordComment.setOrgId(orgId);
            tpTicketRecordComment.setTicketId(ticketId);
            tpTicketRecordComment.setTicketRecordId(tpTicketRecord.getId());
            tpTicketRecordComment.setUuid(personId);
            tpTicketRecordComment.setUserName(taUser.getUserName());
            tpTicketRecordComment.setContent("业主终止工单，原因——无");
            tpTicketRecordComment.setCreateDate(LocalDateTime.now());
            tpTicketRecordCommentMapper.insert(tpTicketRecordComment);

            TpTicket ticket= tpTicketMapper.selectById(ticketId);
            // 推物业端，推这个小区下的所有管理员
//            List<TpUser> tpUserList= tpUserMapper.selectCommunityId(communityId);
//            for (TpUser tpUser:tpUserList) {
//                Map<String, Object> mapProp = new HashMap<>();
//                mapProp.put("communityId", communityId);
//                mapProp.put("createUserId", userElement.getUserVerifyId());
//                mapProp.put("title", ticket.getTicketTitle());
//                mapProp.put("name", userElement.getUserName());
//                mapProp.put("ticketId", ticketId);
//                mapProp.put("tpUserId", tpUser.getId());
//                applicationContext.publishEvent(new MessageEvent(mapProp, Constant.TICKET_TERMINATION, mapProp));
//            }
            return responseBean;
        } catch (Exception e) {
            e.printStackTrace();
            responseBean.addError("服务器异常");
            return responseBean;
        }
    }

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

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

//        messageMapper.insert(tpMessage);

        return tpMessage;

    }
    @Override
    public ResponseBean addWxRecordComment(String parameter, String verifyId,Integer orgId,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.selectById(ticketId);
        TpTicketRecord ticketRecord= tpTicketRecordMapper.selectTpTicketRecord(ticketId, Integer.valueOf(tpTicket.getStatus()));
        TpTicketRecordComment tpTicketRecordComment= new TpTicketRecordComment();
        tpTicketRecordComment.setOrgId(orgId);
        tpTicketRecordComment.setContent(content);
        tpTicketRecordComment.setTicketId(ticketId);
        tpTicketRecordComment.setTicketRecordId(ticketRecord.getId());
        tpTicketRecordComment.setUuid(verifyId);
        tpTicketRecordComment.setUserType("1");
        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(verifyId);
                tdImagesMapper.insert(tdImages);
            }
        }
        //1.5版本推送消息message
        //工单消息回复最最后一个物业人员

        Message message = new Message();
        message.setOrgId(orgId);
        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);
//        // 查询工单创建人名称
//        TaUserVerify taUserVerify = taUserVerifyMapper.selectByPrimaryKey(ticket.getCreateUser());
//        TaUser taUser = taUserMapper.selectByPrimaryKey(taUserVerify.getUserId());
        // app推送物业端的消息
//        Map<String,Object> mapPorp = new HashMap<>();
//        mapPorp.put("communityId",communityId);
//        mapPorp.put("createUserId",tpTicket.getCreateUser());
//        mapPorp.put("uuId",recordComment==null?uuserID:recordComment.getUuid());
//        mapPorp.put("ticketId",ticketId);
//        mapPorp.put("replyCount","业主"+taUser.getUserName()+"回复了工单“"+ticket.getTicketTitle()+"”，请处理");
//        mapPorp.put("uuidType",Constant.UUID_TYPE_PROP);
//        mapPorp.put("source",Constant.SOURCE_APP);
//        applicationContext.publishEvent(new MessageEvent(tpTicket, Constant.TICKET_REPLY_PROP,mapPorp));
        response.addSuccess("成功");
        return response;
    }

    /**
     * 添加工单费用
     *
     * @param parameter
     * @param userId
     * @param orgId
     * @return
     */
    @Transactional
    @Override
    public ResponseBean updateTicketPrice(String parameter, Integer userId, Integer orgId) {
        TpTicketVO ticket = JSONObject.parseObject(parameter, TpTicketVO.class);
        TpTicket tpTicket = tpTicketMapper.selectById(ticket.getId());

        // 新建缴费项
        Bill bill = new Bill();
        bill.setBillName(tpTicket.getTicketTitle());
        bill.setBillExplain(ticket.getPriceExplain());
        bill.setEndDate(Date.from(LocalDateTime.now().plusMonths(1).atZone( ZoneId.systemDefault()).toInstant()));
        bill.setPayPrice(ticket.getPrice().toString());

        bill.setPayedNum(0);
        bill.setBillStatus("0");
        bill.setCreateDate(new Date());
        bill.setCreateUser(userId);
        bill.setOrgId(orgId);
        bill.setPayTotalNum(ticket.getPrice());
        bill.setUnpayedNum(ticket.getPrice());
        billMapper.insert(bill);

        // 新增缴费单
        BillInvoice billInvoice = new BillInvoice();
        billInvoice.setOrgId(orgId);
        billInvoice.setBillId(bill.getId());

        // 获取房间号
        QueryWrapper<TaUserVerify> taUserVerifyQueryWrapper = new QueryWrapper<>();
        taUserVerifyQueryWrapper.eq("verify_status","1");
        taUserVerifyQueryWrapper.eq("person_id",tpTicket.getPersonId());
        List<TaUserVerify> userVerifyList = taUserVerifyMapper.selectList(taUserVerifyQueryWrapper);
        billInvoice.setRoomNoId(userVerifyList.get(0).getRoomNoId());
        billInvoice.setBillInvoiceExplain(bill.getBillExplain());
        billInvoice.setPayPrice(Integer.valueOf(bill.getPayPrice()));
        billInvoice.setBillStatus("0");
        billInvoice.setCreateUser(userId);
        billInvoice.setCreateDate(new Date());
        billInvoice.setStatus(1);

        billInvoiceMapper.insert(billInvoice);

        // 返更新ticket
        tpTicket.setPrice(ticket.getPrice());
        tpTicket.setBillInvoiceId(billInvoice.getId());
        tpTicketMapper.updateById(tpTicket);
        tpTicket.setPriceExplain(ticket.getPriceExplain());
        return ResponseBean.success(tpTicket);
    }

    /**
     * 完成工单
     *
     * @param parameter
     * @param userId
     * @param orgId
     * @param userName
     * @param loginName
     * @return
     */
    @Override
    public ResponseBean endTicket(String parameter, Integer userId, Integer orgId, String userName, String loginName) {
        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.setOrgId(orgId);
        tpTicketRecord.setTicketId(ticketId);
        tpTicketRecord.setContent("物业工作人员"+userName+"置为已完成！");
        tpTicketRecord.setStatus("4");
        tpTicketRecord.setCreateUser(userId.toString());
        tpTicketRecord.setCreateDate(LocalDateTime.now());
        tpTicketRecordMapper.insert(tpTicketRecord);
        response.addSuccess("成功");
        return response;
    }

    /**
     * 获取维修人员的工单列表
     *
     * @param pageNum
     * @param pageSize
     * @param userId
     * @param orgId
     * @return
     */
    @Override
    public ResponseBean getWorkerList(Integer pageNum, Integer pageSize, Integer userId, Integer orgId) {
        IPage<TpTicket> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<TpTicket> tpTicketLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tpTicketLambdaQueryWrapper.eq(TpTicket::getOrgId,orgId);
        tpTicketLambdaQueryWrapper.eq(TpTicket::getTpUserId,userId);
        tpTicketLambdaQueryWrapper.orderByDesc(TpTicket::getCreateDate);
        IPage<TpTicket> tpTicketIPage = tpTicketMapper.selectPage(page, tpTicketLambdaQueryWrapper);
        List<TpTicket> tpTicketList = tpTicketIPage.getRecords();

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

        return ResponseBean.success(map);
    }
}
