package com.younike.system.service.impl;

import com.younike.common.core.domain.AjaxResult;
import com.younike.common.exception.ServiceException;
import com.younike.common.utils.SecurityUtils;
import com.younike.common.utils.bean.BeanUtils;
import com.younike.common.utils.id.RandomCodeGenerate;
import com.younike.system.domain.Order;
import com.younike.system.domain.OrderRecord;
import com.younike.system.domain.OrderVerificationRecord;
import com.younike.system.domain.vo.OrderVerificationRecordVO;
import com.younike.system.enums.OrderStateEnum;
import com.younike.system.mapper.OrderMapper;
import com.younike.system.mapper.OrderRecordMapper;
import com.younike.system.mapper.OrderVerificationRecordMapper;
import com.younike.system.param.AccessPasscodeParam;
import com.younike.system.param.GroupOrderVerifyParam;
import com.younike.system.service.IAccessPasscodeService;
import com.younike.system.service.IOrderVerificationRecordService;
import com.younike.system.service.ISysCodeService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 团购订单核销记录Service业务层处理
 *
 * @author dail
 * @date 2022-03-14
 */
@Service
@Log4j2
public class OrderVerificationRecordServiceImpl implements IOrderVerificationRecordService {
    @Autowired
    private OrderVerificationRecordMapper orderVerificationRecordMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderRecordMapper orderRecordMapper;

    @Autowired
    private ISysCodeService sysCodeService;

    @Autowired
    private IAccessPasscodeService merchantAccessPasscodeService;


    /**
     * 查询团购订单核销记录
     *
     * @param orderVerificationRecordId 团购订单核销记录主键
     * @return 团购订单核销记录
     */
    @Override
    public OrderVerificationRecord selectOrderVerificationRecordByOrderVerificationRecordId(Long orderVerificationRecordId) {
        return orderVerificationRecordMapper.selectOrderVerificationRecordByOrderVerificationRecordId(orderVerificationRecordId);
    }

    /**
     * 查询团购订单核销记录列表
     *
     * @param orderVerificationRecord 团购订单核销记录
     * @return 团购订单核销记录
     */
    @Override
    public List<OrderVerificationRecord> selectOrderVerificationRecordList(OrderVerificationRecord orderVerificationRecord) {
        return orderVerificationRecordMapper.selectOrderVerificationRecordList(orderVerificationRecord);
    }

    /**
     * 新增团购订单核销记录
     *
     * @param orderVerificationRecord 团购订单核销记录
     * @return 结果
     */
    @Override
    public int insertOrderVerificationRecord(OrderVerificationRecord orderVerificationRecord) {
        orderVerificationRecord.setCreateTime(LocalDateTime.now());
        return orderVerificationRecordMapper.insertOrderVerificationRecord(orderVerificationRecord);
    }

    /**
     * 修改团购订单核销记录
     *
     * @param orderVerificationRecord 团购订单核销记录
     * @return 结果
     */
    @Override
    public int updateOrderVerificationRecord(OrderVerificationRecord orderVerificationRecord) {
        orderVerificationRecord.setUpdateTime(LocalDateTime.now());
        return orderVerificationRecordMapper.updateOrderVerificationRecord(orderVerificationRecord);
    }

    /**
     * 批量删除团购订单核销记录
     *
     * @param orderVerificationRecordIds 需要删除的团购订单核销记录主键
     * @return 结果
     */
    @Override
    public int deleteOrderVerificationRecordByOrderVerificationRecordIds(Long[] orderVerificationRecordIds) {
        return orderVerificationRecordMapper.deleteOrderVerificationRecordByOrderVerificationRecordIds(orderVerificationRecordIds);
    }

    /**
     * 删除团购订单核销记录信息
     *
     * @param orderVerificationRecordId 团购订单核销记录主键
     * @return 结果
     */
    @Override
    public int deleteOrderVerificationRecordByOrderVerificationRecordId(Long orderVerificationRecordId)
    {
        return orderVerificationRecordMapper.deleteOrderVerificationRecordByOrderVerificationRecordId(orderVerificationRecordId);
    }

