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


import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.enums.AppointmentOrderTypeEnum;
import com.xinelu.common.enums.OrderStatusEnum;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.SecurityUtils;
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.mapper.appointmentorder.AppointmentOrderMapper;
import com.xinelu.manage.mapper.appointmentorderconsumable.AppointmentOrderConsumableMapper;
import com.xinelu.manage.mapper.appointmentorderdetails.AppointmentOrderDetailsMapper;
import com.xinelu.manage.service.appointmentorder.IAppointmentOrderService;
import com.xinelu.manage.vo.appointmentorder.AppointmentOrderVO;
import com.xinelu.manage.vo.appointmentorder.PersonAndDepartmentVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 预约订单信息Service业务层处理
 *
 * @author 纪寒
 * @date 2022-09-05
 */
@Slf4j
@Service
public class AppointmentOrderServiceImpl implements IAppointmentOrderService {
    @Resource
    private AppointmentOrderMapper appointmentOrderMapper;
    @Resource
    private AppointmentOrderDetailsMapper appointmentOrderDetailsMapper;
    @Resource
    private AppointmentOrderConsumableMapper appointmentOrderConsumableMapper;

    /**
     * 查询预约订单信息
     *
     * @param id 预约订单信息主键
     * @return 预约订单信息
     */
    @Override
    public AppointmentOrder selectAppointmentOrderById(Long id) {
        return appointmentOrderMapper.selectAppointmentOrderById(id, null);
    }

    /**
     * 查询预约订单信息列表
     *
     * @param appointmentOrder 预约订单信息
     * @return 预约订单信息
     */
    @Override
    public List<AppointmentOrderVO> selectAppointmentOrderList(AppointmentOrderVO appointmentOrder) {
        return appointmentOrderMapper.selectNameByOrderNoList(appointmentOrder);
    }

    /**
     * 新增预约订单信息
     *
     * @param appointmentOrder 预约订单信息
     * @return 结果
     */
    @Override
    public int insertAppointmentOrder(AppointmentOrder appointmentOrder) {
        appointmentOrder.setCreateTime(LocalDateTime.now());
        return appointmentOrderMapper.insertAppointmentOrder(appointmentOrder);
    }

    /**
     * 修改预约订单信息
     *
     * @param appointmentOrder 预约订单信息
     * @return 结果
     */
    @Override
    public int updateAppointmentOrder(AppointmentOrder appointmentOrder) {
        appointmentOrder.setUpdateTime(LocalDateTime.now());
        return appointmentOrderMapper.updateAppointmentOrder(appointmentOrder);
    }

    /**
     * 逻辑批量删除预约订单信息
     *
     * @param ids 需要删除的预约订单信息主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateAppointmentOrderByIds(Long[] ids) {
        if (Objects.isNull(ids)) {
            throw new ServiceException("删除信息id不能为空");
        }
        // 获取需要删除预约订单信息的所有id
        List<AppointmentOrder> orderByIds = appointmentOrderMapper.getAppointmentOrderByIds(ids);
        for (AppointmentOrder orderById : orderByIds) {
            // 获取每个预约订单编号
            String orderNo = orderById.getOrderNo();
            // 根据预约订单编号查询对应的id
            List<AppointmentOrderDetails> orderNoByIds = appointmentOrderDetailsMapper.getAppointmentOrderDetailsOrderNoByIds(orderNo);
            for (AppointmentOrderDetails appointmentOrder : orderNoByIds) {
                Long appointmentOrderId = appointmentOrder.getId();
                AppointmentOrderConsumable orderDetailsList = appointmentOrderConsumableMapper.getAppointmentOrderDetailsList(appointmentOrderId);
                if (!Objects.isNull(orderDetailsList) && !Objects.isNull(appointmentOrderId)) {
                    int consumableById = appointmentOrderConsumableMapper.updateAppointmentOrderConsumableById(appointmentOrderId);
                    if (consumableById <= 0) {
                        throw new ServiceException("删除预约订单明细耗材信息失败");
                    }
                }
            }
            List<AppointmentOrderDetails> orderNoList = appointmentOrderDetailsMapper.getOrderNoList(orderNo);
            for (AppointmentOrderDetails appointmentOrderDetailsVO : orderNoList) {
                String orderDetailsOrderNo = appointmentOrderDetailsVO.getOrderNo();
                if (!Objects.isNull(orderDetailsOrderNo) && !StringUtils.isBlank(orderNo)) {
                    //根据预约订单编号逻辑批量删除预约订单明细
                    int detailsOrderNoByIds = appointmentOrderDetailsMapper.updateAppointmentOrderDetailsOrderNoByIds(orderDetailsOrderNo);
                    if (detailsOrderNoByIds <= 0) {
                        throw new ServiceException("删除预约订单明细信息失败");
                    }
                }
            }

        }
        // 逻辑删除主表预约订单信息
        int appointmentOrderByIds = appointmentOrderMapper.updateAppointmentOrderByIds(ids);
        if (appointmentOrderByIds <= 0) {
            throw new ServiceException("删除预约订单信息失败");
        }
        return AjaxResult.success();
    }

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

    /**
     * 通过订单id，护理站人员id修改订单信息
     *
     * @param appointmentOrder 订单
     * @return com.xinyilu.common.core.domain.AjaxResult
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateOrderStatusByOrderNo(AppointmentOrder appointmentOrder) {
        //根据订单id查询订单信息
        AppointmentOrder appointmentOrders = appointmentOrderMapper.selectAppointmentOrderById(null, appointmentOrder.getOrderNo());
        if (Objects.isNull(appointmentOrders) || StringUtils.isBlank(appointmentOrders.getOrderStatus())) {
            return AjaxResult.error("当前订单状态不存在，请重新选择！");
        }
        if (!appointmentOrders.getOrderStatus().equals(OrderStatusEnum.WAIT_DISPATCH.getInfo())) {
            return AjaxResult.error("订单状态异常，请选择待派单订单!");
        }
        //填加修改信息
        appointmentOrders.setOrderStatus(OrderStatusEnum.WAIT_RECEIVE.getInfo());
        appointmentOrders.setNurseStationPersonId(appointmentOrder.getNurseStationPersonId());
        appointmentOrders.setUpdateBy(SecurityUtils.getUsername());
        appointmentOrders.setUpdateTime(LocalDateTime.now());
        int updateAppointmentOrderStatus = appointmentOrderMapper.updateAppointmentOrderDispatchStatus(appointmentOrders);
        if (updateAppointmentOrderStatus <= 0) {
            throw new ServiceException("派单失败,请联系管理员！");
        }
        return AjaxResult.success();
    }

    /**
     * 通过订单id查询护理所属护理站人员
     *
     * @param personAndDepartment 订单
     * @return AjaxResult
     */
    @Override
    public List<PersonAndDepartmentVO> getNurseStationPerson(PersonAndDepartmentVO personAndDepartment) {
        if (Objects.isNull(personAndDepartment.getOrderNo())) {
            return new ArrayList<>();
        }
        return appointmentOrderMapper.selectNurseStationPersonNameList(personAndDepartment);
    }

