package com.xinelu.manage.service.consultationInfo.impl;

import com.alibaba.fastjson2.JSONObject;
import com.xinelu.common.config.XinELuConfig;
import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.exception.file.InvalidExtensionException;
import com.xinelu.common.utils.DateUtils;
import com.xinelu.common.utils.bean.BeanUtils;
import com.xinelu.common.utils.file.FileUploadUtils;
import com.xinelu.common.utils.file.MimeTypeUtils;
import com.xinelu.manage.domain.consultationInfo.ConsultationInfo;
import com.xinelu.manage.domain.goodsOrder.GoodsOrder;
import com.xinelu.manage.domain.scheduleplandetail.SchedulePlanDetail;
import com.xinelu.manage.dto.consultationInfo.ConsultationInfoDTO;
import com.xinelu.manage.mapper.consultationInfo.ConsultationInfoMapper;
import com.xinelu.manage.mapper.goodsOrder.GoodsOrderMapper;
import com.xinelu.manage.mapper.patientinfo.PatientInfoMapper;
import com.xinelu.manage.mapper.scheduleplandetail.SchedulePlanDetailMapper;
import com.xinelu.manage.service.consultationInfo.IConsultationInfoService;
import com.xinelu.manage.service.messagepush.MessagePushService;
import com.xinelu.manage.vo.consultationInfo.ConsultationInfoVO;
import com.xinelu.manage.vo.patientinfo.PatientInfoVO;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


/**
 * 在线问诊-问诊信息（图文和视频问诊基本信息）Service业务层处理
 *
 * @author xinelu
 * @date 2023-09-25
 */
@Service
public class ConsultationInfoServiceImpl implements IConsultationInfoService {
    @Resource
    private ConsultationInfoMapper consultationInfoMapper;

    @Resource
    private XinELuConfig xinYiLuConfig;

	@Resource
	private GoodsOrderMapper goodsOrderMapper;

	@Resource
	private MessagePushService messagePushService;

	@Resource
	private PatientInfoMapper patientInfoMapper;

	@Resource
	private SchedulePlanDetailMapper schedulePlanDetailMapper;

    /**
     * 查询在线问诊-问诊信息（图文和视频问诊基本信息）
     *
     * @param id 在线问诊-问诊信息（图文和视频问诊基本信息）主键
     * @return 在线问诊-问诊信息（图文和视频问诊基本信息）
     */
    @Override
    public ConsultationInfoDTO selectConsultationInfoById(Long id) {
        ConsultationInfoDTO consultationInfoDTO = consultationInfoMapper.selectConsultationInfoById(id);
        if (consultationInfoDTO != null) {
            consultationInfoDTO.setFileUrls(consultationInfoMapper.getConsultationFiles(id));
        }
        return consultationInfoDTO;
    }

    /**
     * 查询在线问诊-问诊信息（图文和视频问诊基本信息）列表
     *
     * @param consultationInfoDTO 在线问诊-问诊信息（图文和视频问诊基本信息）
     * @return 在线问诊-问诊信息（图文和视频问诊基本信息）
     */
    @Override
    public List<ConsultationInfoVO> selectConsultationInfoList(ConsultationInfoDTO consultationInfoDTO) {
        return consultationInfoMapper.selectConsultationInfoList(consultationInfoDTO);
    }

    /**
     * 新增在线问诊-问诊信息（图文和视频问诊基本信息）
     *
     * @param consultationInfoDTO 在线问诊-问诊信息（图文和视频问诊基本信息）
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertConsultationInfo(ConsultationInfoDTO consultationInfoDTO) {
		if (StringUtils.equals("VIDEO_CONSULTATION", consultationInfoDTO.getConsultationType()) && consultationInfoDTO.getSchedulePlanDetailId() == null) {
			return AjaxResult.error("请选择预约时间段");
		}
        consultationInfoDTO.setCreateTime(DateUtils.getNowDate());
        ConsultationInfo consultationInfo = new ConsultationInfo();
        BeanUtils.copyBeanProp(consultationInfo, consultationInfoDTO);
        int count = consultationInfoMapper.insertConsultationInfo(consultationInfo);
        if (count > 0) {
            if (CollectionUtils.isNotEmpty(consultationInfoDTO.getFileUrls())) {
                consultationInfoMapper.insertConsultationFile(consultationInfo.getId(), consultationInfoDTO.getFileUrls());
            }
			// 专家咨询，修改预约时间段的预约状态
	        if (StringUtils.equals("VIDEO_CONSULTATION", consultationInfoDTO.getConsultationType())) {
		        SchedulePlanDetail schedulePlanDetail = new SchedulePlanDetail();
				schedulePlanDetail.setId(consultationInfoDTO.getSchedulePlanDetailId());
				schedulePlanDetail.setApplyState("1");
		        schedulePlanDetailMapper.updateByPrimaryKeySelective(schedulePlanDetail);
	        }
            return AjaxResult.success(consultationInfo);
        }
        return AjaxResult.error();
    }

    /**
     * 修改在线问诊-问诊信息（图文和视频问诊基本信息）
     *
     * @param consultationInfo 在线问诊-问诊信息（图文和视频问诊基本信息）
     * @return 结果
     */
    @Override
    public int updateConsultationInfo(ConsultationInfo consultationInfo) {
        consultationInfo.setUpdateTime(DateUtils.getNowDate());
        return consultationInfoMapper.updateConsultationInfo(consultationInfo);
    }

