package com.xinelu.applet.service.nursingorder.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.xinelu.applet.dto.nurseorder.NurseOrderDTO;
import com.xinelu.applet.mapper.nursingorder.NursingOrderMapper;
import com.xinelu.applet.service.nursingorder.INursingOrderService;
import com.xinelu.applet.vo.nursingorder.*;
import com.xinelu.applet.vo.specialdisease.AppointmentOrderDetailsInfoVO;
import com.xinelu.common.constant.HttpStatus;
import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.core.domain.entity.SysDictData;
import com.xinelu.common.core.page.TableDataInfo;
import com.xinelu.common.enums.ConfirmRefundStatusEnum;
import com.xinelu.common.enums.GooodsOrderStatusEnum;
import com.xinelu.common.enums.OrderSourceEnum;
import com.xinelu.common.enums.OrderStatusEnum;
import com.xinelu.common.enums.OrderTypeEnum;
import com.xinelu.common.utils.DateUtils;
import com.xinelu.common.utils.http.HttpUtils;
import com.xinelu.common.utils.spring.SpringUtils;
import com.xinelu.manage.domain.goodsOrder.GoodsOrder;
import com.xinelu.manage.domain.hospitalinfo.HospitalInfo;
import com.xinelu.manage.domain.hospitalpersoninfo.HospitalPersonInfo;
import com.xinelu.manage.dto.consultationInfo.ConsultationInfoDTO;
import com.xinelu.manage.mapper.goodsOrder.GoodsOrderMapper;
import com.xinelu.manage.service.consultationInfo.IConsultationInfoService;
import com.xinelu.manage.service.hospitalinfo.IHospitalInfoService;
import com.xinelu.manage.service.hospitalpersoninfo.IHospitalPersonInfoService;
import com.xinelu.manage.service.patientinfo.IPatientInfoService;
import com.xinelu.manage.vo.patientinfo.PatientInfoVO;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @Description 订单分页
 * @Author ZhangHeng
 * @Date 2022-09-06
 * @Version
 */
@Service
@Slf4j
public class NursingOrderServiceImpl implements INursingOrderService {

    @Resource
    private NursingOrderMapper nursingOrderMapper;

	@Resource
	private GoodsOrderMapper goodsOrderMapper;
	@Resource
	private IPatientInfoService patientService;
	@Resource
	private IHospitalPersonInfoService hospitalPersonInfoService;
	@Resource
	private IHospitalInfoService hospitalInfoService;
	@Resource
	private IConsultationInfoService consultationInfoService;

    /**
     * 未评价标识
     */
    private final String NOT_EVALUATED = "NOT_EVALUATED";

    /**
     * 已评价标识
     */
    private final String EVALUATED = "EVALUATED";

    /**
     * 查询个人订单列表并分页
     *
     * @param patientId 被护理人id
     * @return 结果
     */
    @Override
    public List<NursingOrderInfoVO> getNursingOrderByPatientId(Long patientId) {
        return nursingOrderMapper.getNursingOrderVOByPatientId(patientId);
    }

    /**
     * 根据护理人id以及订单状态查询订单信息
     *
     * @param goodsOrderVO 订单信息
     * @return java.util.List<com.xinyilu.nurseapplet.domain.vo.nursingorder.GoodsOrderVO>
     **/
    @Override
    public List<AppletGoodsOrderVO> getGoodsOrder(AppletGoodsOrderVO goodsOrderVO) {
        return nursingOrderMapper.getGoodsOrder(goodsOrderVO);
    }

    /**
     * 根据订单编号查询专家咨询订单详情
     *
     * @param orderNo 订单编号
     **/
    @Override
    public ConsultationGoodVO getConsultationOrder(String orderNo) {
        return nursingOrderMapper.getConsultationOrder(orderNo);
    }

    /**
     * 查询退款原因
     *
     * @param sysDictData 退款原因
     * @return com.xinyilu.common.core.domain.entity.SysDictData
     **/
    @Override
    public List<SysDictData> getRefundReason(SysDictData sysDictData) {
        //dict_type 字典类型refund_reason
        sysDictData.setDictType("refund_reason");
        return nursingOrderMapper.getRefundReason(sysDictData);
    }

