package com.ghy.order.service.impl;

import com.ghy.common.constant.UserConstants;
import com.ghy.common.core.text.Convert;
import com.ghy.order.domain.OrderMaster;
import com.ghy.order.mapper.OrderMasterMapper;
import com.ghy.order.request.AppOrderRequest;
import com.ghy.order.service.OrderMasterService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 商品模块实现类
 *
 * @author clunt
 */
@Service
public class OrderMasterServiceImpl implements OrderMasterService {

    @Resource
    private OrderMasterMapper orderMasterMapper;

    AtomicLong index = new AtomicLong(1L);

    private final static ThreadLocal<SimpleDateFormat> dateFormat = ThreadLocal.withInitial(()->new SimpleDateFormat("yyyyMMddHHmmss"));

    @Override
    public String createOrderCode() {
        index.compareAndSet(9999L, 1L);
        return "om" + dateFormat.get().format(new Date()) + index.getAndIncrement();
    }

    @Override
    public OrderMaster createMasterOrder(AppOrderRequest appOrderRequest) {
        return null;
    }

    @Override
    public int insertOrderMaster(OrderMaster orderMaster) {
        return orderMasterMapper.insertOrderMaster(orderMaster);
    }

    @Override
    public int updateOrderMaster(OrderMaster orderMaster) {
        return orderMasterMapper.updateOrderMaster(orderMaster);
    }

    @Override
    public List<OrderMaster> selectOrderMasterList(OrderMaster orderMaster) {
        return orderMasterMapper.selectOrderMasterList(orderMaster);
    }

    @Override
    public OrderMaster selectById(Long orderMasterId) {
        return orderMasterMapper.selectById(orderMasterId);
    }

    @Override
    public OrderMaster selectByCode(String orderMasterCode) {
        return orderMasterMapper.selectByCode(orderMasterCode);
    }

    @Override
    public int deleteOrderMasterByIds(String ids) {
        Long[] orderMasterIds = Convert.toLongArray(ids);
        return orderMasterMapper.deleteOrderMasterByIds(orderMasterIds);
    }

    @Override
    public String checkOrderMasterCodeUnique(OrderMaster orderMaster) {
        long orderMasterId = orderMaster.getId() == null ? -1L : orderMaster.getId();
        OrderMaster info = orderMasterMapper.checkOrderMasterCodeUnique(orderMaster.getCode());
        if (info != null && info.getId() != orderMasterId) {
            return UserConstants.ORDER_CODE_NOT_UNIQUE;
        }
        return UserConstants.ORDER_CODE_UNIQUE;
    }

}
