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


import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.bean.BeanUtils;
import com.xinelu.common.utils.regex.RegexUtil;
import com.xinelu.manage.domain.appointmentorder.AppointmentOrder;
import com.xinelu.manage.domain.appointmentorderconsumable.AppointmentOrderConsumable;
import com.xinelu.manage.domain.appointmentorderdetails.AppointmentOrderDetails;
import com.xinelu.manage.domain.patientdiseaseinfo.PatientDiseaseInfo;
import com.xinelu.manage.dto.appointmentorderdetails.AppointmentOrderDetailsDTO;
import com.xinelu.manage.mapper.appointmentorder.AppointmentOrderMapper;
import com.xinelu.manage.mapper.appointmentorderconsumable.AppointmentOrderConsumableMapper;
import com.xinelu.manage.mapper.appointmentorderdetails.AppointmentOrderDetailsMapper;
import com.xinelu.manage.mapper.patientdiseaseinfo.PatientDiseaseInfoMapper;
import com.xinelu.manage.service.appointmentorderdetails.IAppointmentOrderDetailsService;
import com.xinelu.manage.vo.appointmentorderdetails.AppointmentOrderDetailsVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 预约订单明细Service业务层处理
 *
 * @author 纪寒
 * @date 2022-09-05
 */
@Service
public class AppointmentOrderDetailsServiceImpl implements IAppointmentOrderDetailsService {
    @Resource
    private AppointmentOrderDetailsMapper appointmentOrderDetailsMapper;
    @Resource
    private AppointmentOrderConsumableMapper appointmentOrderConsumableMapper;
    @Resource
    private PatientDiseaseInfoMapper patientDiseaseInfoMapper;
    @Resource
    private AppointmentOrderMapper appointmentOrderMapper;
    @Resource
    private RegexUtil regexUtil;

    /**
     * 查询预约订单明细
     *
     * @param id 预约订单明细主键
     * @return 预约订单明细
     */
    @Override
    public AppointmentOrderDetails selectAppointmentOrderDetailsById(Long id) {
        return appointmentOrderDetailsMapper.selectAppointmentOrderDetailsById(id);
    }

    /**
     * 查询预约订单明细列表
     *
     * @param appointmentOrderDetails 预约订单明细
     * @return 预约订单明细
     */
    @Override
    public List<AppointmentOrderDetails> selectAppointmentOrderDetailsList(AppointmentOrderDetails appointmentOrderDetails) {
        return appointmentOrderDetailsMapper.selectAppointmentOrderDetailsList(appointmentOrderDetails);
    }

    /**
     * 新增预约订单明细
     *
     * @param appointmentOrderDetails 预约订单明细
     * @return 结果
     */
    @Override
    public int insertAppointmentOrderDetails(AppointmentOrderDetails appointmentOrderDetails) {
        appointmentOrderDetails.setCreateTime(LocalDateTime.now());
        return appointmentOrderDetailsMapper.insertAppointmentOrderDetails(appointmentOrderDetails);
    }

    /**
     * 修改预约订单明细
     *
     * @param appointmentOrderDetails 预约订单明细
     * @return 结果
     */
    @Override
    public int updateAppointmentOrderDetails(AppointmentOrderDetails appointmentOrderDetails) {
        appointmentOrderDetails.setUpdateTime(LocalDateTime.now());
        return appointmentOrderDetailsMapper.updateAppointmentOrderDetails(appointmentOrderDetails);
    }

    /**
     * 逻辑批量删除预约订单明细
     *
     * @param ids 需要删除的预约订单明细主键
     * @return 结果
     */
    @Override
    public AjaxResult updateAppointmentOrderDetailsByIds(Long[] ids) {
        int appointmentOrderDetailsByIds = appointmentOrderDetailsMapper.updateAppointmentOrderDetailsByIds(ids);
        if (appointmentOrderDetailsByIds <= 0) {
            throw new ServiceException("删测试项目信息失败");
        }
        return AjaxResult.success();
    }

    /**
     * 删除预约订单明细信息
     *
     * @param id 预约订单明细主键
     * @return 结果
     */
    @Override
    public int deleteAppointmentOrderDetailsById(Long id) {
        return appointmentOrderDetailsMapper.deleteAppointmentOrderDetailsById(id);
    }

