<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\group_activity;


use think\Exception;
use think\facade\Db;
use think\facade\Log;
use app\common\enum\RefundEnum;
use app\common\logic\BaseLogic;
use app\common\logic\RefundLogic;
use app\common\model\equity\UserEquity;
use app\common\model\refund\RefundRecord;
use app\common\model\equity\UserEquityLog;
use app\common\model\group_activity\GroupUserOrder;

/**
 * 拼团用户订单
 * Class GroupOrderLogic
 * @package app\adminapi\logic\group_activity
 */
class GroupUserOrderLogic extends BaseLogic
{
    /**
     * 订单退款
     * @param $params
     * @return false|void
     */
    public static function refundOrder($params)
    {
        Db::startTrans();
        try {
            $order =  GroupUserOrder::where([
                    'id'=>$params['id']
                ])->field('id,sn,status,order_amount,pay_status,pay_way,user_equity_id,user_id,order_terminal')->findOrEmpty()->toArray();
            if(empty($order)){
                self::setError('订单不存在');
                return false;
            }
            if($order['status'] != 1 || $order['pay_status'] != 1){
                self::setError('当前订单不支持退款');
                return false;
            }
            if ($order['user_equity_id']) {
                //判断权益卡是否已使用
                $used = UserEquityLog::where(['user_equity_id' => $order['user_equity_id'],'user_id' => $params['user_id']])->count();
                if ($used) {
                    self::setError('当前权益卡已使用，不支持退款');
                    return false;
                }
                //删除用户权益卡
                $userEquity = UserEquity::where(['id' => $order['user_equity_id'],'user_id' => $params['user_id']])->findOrEmpty();
                $userEquity->delete();
            }

            //将用户订单状态更新为申请退款
            GroupUserOrder::where('id',$order['id'])->update(['status' => 3,'refund_status' => 1]);

            // 生成退款记录
            $recordSn = generate_sn(RefundRecord::class, 'sn');
            $record = RefundRecord::create([
                'sn' => $recordSn,
                'user_id' => $order['user_id'],
                'order_id' => $order['id'],
                'order_sn' => $order['sn'],
                'order_type' => RefundEnum::ORDER_TYPE_GROUP,
                'order_amount' => $order['order_amount'],
                'refund_amount' => $order['order_amount'],
                'refund_type' => RefundEnum::TYPE_ADMIN,
                'transaction_id' => $order['transaction_id'] ?? '',
                'refund_way' => RefundEnum::getRefundWayByPayWay($order['pay_way']),
            ]);

            // 退款
            $result = RefundLogic::refund($order, $record['id'], $order['order_amount'], 1);
            
            if ($result !== true) {
                $resultMsg = RefundLogic::getError();
                Log::write("拼团订单退款失败，订单号：{$order['sn']}，原因：{$resultMsg}");
                self::setError($resultMsg);
                return false;
            }

            Db::commit();
            return true;
        }
        catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            Log::write("拼团订单退款失败：".$e->getMessage());
            return false;
        }
    }
}