package com.cf.imes.module.executor.service.order;

import com.cf.imes.module.executor.controller.admin.order.vo.order.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import com.cf.imes.module.executor.dal.dataobject.order.OrderDO;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.common.util.object.BeanUtils;

import com.cf.imes.module.executor.dal.mysql.order.OrderMapper;


import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.module.executor.enums.ErrorCodeConstants.*;

/**
 * 生产单表 order_{N} Service 实现类
 *
 * @author 晨丰科技
 */
@Service
@Validated
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    private static final int DEFAULT_DAYS_TO_ADD = 30;

    @Override
    public Long createOrder(OrderSaveReqVO createReqVO) {
        //校验手机号是否合法
        validatePhoneNumber(createReqVO.getPhoneNumber());
        validatePhoneNumber(createReqVO.getDealerPhoneNumber());
        //验证自定义单号是否存在，业务员、拆单员是否存在
        validateCustomOrderNoExists(createReqVO.getCustomOrderNo());
        validateSalesmanOrderNoExists(createReqVO.getSalesman());
        validateSplitterOrderNoExists(createReqVO.getSplitter());

        LocalDateTime time = getAfterDate(createReqVO.getDeliveryDate());
        createReqVO.setDeliveryDate(time);
        // 插入
        OrderDO order = BeanUtils.toBean(createReqVO, OrderDO.class);
        orderMapper.insert(order);
        // 返回
        return order.getId();
    }

    @Override
    public void updateOrder(OrderSaveReqVO updateReqVO) {
        // 校验存在
        validateOrderExists(updateReqVO.getId());
        // 更新
        OrderDO updateObj = BeanUtils.toBean(updateReqVO, OrderDO.class);
        orderMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrder(Long id) {
        // 校验存在
        validateOrderExists(id);
        // 删除
        orderMapper.deleteById(id);
    }

    private void validateOrderExists(Long id) {
        if (orderMapper.selectById(id) == null) {
            throw exception(ORDER_NOT_EXISTS);
        }
    }

    @Override
    public OrderDO getOrder(Long id) {
        return orderMapper.selectById(id);
    }

    @Override
    public PageResult<OrderDO> getOrderPage(OrderPageReqVO pageReqVO) {
        return orderMapper.selectPage(pageReqVO);
    }

    @Override
    public OrderImportRespVO importOrderList(List<OrderPlateImportExcelVO> importOrders, Boolean isUpdateSupport) {

        return null;
    }

    private LocalDateTime getAfterDate(LocalDateTime date) {
        // 获取当前日期类型 2024-03-06 16:50:15
        // 获取当前日期，明确指定时区为业务所在时区，例如Asia/Shanghai
        ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC"));
        LocalDateTime localDateTime = now.toLocalDateTime();

        if (localDateTime.isAfter(date)) {
            // 添加30天
            LocalDateTime futureDate = localDateTime.plusDays(DEFAULT_DAYS_TO_ADD);
            try {
                // 考虑到异常处理，使用try-catch块
                return futureDate;
            } catch (DateTimeParseException e) {
                // 在实际应用中应该有更详细的错误处理逻辑
                System.err.println("Error parsing future date: " + e.getMessage());
                // 根据业务需求，这里可以选择记录日志、抛出自定义异常或进行其他处理
            }
        }
        return date;
    }

//    验证自定义单号是否存在
    private void validateCustomOrderNoExists(String customOrderNo){
        if (orderMapper.selectOne("custom_order_no", customOrderNo) != null) {
            throw exception(CUSTOM_ORDER_EXISTS);
        }
    }

//    业务员是否存在
    private void validateSalesmanOrderNoExists(String salesman){
        if (orderMapper.selectOne("salesman", salesman) == null) {
            throw exception(SALESMAN_ORDER_NOT_EXISTS);
        }
    }

//    拆单员是否存在
    private void validateSplitterOrderNoExists(String splitter){
        if (orderMapper.selectOne("splitter", splitter) == null) {
            throw exception(SPLITTER_ORDER_NOT_EXISTS);
        }
    }

//    校验手机号是否合法
    private void validatePhoneNumber(String phoneNumber){
        // 定义手机号正则表达式
        String regex = "^1[3-9]\\d{9}$";

        // 编译正则表达式
        Pattern pattern = Pattern.compile(regex);

        // 创建 Matcher 对象
        Matcher matcher = pattern.matcher(phoneNumber);

        // 判断手机号是否匹配正则表达式
        if (matcher.matches()) {
            System.out.println("手机号合法");
        } else {
            throw exception(PHONE_NOT_LAWFUL);
        }
    }
}