    /**
     * 修改商品订单(退款售后记录信息)
     *
     * @param goodsOrder 商品订单
     * @return 结果
     */
    @Override
    public int updateGoodsOrder(GoodsOrder goodsOrder) {
        //设置修改人以及修改时间
        goodsOrder.setUpdateTime(LocalDateTime.now());
        //订单状态 退款中 WAIT_REFUND
        goodsOrder.setOrderStatus(GooodsOrderStatusEnum.WAIT_REFUND.getInfo());
        //确认退款状态 未确认 NOT_CONFIRM
        goodsOrder.setConfirmRefundStatus(ConfirmRefundStatusEnum.NOT_CONFIRM.getInfo());
        return nursingOrderMapper.updateGoodsOrder(goodsOrder);
    }

    /**
     * 根据预约订单编号查询对应得订单详情信息
     *
     * @param orderNo 订单编号
     * @return 详情信息
     */
    @Override
    public AjaxResult getAppointmentDetailsInfo(String orderNo) {
        //查询预约服务订单信息
        AppointmentOrderDetailsInfoVO detailsInfoVO = nursingOrderMapper.getAppointmentOrderDetailsInfo(orderNo);
        if (Objects.isNull(detailsInfoVO)) {
            return AjaxResult.success();
        }
        //查询护理站相关信息
        AppointmentOrderDetailsInfoVO nurseStationInfo = nursingOrderMapper.getNurseStationByItemId(Objects.isNull(detailsInfoVO.getNurseStationItemId()) ? 0L : detailsInfoVO.getNurseStationItemId());
        if (Objects.nonNull(nurseStationInfo)) {
            detailsInfoVO.setNurseStationName(StringUtils.isBlank(nurseStationInfo.getNurseStationName()) ? "" : nurseStationInfo.getNurseStationName());
            detailsInfoVO.setStationPhone(StringUtils.isBlank(nurseStationInfo.getStationPhone()) ? "" : nurseStationInfo.getStationPhone());
            detailsInfoVO.setAddress(StringUtils.isBlank(nurseStationInfo.getAddress()) ? "" : nurseStationInfo.getAddress());
            detailsInfoVO.setStationPictureUrl(StringUtils.isBlank(nurseStationInfo.getStationPictureUrl()) ? "" : nurseStationInfo.getStationPictureUrl());
            detailsInfoVO.setItemPictureUrl(StringUtils.isBlank(nurseStationInfo.getItemPictureUrl()) ? "" : nurseStationInfo.getItemPictureUrl());
        }
        return AjaxResult.success(detailsInfoVO);
    }

