package com.fs.his.service.impl;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fs.common.service.impl.SmsServiceImpl;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.event.TemplateBean;
import com.fs.event.TemplateEvent;
import com.fs.event.TemplateListenEnum;
import com.fs.event.TemplateListener;
import com.fs.his.domain.*;
import com.fs.his.dto.FsInquiryOrderPatientDTO;
import com.fs.his.dto.PayloadDTO;
import com.fs.his.mapper.*;
import com.fs.his.param.FsFollowReportParam;
import com.fs.his.param.FsInquiryOrderMsgListDParam;
import com.fs.his.param.ImMsgParam;
import com.fs.his.service.IFsFollowReportService;
import com.fs.his.service.IFsInquiryOrderReportService;
import com.fs.his.vo.FsInquiryOrderMsgListDVO;
import com.fs.im.config.IMConfig;
import com.fs.im.dto.OpenImMsgCallBackResponse;
import com.fs.im.service.IImService;
import com.fs.im.vo.OpenImMsgCallBackVO;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import com.fs.watch.domain.WatchDeviceInfo;
import com.fs.watch.mapper.WatchDeviceInfoMapper;
import com.fs.watch.service.DeviceSetUpService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.fs.his.service.IFsInquiryOrderMsgService;

/**
 * 图文订单Service业务层处理
 *
 * @author fs
 * @date 2023-06-12
 */
@Slf4j
@Service
public class FsInquiryOrderMsgServiceImpl implements IFsInquiryOrderMsgService
{
    @Autowired
    private FsInquiryOrderMsgMapper fsInquiryOrderMsgMapper;
    @Autowired
    private IFsFollowReportService fsFollowReportService;
    @Autowired
    @Lazy
    private FsFollowReportMapper fsFollowReportMapper;
    @Autowired
    private FsDoctorMapper  doctorMapper;
    @Lazy
    @Autowired
    SmsServiceImpl smsService;
    @Autowired
    FsUserMapper fsUserMapper;
    @Autowired
    ApplicationEventPublisher publisher;
    @Autowired
    private FsPrescribeMapper fsPrescribeMapper;
    @Autowired
    private IFsInquiryOrderReportService fsInquiryOrderReportService;
    @Autowired
    private WatchDeviceInfoMapper watchDeviceInfoMapper;
    @Autowired
    private DeviceSetUpService deviceSetUpService;

//    @Autowired
//    TemplateListener publisher;
    Logger logger= LoggerFactory.getLogger(getClass());
    /**
     * 查询图文订单
     *
     * @param msgId 图文订单主键
     * @return 图文订单
     */
    @Override
    public FsInquiryOrderMsg selectFsInquiryOrderMsgByMsgId(Long msgId)
    {
        return fsInquiryOrderMsgMapper.selectFsInquiryOrderMsgByMsgId(msgId);
    }

    /**
     * 查询图文订单列表
     *
     * @param fsInquiryOrderMsg 图文订单
     * @return 图文订单
     */
    @Override
    public List<FsInquiryOrderMsg> selectFsInquiryOrderMsgList(FsInquiryOrderMsg fsInquiryOrderMsg)
    {
        return fsInquiryOrderMsgMapper.selectFsInquiryOrderMsgList(fsInquiryOrderMsg);
    }

    /**
     * 新增图文订单
     *
     * @param fsInquiryOrderMsg 图文订单
     * @return 结果
     */
    @Override
    public int insertFsInquiryOrderMsg(FsInquiryOrderMsg fsInquiryOrderMsg)
    {
        fsInquiryOrderMsg.setCreateTime(DateUtils.getNowDate());
        return fsInquiryOrderMsgMapper.insertFsInquiryOrderMsg(fsInquiryOrderMsg);
    }

    /**
     * 修改图文订单
     *
     * @param fsInquiryOrderMsg 图文订单
     * @return 结果
     */
    @Override
    public int updateFsInquiryOrderMsg(FsInquiryOrderMsg fsInquiryOrderMsg)
    {
        return fsInquiryOrderMsgMapper.updateFsInquiryOrderMsg(fsInquiryOrderMsg);
    }

    /**
     * 批量删除图文订单
     *
     * @param msgIds 需要删除的图文订单主键
     * @return 结果
     */
    @Override
    public int deleteFsInquiryOrderMsgByMsgIds(Long[] msgIds)
    {
        return fsInquiryOrderMsgMapper.deleteFsInquiryOrderMsgByMsgIds(msgIds);
    }

