package com.rf.psychological.douyin.service.impl;

import cn.hutool.core.date.DateUtil;
import com.rf.psychological.douyin.model.DouYinOrderEntity;
import com.rf.psychological.douyin.repository.DouYinOrderRepository;
import com.rf.psychological.douyin.service.DouYinOrderService;
import com.rf.psychological.enums.OrderStatus;
import com.rf.psychological.wxpay.utils.OrderNoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:订单信息
 * @Author: mimang
 * @Date: 2023/8/17
 */
@Service
@ConditionalOnProperty(prefix="douyin",name = "isDouYin", havingValue = "true")
public class DouYinOrderServiceImpl implements DouYinOrderService {

    @Autowired
    private DouYinOrderRepository repository;

    /**
     * 获取订单
     * @param resultId 结果Id
     * @param type 支付状态
     * @return
     */
    @Override
    public DouYinOrderEntity findByResultIdAndStatus(String resultId, String type) {
        return repository.findFirstByResultIdAndOrderStatus(resultId,type);
    }

    /**
     * 生成新的订单
     * @param totalAmount 金额
     * @param subject 描述
     * @param body 详情
     * @param resultId 结果Id
     * @return
     */
    @Override
    public DouYinOrderEntity createNewOrder(int totalAmount, String subject, String body, String resultId) {
        DouYinOrderEntity entity = new DouYinOrderEntity();
        entity.setCreateTime(DateUtil.now());
        entity.setBody(body);
        entity.setSubject(subject);
        entity.setTotalAmount(totalAmount);
        entity.setResultId(resultId);
        entity.setOrderStatus(OrderStatus.PROCESSING.name());
        entity.setOutOrderNo(OrderNoUtils.getDouYinOrderNo());
        return repository.save(entity);
    }

    @Override
    public void updateOrder(DouYinOrderEntity orderInfo) {
        orderInfo.setUpdateTime(DateUtil.now());
        repository.save(orderInfo);
    }

    @Override
    public DouYinOrderEntity findByOutOrderNo(String orderNo) {
        return repository.findByOutOrderNo(orderNo);
    }

    @Override
    public List<DouYinOrderEntity> findAllByStatus(OrderStatus notpay) {
        return repository.findAllByOrderStatus(notpay.name());
    }

    @Override
    public boolean checkPayOrder(String resultId) {
        try {
            DouYinOrderEntity orderInfo = repository.findFirstByResultIdAndOrderStatus(resultId,OrderStatus.SUCCESS.name());
            if ( orderInfo == null){
                return false;
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void deleteByNo(String outOrderNo) {
        repository.deleteByOutOrderNo(outOrderNo);
    }
}