    /**
     * 通过护理员id查询护理所属护理站人员
     *
     * @param nurseStationPersonId 护理员id
     * @return AjaxResult
     */
    @Override
    public AjaxResult getNurseStationPersonInfo(Long nurseStationPersonId) {
        return AjaxResult.success(appointmentOrderMapper.selectNurseStationPersonCertificateList(nurseStationPersonId));
    }

    /**
     * 确认取消订单
     *
     * @param appointmentOrderId 订单id
     * @return AjaxResult
     */
    @Override
    public AjaxResult updateAppointmentOrder(Long appointmentOrderId) {
        AppointmentOrder appointment = appointmentOrderMapper.selectAppointmentOrderById(appointmentOrderId, null);
        if (Objects.isNull(appointment) || StringUtils.isBlank(appointment.getOrderStatus())) {
            return AjaxResult.error("当前订单不存在，请重新选择！");
        }
        if (appointment.getOrderStatus().equals(OrderStatusEnum.CANCEL.getInfo())) {
            return AjaxResult.success("当前订单已确认取消，请重新选择！");
        }
        AppointmentOrder appointmentOrder = new AppointmentOrder();
        appointmentOrder.setUpdateTime(LocalDateTime.now());
        appointmentOrder.setUpdateBy(SecurityUtils.getUsername());
        appointmentOrder.setId(appointmentOrderId);
        appointmentOrder.setOrderNo(StringUtils.isBlank(appointment.getOrderNo()) ? "" : appointment.getOrderNo());
        appointmentOrder.setOrderStatus(OrderStatusEnum.CANCEL.getInfo());
        int update = appointmentOrderMapper.updateAppointmentOrderByOrderId(appointmentOrder);
        if (update <= 0) {
            throw new ServiceException("确认取消订单失败，请联系管理员！");
        }
        return AjaxResult.success();
    }

    /**
     * 院内陪护确认完成
     *
     * @param orderNo     订单编号
     * @param orderStatus 订单状态
     * @return AjaxResult
     */
    @Override
    public AjaxResult updateCompanionOrderStatus(String orderNo, String orderStatus) {
        AppointmentOrder appointmentOrder = appointmentOrderMapper.getAppointmentOrderByOrderNo(orderNo);
        if (Objects.isNull(appointmentOrder) || StringUtils.isBlank(appointmentOrder.getOrderType()) || StringUtils.isBlank(appointmentOrder.getOrderStatus())) {
            return AjaxResult.error("当前订单不存在，请重新选择！");
        }
        if (!AppointmentOrderTypeEnum.COMPANION_IN_HOSPITAL.getInfo().equals(appointmentOrder.getOrderType())) {
            return AjaxResult.error("当前订单不是院内陪护，请重新选择！");
        }
        if (!OrderStatusEnum.WAIT_DISPATCH.getInfo().equals(appointmentOrder.getOrderStatus())) {
            return AjaxResult.error("当前订单状态不能确认完成，请重新选择！");
        }
        return AjaxResult.success(appointmentOrderMapper.updateAppointmentOrderStatus(OrderStatusEnum.COMPLETE.getInfo(), orderNo));
    }
}
