package com.fjhx.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.base.BaseEntity;
import com.fjhx.constants.ErrorMsgConstant;
import com.fjhx.constants.LibrarySupplyLockConstant;
import com.fjhx.entity.ApplyPurchase;
import com.fjhx.entity.Order;
import com.fjhx.entity.Supplier;
import com.fjhx.enums.OrderStatusEnum;
import com.fjhx.mapper.OrderMapper;
import com.fjhx.service.ApplyPurchaseService;
import com.fjhx.service.OrderService;
import com.fjhx.service.SupplierService;
import com.fjhx.utils.Assert;
import org.springblade.core.redis.lock.RedisLockClient;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-08-25
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private RedisLockClient redisLockClient;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private ApplyPurchaseService applyPurchaseService;

    @Override
    public void createOrder(Long supplierId, List<ApplyPurchase> applyPurchaseList, String code) {
        createOrderFun(supplierId, applyPurchaseList, () -> {
            Long count = count(Wrappers.<Order>lambdaQuery()
                    .eq(Order::getCode, code)
                    .eq(BaseEntity::getTenantId, AuthUtil.getTenantId()));
            Assert.eqZero(count, "订号已存在");
            return code;
        });
    }

    @Override
    public void createOrderAuth(Long supplierId, List<ApplyPurchase> applyPurchaseList, String codePrefix) {
        createOrderFun(supplierId, applyPurchaseList, () -> createOrderCode(codePrefix));
    }

    @Override
    public void createOrderAuth(Long supplierId, List<ApplyPurchase> applyPurchaseList) {
        String codePrefix = "PO" + DateUtil.format(new Date(), "yyMMdd-");
        createOrderFun(supplierId, applyPurchaseList, () -> createOrderCode(codePrefix));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void flowNotPass(Long orderId) {
        updateStatus(orderId, OrderStatusEnum.NOT_PASS);
        applyPurchaseService.flowOrderNotPass(orderId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void flowPass(Long orderId) {
        updateStatus(orderId, OrderStatusEnum.PASS);
        applyPurchaseService.flowOrderPass(orderId);
    }

    @Override
    public boolean orderComplete(Long orderId) {

        boolean b = applyPurchaseService.orderIsComplete(orderId);

        if (b) {
            updateStatus(orderId, OrderStatusEnum.COMPLETED);
        }

        return b;
    }

    /**
     * 生成订单
     *
     * @param supplierId        供应商id
     * @param applyPurchaseList 申购列表
     * @param fun               获取订单单号方法
     */
    private void createOrderFun(Long supplierId, List<ApplyPurchase> applyPurchaseList, java.util.function.Supplier<String> fun) {
        String tenantId = AuthUtil.getTenantId();

        // 获取供应商账期
        Supplier supplier = supplierService.getById(supplierId);
        Integer accountPeriod = supplier.getAccountPeriod();

        Order order = redisLockClient.lockFair(LibrarySupplyLockConstant.ORDER_CODE_LOCK + tenantId, () -> {

            String code = fun.get();

            BigDecimal price = applyPurchaseList.stream().map(ApplyPurchase::getApplyPrice)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            Order orderTemp = new Order();
            orderTemp.setPrice(price);
            orderTemp.setArrivalPrice(BigDecimal.ZERO);
            orderTemp.setPayPrice(BigDecimal.ZERO);
            orderTemp.setSupplierId(supplierId);
            orderTemp.setAccountPeriod(accountPeriod);
            orderTemp.setCode(code);
            orderTemp.setStatus(OrderStatusEnum.IN_APPROVAL.getValue());
            save(orderTemp);

            return orderTemp;
        });

        Assert.notEmpty(order, ErrorMsgConstant.SYSTEM_BUSY_ERROR);

        // 赋值申购单属性
        applyPurchaseService.flowOrder(applyPurchaseList, order.getId(), order.getCode(), supplierId, accountPeriod);
    }

    /**
     * 自动生成申购单编号
     */
    public String createOrderCode(String codePrefix) {
        StringBuilder builder = new StringBuilder();
        builder.append(codePrefix);

        Order order = getOne(Wrappers.<Order>lambdaQuery()
                .select(Order::getCode)
                .eq(BaseEntity::getTenantId, AuthUtil.getTenantId())
                .likeRight(Order::getCode, codePrefix)
                .orderByDesc(Order::getCode)
                .last("limit 1"));

        if (order == null) {
            return builder.append("001").toString();
        }

        int codeNum = Integer.parseInt(order.getCode().replace(codePrefix, ""));

        return builder.append(codeNum < 9 ? "00" : codeNum < 99 ? "0" : "").append(codeNum + 1).toString();
    }

    /**
     * 修改订单状态
     */
    private void updateStatus(Long orderId, OrderStatusEnum orderStatusEnum) {
        update(Wrappers.<Order>lambdaUpdate()
                .eq(BaseEntity::getId, orderId)
                .set(Order::getStatus, orderStatusEnum.getValue())
                .set(BaseEntity::getUpdateUser, AuthUtil.getUserId())
                .set(BaseEntity::getUpdateTime, new Date())
        );
    }

}
