package com.ghy.common.utils;

import com.ghy.common.enums.AdapayOrderType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author HH 2022/5/21
 */
@Slf4j
public class AdapayUtils {

    private static final AtomicLong INDEX = new AtomicLong(1L);
    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    /**
     * 生成 Adapay member_id
     *
     * @param customerId 消费者ID
     * @param deptId     分平台id
     * @return Adapay member_id
     */
    public static String getCustomerMemberId(Long customerId, Long deptId) {
        Assert.isTrue(Math.min(customerId, deptId) > 0, "Invalid [customerId] or [deptId]");
        return String.format("C%dD%d", customerId, deptId);
    }

    /**
     * 生成 Adapay member_id
     *
     * @param workerId 师傅id
     * @param deptId   分平台id
     * @return 生成的唯一id
     */
    public static String getWorkerMemberId(Long workerId, Long deptId) {
        Assert.isTrue(Math.min(workerId, deptId) > 0, "Invalid [workerId] or [deptId]");
        return String.format("W%dD%d", workerId, deptId);
    }

    /**
     * 把BigDecimal格式的价格转为保留两位小数的String
     *
     * @param b BigDecimal
     * @return 保留两位小数的String
     */
    public static String bigDecimalToString(BigDecimal b) {
        return b.setScale(2, RoundingMode.CEILING).toString();
    }

    public synchronized static String createOrderNo(AdapayOrderType type) {
        INDEX.compareAndSet(9999L, 1L);
        return type.getCode() + DATETIME_FORMATTER.format(LocalDateTime.now()) + INDEX.getAndIncrement();
    }

}
