package com.ichangzuo.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ichangzuo.system.mapper.OrderMapper;
import com.ichangzuo.system.model.entity.Order;
import com.ichangzuo.system.model.query.OrderPageQuery;
import com.ichangzuo.system.model.vo.OrderPageVO;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> {
    public IPage<OrderPageVO> listPage(OrderPageQuery queryParams){
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        return baseMapper.listPaged(new Page<>(pageNum, pageSize), queryParams);
    }

    public Order createNewOrder(Long userId, String payType, String money){
        Date now = new Date();
        SimpleDateFormat formatYmd = new SimpleDateFormat("yyyyMMdd");
        String ymd = formatYmd.format(now);
        SimpleDateFormat formatHms = new SimpleDateFormat("HHmmss");
        String hms = formatHms.format(now);

        Order order = new Order();
        order.setUserId(userId);
        order.setOrderNumber(ymd + "-" + payType + "-" + userId + "-" + hms);
        order.setMoney(Double.parseDouble(money));
        order.setPayway(payType);
        order.setPaytime((int)(now.getTime()/1000));
        order.setState(0);

        if( save(order) )
            return order;

        return null;
    }

    public boolean createNewOrder(String orderNo, String money){
        String[] arr = orderNo.split("-");

        Order order = new Order();
        order.setUserId(Long.parseLong(arr[2]));
        order.setOrderNumber(orderNo);
        order.setMoney(Double.parseDouble(money));
        order.setPayway(arr[1]);
        order.setPaytime((int)(System.currentTimeMillis()/1000));
        order.setState(0);

        return save(order);
    }

    public String generatorOrderNo(Long userId, String payType){
        Date now = new Date();
        SimpleDateFormat formatYmd = new SimpleDateFormat("yyyyMMdd");
        String ymd = formatYmd.format(now);
        SimpleDateFormat formatHms = new SimpleDateFormat("HHmmss");
        String hms = formatHms.format(now);

        return ymd + "-" + payType + "-" + userId + "-" + hms;
    }
}