    /**
     * 根据parentId编号查询对应得订单
     *
     * @param nurseOrder nurseOrder
     * @return AjaxResult
     */
    @Override
    public TableDataInfo getAppletOrderList(NurseOrderDTO nurseOrder) {
        List<PatientOrder> patientOrders = new ArrayList<>();
        List<PatientOrder> appletOrderList = new ArrayList<>();
        List<PatientOrder> goodsOrderAndConsultationOrder = new ArrayList<>();
        if (NOT_EVALUATED.equals(nurseOrder.getOrderStatus())) {
            List<String> strings = new ArrayList<>();
            strings.add(GooodsOrderStatusEnum.RECEIVED_GOODS.getInfo());
            strings.add(GooodsOrderStatusEnum.COMPLETED.getInfo());
            appletOrderList = nursingOrderMapper.getAppointmentOrderListByParentId(nurseOrder.getParentId(), OrderStatusEnum.COMPLETE.getInfo());
            goodsOrderAndConsultationOrder = nursingOrderMapper.getGoodsOrderAndConsultationOrder(nurseOrder.getParentId(), strings);
        }
        if (EVALUATED.equals(nurseOrder.getOrderStatus())) {
            List<String> strings = new ArrayList<>();
            strings.add(GooodsOrderStatusEnum.EVALUATED.getInfo());
            appletOrderList = nursingOrderMapper.getAppointmentOrderListByParentId(nurseOrder.getParentId(), OrderStatusEnum.EVALUATED.getInfo());
            goodsOrderAndConsultationOrder = nursingOrderMapper.getGoodsOrderAndConsultationOrder(nurseOrder.getParentId(), strings);
        }
        if (CollectionUtils.isNotEmpty(appletOrderList)) {
            patientOrders.addAll(appletOrderList);
        }
        if (CollectionUtils.isNotEmpty(goodsOrderAndConsultationOrder)) {
            patientOrders.addAll(goodsOrderAndConsultationOrder);
        }
        PatientOrderVO resultHttp = new PatientOrderVO();
        if (Objects.nonNull(nurseOrder.getRegion())) {
            try {
                String result = HttpUtils.sendGet(SpringUtils.getFdUrl(nurseOrder.getRegion()) + "/performance/recordV2/" + nurseOrder.getCardNo());
                if (StringUtils.isBlank(result)) {
                    log.info("获取家医小程序用户订单信息失败，result = " + result);
                }
                resultHttp = JSON.parseObject(result, PatientOrderVO.class);
            } catch (Exception e) {
                log.error("查询家医履约评价记录异常:  " + e.getMessage());
            }
            if (Objects.nonNull(resultHttp) && CollectionUtils.isNotEmpty(resultHttp.getData()) && Objects.nonNull(resultHttp.getData().get(0).getOrderNo())) {
                List<PatientOrder> data = resultHttp.getData();
                for (PatientOrder patientOrder : data) {
                    patientOrder.setOrderSource(OrderSourceEnum.FAMILY_DOCTOR.getInfo());
                    patientOrder.setOrderType(OrderSourceEnum.FAMILY_DOCTOR.getInfo());
                }
                List<PatientOrder> orderEvaluate = nursingOrderMapper.getOrderEvaluateByPatientId(nurseOrder.getParentId());
                if (CollectionUtils.isNotEmpty(orderEvaluate) && EVALUATED.equals(nurseOrder.getOrderStatus())) {
                    for (PatientOrder patientOrder : orderEvaluate) {
                        PatientOrder dataFirst = data.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getOrderNo()) && patientOrder.getOrderNo().equals(item.getOrderNo())).findFirst().orElse(new PatientOrder());
                        dataFirst.setCompositeScore(patientOrder.getCompositeScore());
                        patientOrders.add(dataFirst);
                    }
                }
                if (CollectionUtils.isNotEmpty(orderEvaluate) && NOT_EVALUATED.equals(nurseOrder.getOrderStatus())) {
                    Collection<PatientOrder> subtract = CollectionUtils.subtract(data, orderEvaluate);
                    patientOrders.addAll(subtract);
                }
                if (CollectionUtils.isEmpty(orderEvaluate) && NOT_EVALUATED.equals(nurseOrder.getOrderStatus())) {
                    patientOrders.addAll(data);
                }
            }
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setTotal(new PageInfo(patientOrders).getTotal());
        if (CollectionUtils.isNotEmpty(patientOrders)) {
            Collections.sort(patientOrders, Comparator.comparing(PatientOrder::getCreateTime, (u1, u2) -> u2.compareTo(u1)));
            patientOrders = patientOrders.stream().skip((nurseOrder.getPageNum() - 1) * nurseOrder.getPageSize()).limit(nurseOrder.getPageSize()).collect(Collectors.toList());
        }
        rspData.setRows(patientOrders);
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        return rspData;
    }

	@Override public JSONObject pushMeg(Long orderId, Long patientId) {
		JSONObject result = new JSONObject();
		if (orderId != null && patientId != null) {
			PatientInfoVO patient = patientService.selectPatientInfoById(patientId);
			GoodsOrder goodsOrder = goodsOrderMapper.selectGoodsOrderById(orderId);
			HospitalPersonInfo hospitalPersonInfo = hospitalPersonInfoService.selectHospitalPersonInfoById(goodsOrder.getHospitalPersonId());
			HospitalInfo hospitalInfo = hospitalInfoService.selectHospitalInfoById(hospitalPersonInfo.getHospitalId());
			if (StringUtils.equals(OrderTypeEnum.HEALTH_CONSULTATION.getInfo(), goodsOrder.getOrderType())) {
				ConsultationInfoDTO consultationInfo = consultationInfoService.selectConsultationInfoById(goodsOrder.getConsultationInfoId());
				result.put("sendTime", DateUtils.parseDateToStr("yyyy-MM-dd", consultationInfo.getAppointmentDate()) +" "+ consultationInfo.getAppointmentStartTime());
			}else {
				result.put("sendTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date()));
			}
			if (patient != null && goodsOrder != null) {
				// 组装发送消息通知参数
				result.put("patientId", patientId);
				result.put("openid", patient.getOpenid());
				result.put("receiveName", patient.getPatientName());
				result.put("text1", hospitalInfo.getHospitalName());
				result.put("text2", "专家咨询");
				result.put("text3", "专家咨询");
				result.put("sendTitle", "专家咨询");

				result.put("busType", "10");
				result.put("sendContent", patient.getPatientName() + "专家咨询预约成功");
				result.put("messageType", "5");
				result.put("messageCategory", "4");
				result.put("cardNo", patient.getCardNo());
				return result;
			}
		}
		return null;
	}
}