    /**
     * 批量删除在线问诊-问诊信息（图文和视频问诊基本信息）
     *
     * @param ids 需要删除的在线问诊-问诊信息（图文和视频问诊基本信息）主键
     * @return 结果
     */
    @Override
    public int deleteConsultationInfoByIds(Long[] ids) {
        return consultationInfoMapper.deleteConsultationInfoByIds(ids);
    }

    /**
     * 删除在线问诊-问诊信息（图文和视频问诊基本信息）信息
     *
     * @param id 在线问诊-问诊信息（图文和视频问诊基本信息）主键
     * @return 结果
     */
    @Override
    public int deleteConsultationInfoById(Long id) {
        return consultationInfoMapper.deleteConsultationInfoById(id);
    }


    /**
     * 图文和视频问诊基本信息-文件上传
     *
     * @param multipartFile 文件
     * @return 结果
     */
    @Override
    public AjaxResult uploadConsultationFile(MultipartFile multipartFile) throws IOException, InvalidExtensionException {
        //获取不同的文件路径
        String uploadPathUrl = XinELuConfig.getProfile() + xinYiLuConfig.getConsultationFileUrl();
        if (StringUtils.isBlank(uploadPathUrl)) {
            return AjaxResult.success();
        }
        //上传
        String pictureName = FileUploadUtils.uploadNurseStationPath(uploadPathUrl, multipartFile, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        if (StringUtils.isBlank(pictureName)) {
            throw new ServiceException("文件上传失败，请联系管理员！");
        }
        AjaxResult ajax = AjaxResult.success("上传成功！");
        ajax.put("fileUrl", pictureName);
        return ajax;
    }

	@Override public AjaxResult startConsultation(Long goodsOrderId) {
		GoodsOrder goodOrder = goodsOrderMapper.selectGoodsOrderById(goodsOrderId);
		if (goodOrder == null) {
			return AjaxResult.error("未查找到该订单，请联系管理员");
		}
		// 根据图文咨询申请主键查询居民主键
		ConsultationInfoDTO consultationInfo = consultationInfoMapper.selectConsultationInfoById(goodOrder.getConsultationInfoId());
		if (consultationInfo == null) {
			return AjaxResult.error("生成房间号失败");
		}
		String roomId = "";
		if(com.xinelu.common.utils.StringUtils.isNotBlank(goodOrder.getRoomId())) {
			roomId = goodOrder.getRoomId();
		} else {
			// 房间号
			Random random = new Random();
			int randomNumber = random.nextInt(900000) + 100000; // 限制范围为 100000-999999
			roomId = String.valueOf(randomNumber);
			if (roomId.length() < 6) {
				roomId = "0" + roomId; // 补零
			}
			// 保存房间号
			goodOrder.setRoomId(roomId);
			goodsOrderMapper.updateGoodsOrder(goodOrder);
		}
		PatientInfoVO patient = patientInfoMapper.selectPatientInfoById(goodOrder.getPatientId());
		if (patient == null) {
			return AjaxResult.error("未查询到该居民");
		}

		// 给居民推送消息通知
		JSONObject result = new JSONObject()
			.fluentPut("patientId", patient.getId())
			.fluentPut("openid", patient.getOpenid())
			.fluentPut("receiveName", patient.getPatientName())
			.fluentPut("sendTitle", "专家视频问诊")
			.fluentPut("sendTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date()))
			.fluentPut("busType", "")
			.fluentPut("sendContent", "专家邀请您进行视频问诊，请及时接听")
			.fluentPut("messageType", "1")
			.fluentPut("messageCategory", "4")
			.fluentPut("cardNo", patient.getCardNo())
			.fluentPut("senderName", consultationInfo.getDoctorName())
			.fluentPut("contentId", goodOrder.getId())
			.fluentPut("sourceType", "2");
		messagePushService.fdApprovePush(result);
		return AjaxResult.success(roomId);
	}

	@Override
	public AjaxResult getAppletRoomId(Long goodsOrderId) {
		GoodsOrder order = goodsOrderMapper.selectGoodsOrderById(goodsOrderId);
		if (order == null) {
			return AjaxResult.error("未查询到订单信息");
		}
		return AjaxResult.success(order.getRoomId());
	}
}