    /**
     * 删除图文订单信息
     *
     * @param msgId 图文订单主键
     * @return 结果
     */
    @Override
    public int deleteFsInquiryOrderMsgByMsgId(Long msgId)
    {
        return fsInquiryOrderMsgMapper.deleteFsInquiryOrderMsgByMsgId(msgId);
    }

    @Override
    public void saveMsg(ImMsgParam messageInfo) {
        if (messageInfo.getCallbackCommand().equals("C2C.CallbackAfterMsgWithDraw")){
            fsInquiryOrderMsgMapper.deleteFsInquiryOrderMsgByMsgKey(messageInfo.getMsgKey());
        }
        String send =messageInfo.getFrom_Account();
        String to =messageInfo.getTo_Account();
        Long time =messageInfo.getMsgTime();
        Date date = new Date(time * 1000);
        List<ImMsgParam.MsgBody> msgBody = messageInfo.getMsgBody();

        for (ImMsgParam.MsgBody body : msgBody) {

            String[] sendSplit = send.split("-");
            String[] toSplit = to.split("-");
            String userId="";
            String doctorId="";
            String msgType="2";
            if (sendSplit[0].equals("U")){
                msgType="1";
                userId=sendSplit[1];
                doctorId=toSplit[1];
                fsFollowReportService.addReport(userId,doctorId);
            }else {
                userId=toSplit[1];
                doctorId=sendSplit[1];

                TemplateBean templateBean = TemplateBean.builder()
                        .title("您收到咨询回复")
                        .remark("您的咨询已回复")
                        .uid(Long.parseLong(userId))
                        .templateType(TemplateListenEnum.TYPE_5.getValue())
                        .build();
                publisher.publishEvent(new TemplateEvent(this, templateBean));
                if (body.getMsgType().equals("TIMTextElem")){
                    String text = body.getMsgContent().getText();
                   if (text.contains("您的信息我已收到")){
                       long doctorIdL = Long.parseLong(doctorId);
                       long userIdL = Long.parseLong(userId);
                       int count = fsFollowReportMapper.selectFollowByUserIdAndDoctorIdAndType(userIdL, doctorIdL);
                       if (count==0){
                           FsUser fsUser = fsUserMapper.selectFsUserByUserId(userIdL);
                           if (fsUser!=null&&fsUser.getPhone()!=null){
                               FsInquiryOrder order = fsFollowReportMapper.selectFsInquiryOrderByUserAndDoc(userIdL, doctorIdL);
                               if (order!=null){
                                   FsInquiryOrderPatientDTO patientDTO = JSON.parseObject(order.getPatientJson(),FsInquiryOrderPatientDTO.class);
                                   if (patientDTO!=null&&patientDTO.getPatientName()!=null){
                                       FsDoctor doctor=doctorMapper.selectFsDoctorByDoctorId(doctorIdL);
                                       if (doctor.getDeptId()!=null&&doctor.getDeptId().compareTo(39L)==0){
                                           logger.info("药师回复发送短信:"+fsUser.getPhone()+patientDTO.getPatientName());
                                           smsService.sendUserSms(fsUser.getPhone(), patientDTO.getPatientName(), "7");
                                       }else {
                                           logger.info("医生回复发送短信:"+patientDTO.getMobile()+patientDTO.getPatientName());
                                           smsService.sendUserSms(fsUser.getPhone(), patientDTO.getPatientName(), "4");
                                       }
                                   }
                               }else {
                                   FsFollow fo = fsFollowReportMapper.selectFsFollowById(userIdL, doctorIdL);
                                   if (fo!=null&&fo.getPatientName()!=null){
                                       logger.info("药师回复发送短信:"+fsUser.getPhone()+fo.getPatientName());
                                       smsService.sendUserSms(fsUser.getPhone(), fo.getPatientName(), "7");
                                   }
                               }

                           }

                       }
                   }


                }

            }
            Long orderId = fsInquiryOrderMsgMapper.selectFsInquiryOrderMsgOrderId(doctorId, userId);
            if (orderId==null){
                orderId = fsInquiryOrderMsgMapper.selectFsInquiryOrderMsgOrderIdByDate(doctorId, userId,date);
            }

            String msgContentType = body.getMsgType();
            Integer type=0;
            String cont="";
            if (msgContentType != null ) {
                switch (msgContentType) {
                    case "TIMTextElem":
                        type=1;
                        cont=body.getMsgContent().getText();
                        break;
                    case "TIMSoundElem":
                        String soundUrl = body.getMsgContent().getUrl();
                        try {
                            // 创建URL对象
                            URL url = new URL(soundUrl);
                            InputStream in =  url.openStream();
                            CloudStorageService storage = OSSFactory.build();
                            cont = storage.uploadSuffix(in, ".m4a");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        type=2;
                        break;
                    case "TIMImageElem":
                        String imgUrl = body.getMsgContent().getImageInfoArray().get(0).getURL();
                        try {
                            URL url = new URL(imgUrl);
                            InputStream in =  url.openStream();
                            CloudStorageService storage = OSSFactory.build();
                            cont = storage.uploadSuffix(in, ".jpg");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        type=3;
                        break;
                    case "TIMVideoFileElem":
                        String videoUrl = body.getMsgContent().getVideoUrl();
                        try {
                            URL url = new URL(videoUrl);
                            InputStream in =  url.openStream();
                            CloudStorageService storage = OSSFactory.build();
                            cont = storage.uploadSuffix(in, "."+body.getMsgContent().getVideoFormat());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        type=4;
                        break;
                    case "TIMCustomElem":
                        if (body.getMsgContent().getData().equals("prescribe")){
                            cont=body.getMsgContent().getExt();
                            type=5;
                            break;
                        }else if (body.getMsgContent().getData().equals("report")){
                            cont=body.getMsgContent().getDesc();
                            type=6;
                            break;
                        }else if (body.getMsgContent().getData().equals("follow")){
                             cont=body.getMsgContent().getDesc();
                            type= 7;
                            break;
                        }else if (body.getMsgContent().getData().equals("drugReport")){
                            cont=body.getMsgContent().getDesc();
                            type= 8;
                            break;
                        }else {
                            String ext = body.getMsgContent().getExt();
                            Map<String,String> parse = (Map)JSON.parse(ext);
                            cont= parse.get("title");
                            type=1;
                            break;
                        }

                }
            }

            FsInquiryOrderMsg msg = new FsInquiryOrderMsg();
            msg.setOrderId(orderId);
            msg.setMsgContentType(type);
            msg.setFromAccount(userId);
            msg.setToAccount(doctorId);
            msg.setMsgKey(messageInfo.getMsgKey());
            msg.setContent(cont);
            msg.setCreateTime(date);
            msg.setMsgType(msgType);
            fsInquiryOrderMsgMapper.insertFsInquiryOrderMsg(msg);

        }

    }

    @Override
    public List<FsInquiryOrderMsgListDVO> selectFsInquiryOrderMsgListDVO(FsInquiryOrderMsgListDParam param) {
        return fsInquiryOrderMsgMapper.selectFsInquiryOrderMsgListDVO(param);
    }
    @Override
    public OpenImMsgCallBackResponse openImSaveMsg(OpenImMsgCallBackVO openImMsgCallBackVO) throws JsonProcessingException {
        OpenImMsgCallBackResponse openImMsgCallBackResponse = new OpenImMsgCallBackResponse();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (openImMsgCallBackVO.getCallbackCommand().equals("callbackBeforeAfterMsgCommand")){
                fsInquiryOrderMsgMapper.deleteFsInquiryOrderMsgByMsgKey(openImMsgCallBackVO.getClientMsgID());
                return openImMsgCallBackResponse;
            }
            String send =openImMsgCallBackVO.getSendID();
            String to =openImMsgCallBackVO.getRecvID();
            Long time =openImMsgCallBackVO.getSendTime();
            Date date = new Date(time);
            String content = openImMsgCallBackVO.getContent();


            String userId="";
            String doctorId="";
            String companyUserId="";
            String msgType="2";
            //用户发送消息
            if (send.contains("U")){
                msgType="1";
                userId=send.replace("U","");
                if (to.contains("D")){
                    doctorId=to.replace("D","");
                    fsFollowReportService.addReport(userId,doctorId);
                }else if (to.contains("C")){
                    companyUserId=to.replace("C","");
                }
                //医生发送消息
            }else if (send.contains("D")){
                doctorId=send.replace("D","");
                if (to.contains("U")){
                    userId=to.replace("U","");
                    TemplateBean templateBean = TemplateBean.builder()
                            .title("您收到咨询回复")
                            .remark("您的咨询已回复")
                            .uid(Long.parseLong(userId))
                            .templateType(TemplateListenEnum.TYPE_5.getValue())
                            .build();
                    publisher.publishEvent(new TemplateEvent(this, templateBean));
                    if (openImMsgCallBackVO.getContentType()==101){
                        if (content.contains("您的信息我已收到")){
                            long doctorIdL = Long.parseLong(doctorId);
                            long userIdL = Long.parseLong(userId);
                            int count = fsFollowReportMapper.selectFollowByUserIdAndDoctorIdAndType(userIdL, doctorIdL);
                            if (count==0){
                                FsUser fsUser = fsUserMapper.selectFsUserByUserId(userIdL);
                                if (fsUser!=null&&fsUser.getPhone()!=null){
                                    FsInquiryOrder order = fsFollowReportMapper.selectFsInquiryOrderByUserAndDoc(userIdL, doctorIdL);
                                    if (order!=null){
                                        FsInquiryOrderPatientDTO patientDTO = JSON.parseObject(order.getPatientJson(),FsInquiryOrderPatientDTO.class);
                                        if (patientDTO!=null&&patientDTO.getPatientName()!=null){
                                            FsDoctor doctor=doctorMapper.selectFsDoctorByDoctorId(doctorIdL);
                                            if (doctor.getDeptId()!=null&&doctor.getDeptId().compareTo(39L)==0){
                                                logger.info("药师回复发送短信:"+fsUser.getPhone()+patientDTO.getPatientName());
                                                smsService.sendUserSms(fsUser.getPhone(), patientDTO.getPatientName(), "7");
                                            }else {
                                                logger.info("医生回复发送短信:"+patientDTO.getMobile()+patientDTO.getPatientName());
                                                smsService.sendUserSms(fsUser.getPhone(), patientDTO.getPatientName(), "4");
                                            }
                                        }
                                    }else {
                                        FsFollow fo = fsFollowReportMapper.selectFsFollowById(userIdL, doctorIdL);
                                        if (fo!=null&&fo.getPatientName()!=null){
                                            logger.info("药师回复发送短信:"+fsUser.getPhone()+fo.getPatientName());
                                            smsService.sendUserSms(fsUser.getPhone(), fo.getPatientName(), "7");
                                        }
                                    }

                                }

                            }
                        }
                    }
                }else {
                    companyUserId = to.replace("C","");
                }
                //销售发送消息
            }else if (send.contains("C")){
                companyUserId=send.replace("C","");
                if (to.contains("U")){
                    userId=to.replace("U","");
                }else {
                    doctorId = to.replace("D","");
                }
            }
            Long orderId = fsInquiryOrderMsgMapper.selectFsInquiryOrderMsgOrderId(doctorId, userId);
            if (orderId==null){
                orderId = fsInquiryOrderMsgMapper.selectFsInquiryOrderMsgOrderIdByDate(doctorId, userId,date);
            }

            Integer msgContentType = openImMsgCallBackVO.getContentType();
            Integer type=0;
            String cont="";
            JsonNode jsonNode = null;
            if (msgContentType != null ) {
                switch (msgContentType) {
                    //普通消息
                    case 101:
                        type=1;
                        jsonNode = objectMapper.readTree(content);
                        cont=jsonNode.get("content").asText();
                        break;
                    //语音消息
                    case 103:
                        jsonNode = objectMapper.readTree(content); // 转为 JsonNode
                        String soundUrl = jsonNode.get("sourceUrl").asText();
                        try {
                            // 创建URL对象
                            URL url = new URL(soundUrl);
                            InputStream in =  url.openStream();
                            CloudStorageService storage = OSSFactory.build();
                            cont = storage.uploadSuffix(in, ".m4a");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        type=2;
                        //医生发送的语音消息，这一段是同步语音消息到腕表的
                        /*if (send.contains("D")){
                            WatchDeviceInfo u = watchDeviceInfoMapper.selectByUserId(to.replace("U", ""));
                            if (u!=null&& StringUtils.isNotEmpty(u.getDeviceNumber())){
                                DeviceSendParam deviceSendParam = new DeviceSendParam();
                                deviceSendParam.setDeviceId(u.getDeviceNumber());
                                deviceSendParam.setFileUrl(soundUrl);
                                deviceSendParam.setSendUserName(openImMsgCallBackVO.getSenderNickname());
                                deviceSetUpService.sendMp3(deviceSendParam);
                            }
                        }*/
                        break;
                    //图片消息
                    case 102:
                        jsonNode = objectMapper.readTree(content); // 转为 JsonNode
                        String imgUrl = jsonNode.get("sourcePicture").get("url").asText();
                        try {
                            URL url = new URL(imgUrl);
                            InputStream in =  url.openStream();
                            CloudStorageService storage = OSSFactory.build();
                            cont = storage.uploadSuffix(in, ".jpg");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        type=3;
                        break;
                    //视频消息
                    case 104:
                        jsonNode = objectMapper.readTree(content); // 转为 JsonNode
                        String videoUrl = jsonNode.get("videoUrl").asText();
                        try {
                            URL url = new URL(videoUrl);
                            InputStream in =  url.openStream();
                            CloudStorageService storage = OSSFactory.build();
                            cont = storage.uploadSuffix(in, "."+jsonNode.get("videoType").asText());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        type=4;
                        break;
                    //自定义消息
                    case 110:
                        PayloadDTO payloadDTO = objectMapper.readValue(content, PayloadDTO.class);

                        jsonNode = objectMapper.readTree(payloadDTO.getData());
                        JsonNode payload = jsonNode.get("payload");
                        String data = payload.get("data").asText();
                        JsonNode extension = payload.get("extension");
                        if (data.equals("prescribe")){
                            String prescribeId = extension.get("prescribeId").asText();
                            FsPrescribe fsPrescribe = fsPrescribeMapper.selectFsPrescribeByPrescribeId(Long.parseLong(prescribeId));
                            cont=objectMapper.writeValueAsString(fsPrescribe);
                            //orderId = fsPrescribe.getInquiryOrderId();
                            type=5;
                            break;
                        }else if (data.equals("report")){

                            String description = payload.get("description").asText();
                            FsInquiryOrderReport fsInquiryOrderReport = fsInquiryOrderReportService.selectFsInquiryOrderReportByOrderId(Long.parseLong(description));
                            if (fsInquiryOrderReport!=null){
                                cont = fsInquiryOrderReport.getOrderId().toString();
                            }
                            type=6;
                            break;
                        }else if (data.equals("follow")){
                            cont=payload.get("extension").get("followId").asText();
                            type= 7;
                            //orderId = payload.get("extension").get("followId").asLong();
                            break;
                        }else if (data.equals("drugReport")){
                            cont=payload.get("description").asText();
                            //orderId = payload.get("description").asLong();
                            type= 8;
                            break;
                        } else if (data.equals("package")){
                            cont=payload.get("extension").get("title").asText();
                            //orderId = payload.get("description").asLong();
                            type= 9;
                            break;
                        }else if (data.equals("couponPackage")){
                            cont=payload.get("extension").get("title").asText();
                            //orderId = payload.get("description").asLong();
                            type= 10;
                            break;
                        }else if (data.equals("inquirySelect")){
                            cont=payload.get("extension").get("title").asText();
                            //orderId = payload.get("description").asLong();
                            type= 11;
                            break;
                        }else if (data.equals("startInquiry")||data.equals("finishInquiry")){
                            cont =payload.get("extension").get("title").asText();
                            type=1;
                            break;
                        }


                }
            }
            if (StringUtils.isEmpty(cont)){
                openImMsgCallBackResponse.setErrMsg("无消息内容，未保存到数据库");
                return openImMsgCallBackResponse;
            }
            if (orderId==null&&StringUtils.isNotEmpty(openImMsgCallBackVO.getEx())){
                JsonNode exJson = objectMapper.readTree(openImMsgCallBackVO.getEx());
                orderId = exJson.get("orderId").asLong();
            }
            FsInquiryOrderMsg msg = new FsInquiryOrderMsg();
            msg.setOrderId(orderId);
            msg.setMsgContentType(type);
            msg.setFromAccount(userId);
            msg.setCompanyUserAccount(companyUserId);
            msg.setToAccount(doctorId);
            msg.setMsgKey(openImMsgCallBackVO.getClientMsgID());
            msg.setContent(cont);
            msg.setCreateTime(date);
            msg.setMsgType(msgType);
            fsInquiryOrderMsgMapper.insertFsInquiryOrderMsg(msg);
            // 极光推送
            //String pushContent = (type == 1) ? content :"您有一条新消息";
            //uniPush2Service.pushOne(Long.parseLong(to.replace("U","")), orderId, null, "新消息提醒", pushContent, PushLogTypeEnum.MARKET.getValue(), PushLogDesTypeEnum.MARKET_PUSH.getValue());
            log.info("返回的参数 {}", JSON.toJSONString(openImMsgCallBackResponse));
            return openImMsgCallBackResponse;
        } catch (Exception e){
            openImMsgCallBackResponse.setActionCode(202);
            openImMsgCallBackResponse.setErrCode(100);
            openImMsgCallBackResponse.setErrDlt("");
            openImMsgCallBackResponse.setErrMsg(e.getMessage());
            log.info("返回的参数 {}", JSON.toJSONString(openImMsgCallBackResponse));
            return openImMsgCallBackResponse;
        }

    }

}
