<?php
namespace app\admin\server\package;

use app\admin\model\Package;
use app\admin\model\PackageOrder;
use app\admin\model\PackageOrderDetail;
use app\admin\model\SystemAdmin;
use app\admin\model\SystemMenu;
use app\admin\model\SystemRole;

class PackageOrderServer
{
    /**
     * Notes:获取角色列表
     * @param string $keywords
     * @param int $page
     * @param int $limit
     * @return array
     * User: QJF
     * Date: 2022/9/17
     */
    public static function getPackageOrderList(int $page, int $limit, string $keywords)
    {
        [$list, $count] =  PackageOrder::getPackageOrderList($page, $limit,$keywords);

        return compact('list', 'page', 'limit', 'count');
    }

    /**
     * Notes:获取订单详情
     * @param int $order_id
     * @return int
     * User: QJF
     * Date: 2022/9/19
     */
    public static function packageOrderInfo($order_id)
    {
        SystemRole::affairBegin();
        try {
            $where = [];
            $where['order_id'] = $order_id;
            $result = PackageOrder::with('Package')->where($where)->first();
            //关联权益包
            $result['package'] = Package::where(['package_id'=>$result['order_package_id']])->get();
            //订单详情的列表
            $result['detail_list'] = PackageOrderDetail::where(['detail_order_id'=>$order_id])->get();

            if (!empty($result)){
                SystemRole::affairCommit();
                return $result;
            }else{
                return false;
            }
        }catch (\Exception $exception){
            SystemRole::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:修改订单支付状态
     * @param string $order_id
     * @param int $order_finish
     * @return int
     * User: YCP
     * Date: 2022/11/28
     */
    public static function updatePayStatus($order_id, $order_pay_status)
    {
        PackageOrder::affairBegin();
        try {
            $where = [];
            $where['order_id'] = $order_id;
            $data = [];
            $data['order_pay_status'] = $order_pay_status;
            if($order_pay_status == 2){
                $data['order_pay_time'] = time();
            }else{
                $data['order_pay_time'] = "";
            }
            $result = PackageOrder::where($where)->update($data);
            if ($result !== false){
                $user_id = PackageOrder::where($where)->value('order_user_id');
                events('createUserNews', ['log_type' => 0, 'log_uid' => $user_id, 'log_content' => '您的权益包订单支付成功了！']);
                PackageOrder::affairCommit();
                return true;
            }
            throw new \Exception('操作失败！');
        }catch (\Exception $exception){
            PackageOrder::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }
}