    /**
     * 预约订单管理列表页面查看明细
     *
     * @param orderNo 订单编号
     * @return com.xinyilu.base.vo.appointmentorderdetails.AppointmentOrderDetailsVO
     **/
    @Override
    public AppointmentOrderDetailsVO getAppointmentOrderDetailsByDetailed(String orderNo) {
        //根据订单编号查询预约订单管理列表页面查看明细
        AppointmentOrderDetailsVO appointmentOrderDetails = appointmentOrderDetailsMapper.getAppointmentOrderDetailsByDetailed(orderNo);
        if (Objects.isNull(appointmentOrderDetails)) {
            return null;
        }
        //健康状况
        List<PatientDiseaseInfo> patientDiseaseInfo = patientDiseaseInfoMapper.selectPatientDiseaseInfoByOrderNo(orderNo);
        if (CollectionUtils.isNotEmpty(patientDiseaseInfo)) {
            List<String> diseaseNameList = patientDiseaseInfo.stream().filter(Objects::nonNull).map(PatientDiseaseInfo::getDiseaseName).filter(StringUtils::isNotBlank).collect(Collectors.toList());
            String diseaseName = String.join(",", diseaseNameList);
            appointmentOrderDetails.setDiseaseName(diseaseName);
        }
        //获取订单明细表id查询耗材包详情信息集合
        if (Objects.isNull(appointmentOrderDetails.getAppointOrderDetailsId())) {
            return appointmentOrderDetails;
        }
        List<AppointmentOrderConsumable> appointmentOrderConsumableList = appointmentOrderConsumableMapper.getByAppointOrderDetailsId(appointmentOrderDetails.getAppointOrderDetailsId());
        if (CollectionUtils.isEmpty(appointmentOrderConsumableList)) {
            return appointmentOrderDetails;
        }
        appointmentOrderDetails.setAppointmentOrderConsumableList(appointmentOrderConsumableList);
        return appointmentOrderDetails;
    }

    /**
     * 根据订单编号查询预约订单信息
     *
     * @param orderNo 订单编号
     * @return 信息
     */
    @Override
    public AjaxResult getCancelAppointmentOrderInfo(String orderNo) {
        return AjaxResult.success(appointmentOrderDetailsMapper.getCancelAppointmentOrderInfo(orderNo));
    }

    /**
     * 修改陪诊陪护预约订单信息
     *
     * @param appointmentOrderDetailsDTO 预约订单信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateAppointmentOrderInfo(AppointmentOrderDetailsDTO appointmentOrderDetailsDTO) {
        //判断时间数量是否符合
        if (Objects.nonNull(appointmentOrderDetailsDTO.getCompanionStartDate()) && Objects.nonNull(appointmentOrderDetailsDTO.getCompanionEndDate())) {
            if (appointmentOrderDetailsDTO.getCompanionStartDate().isBefore(LocalDate.now())) {
                return AjaxResult.error("时间错误，时间只能选择今天以及以后的时间！");
            }
            long companionDays = ChronoUnit.DAYS.between(appointmentOrderDetailsDTO.getCompanionStartDate(), appointmentOrderDetailsDTO.getCompanionEndDate()) + 1;
            if (Objects.nonNull(appointmentOrderDetailsDTO.getCompanionDays()) && appointmentOrderDetailsDTO.getCompanionDays() != companionDays) {
                return AjaxResult.error("数量与时间不符合，请重新调整时间！");
            }
        }
        //预约天数
        int companionDays = Objects.isNull(appointmentOrderDetailsDTO.getCompanionDays()) ? 0 : appointmentOrderDetailsDTO.getCompanionDays();
        //护理项目价格
        BigDecimal nurseItemPrice = Objects.isNull(appointmentOrderDetailsDTO.getNurseItemPrice()) ? BigDecimal.ZERO : appointmentOrderDetailsDTO.getNurseItemPrice();
        if (Objects.nonNull(appointmentOrderDetailsDTO.getTotalPrice()) && appointmentOrderDetailsDTO.getTotalPrice().compareTo(BigDecimal.valueOf(companionDays).multiply(nurseItemPrice)) != 0) {
            return AjaxResult.error("总价格与实际应付价格不符！");
        }
        //判断手机号
        if (StringUtils.isNotBlank(appointmentOrderDetailsDTO.getCaregiverPhone())) {
            boolean regexPhone = regexUtil.regexPhone(appointmentOrderDetailsDTO.getCaregiverPhone());
            if (BooleanUtils.isFalse(regexPhone)) {
                return AjaxResult.error("您输入的联系电话" + appointmentOrderDetailsDTO.getCaregiverPhone() + "不正确，请重新输入！");
            }
        }
        AppointmentOrder appointmentOrder = new AppointmentOrder();
        BeanUtils.copyProperties(appointmentOrderDetailsDTO, appointmentOrder);
        appointmentOrder.setId(appointmentOrderDetailsDTO.getAppointOrderId());
        appointmentOrder.setUpdateTime(LocalDateTime.now());
        int updateAppointmentOrder = appointmentOrderMapper.updateAppointmentOrder(appointmentOrder);
        if (updateAppointmentOrder <= 0) {
            throw new ServiceException("修改订单主表信息失败，请联系管理员！");
        }
        AppointmentOrderDetails appointmentOrderDetails = new AppointmentOrderDetails();
        BeanUtils.copyProperties(appointmentOrderDetailsDTO, appointmentOrderDetails);
        appointmentOrderDetails.setId(appointmentOrderDetailsDTO.getAppointOrderDetailsId());
        appointmentOrderDetails.setUpdateTime(LocalDateTime.now());
        int updateAppointmentOrderDetails = appointmentOrderDetailsMapper.updateAppointmentOrderDetails(appointmentOrderDetails);
        if (updateAppointmentOrderDetails <= 0) {
            throw new ServiceException("修改订单明细表信息失败，请联系管理员！");
        }
        return AjaxResult.success();
    }
}