    /**
     * 核销团购订单
     *
     * @param orderVerifyParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult handleVerifyGroupOrder(GroupOrderVerifyParam orderVerifyParam) {
        // 获取当前登录用户id
        Long userId = SecurityUtils.getUserId();
        // 查询订单信息
        Order order = orderMapper.selectOrderByOrderId(orderVerifyParam.getOrderId());
        if (order == null) {
            return AjaxResult.error("所核销的订单记录不存在！");
        }
        if (order.getGroupTimes() == null || order.getGroupRemainingTimes() == null) {
            return AjaxResult.error("核销订单的团购次数信息有误，请核实后再操作！");
        }
        // 校验订单状态是否为待服务(只有待服务的才可核销)
        if (!OrderStateEnum.PENDING_SERVICE.getCode().equals(order.getOrderState())) {
            return AjaxResult.error("只有待服务的订单才可进行核销操作！");
        }
        // 校验预约时间不得在当前时间之前
        if (orderVerifyParam.getAppointmentTime() != null
                && LocalDateTime.now().isAfter(orderVerifyParam.getAppointmentTime())) {
            return AjaxResult.error("预约时间不可选择当前时间之前！");
        }
        // 校验核销码是否过期
        if (order.getVerificationCodeEffectiveDate() != null
                && LocalDate.now().isAfter(order.getVerificationCodeEffectiveDate().toLocalDate())) {
            return AjaxResult.error("核销码已过期，不可进行核销操作！");
        }
        // 校验所输入核销码和订单是否匹配
        if (!Objects.equals(order.getOrderVerificationCode(), orderVerifyParam.getOrderVerificationCode())) {
            return AjaxResult.error("核销码和所属订单不匹配，请核实后再操作！");
        }

        // 预订服务支付完成后生成门岗通行证
        try {
            AccessPasscodeParam accessPasscodeParam = new AccessPasscodeParam();
            accessPasscodeParam.setOrderId(order.getOrderId());
            accessPasscodeParam.setOrderIndex(order.getOrderIndex());
            accessPasscodeParam.setMerchantId(order.getMerchantId());
            accessPasscodeParam.setOrderVerificationCode(order.getOrderVerificationCode());
            merchantAccessPasscodeService.saveAccessPasscode(accessPasscodeParam);
        } catch (Exception e) {
            log.error("团购订单核销-生成门岗通行证失败!orderId=" + order.getOrderId());
            e.printStackTrace();
        }

        // 订单更新前状态
        String oldOrderState = order.getOrderState();
        // 判断是否最后一次
        int groupTimes = order.getGroupTimes();
        int groupRemainingTimes = order.getGroupRemainingTimes();
        boolean isLast = false;
        groupRemainingTimes = groupRemainingTimes - 1;
        if (groupRemainingTimes == 0) {
            isLast = true;
        }

        // 更新订单信息
        Order newOrder = new Order();
        newOrder.setOrderId(order.getOrderId());
        if (isLast) {
            // 订单状态
            newOrder.setOrderState(OrderStateEnum.FINISHED.getCode());
            // 服务结束时间
            newOrder.setServiceEndTime(Date.from(orderVerifyParam.getAppointmentTime().atZone(ZoneId.systemDefault()).toInstant()));
        }
        newOrder.setGroupRemainingTimes(groupRemainingTimes);
        if (userId != null) {
            newOrder.setUpdateBy(userId.toString());
        }
        newOrder.setUpdateTime(LocalDateTime.now());
        // 核销成功，生成新的核销码
        newOrder.setOrderVerificationCode(RandomCodeGenerate.getOrderVerificationCode());
        int orderUpdateResult = orderMapper.updateOrder(newOrder);
        if (orderUpdateResult <= 0) {
            throw new ServiceException("团购服务订单更新失败！");
        }

        // 新增核销记录
        OrderVerificationRecord orderVerificationRecord = new OrderVerificationRecord();
        BeanUtils.copyProperties(orderVerifyParam, orderVerificationRecord);
        orderVerificationRecord.setMemberId(order.getMemberId());
        orderVerificationRecord.setAppointmentStatus("002");
        orderVerificationRecord.setCreateBy(userId == null ? "-" : userId.toString());
        orderVerificationRecord.setUpdateBy(userId == null ? "-" : userId.toString());
        int verificationRecordInsertResult = orderVerificationRecordMapper.insertOrderVerificationRecord(orderVerificationRecord);
        if (verificationRecordInsertResult <= 0) {
            throw new ServiceException("核销记录新增失败！");
        }

        // 根据订单id查询最近一条订单记录数据
        OrderRecord orderRecord = orderRecordMapper.selectRecentOrderRecord(order.getOrderId());
        // 记录订单核销追踪记录
        OrderRecord record = new OrderRecord();
        if (!Objects.isNull(orderRecord)) {
            record.setPreState(orderRecord.getNowState());
        } else {
            record.setPreState(oldOrderState);
        }
        record.setOrderId(order.getOrderId());
        record.setNowState(order.getOrderState());
        record.setOperateInfo("已核销一次服务");
        int orderRecordInsertResult = orderRecordMapper.insertOrderRecord(record);
        if (orderRecordInsertResult <= 0) {
            throw new ServiceException("订单追踪信息新增失败！");
        }
        // 新增订单追踪记录
        if (isLast) {
            // 最后一次核销，需要增加订单状态变更记录
            OrderRecord lastRecord = new OrderRecord();
            if (!Objects.isNull(orderRecord)) {
                lastRecord.setPreState(orderRecord.getNowState());
            } else {
                lastRecord.setPreState(oldOrderState);
            }
            lastRecord.setOrderId(order.getOrderId());
            lastRecord.setNowState(newOrder.getOrderState());
            lastRecord.setOperateInfo("确认完成");
            int lastRecordInsertResult = orderRecordMapper.insertOrderRecord(lastRecord);
            if (lastRecordInsertResult <= 0) {
                throw new ServiceException("订单追踪信息新增失败！");
            }
        }

        return AjaxResult.success("核销成功！");
    }

    /**
     * 查询团购订单核销记录列表
     *
     * @param orderVerificationRecord
     * @return
     */
    @Override
    public List<OrderVerificationRecordVO> selectOrderVerificationRecordVOList(OrderVerificationRecord orderVerificationRecord) {
        return orderVerificationRecordMapper.selectOrderVerificationRecordVOList(orderVerificationRecord);
    }
}
