<?php

namespace app\admin\controller;

use app\BaseController;
use app\admin\model\FundsRecord;
use app\admin\model\User;
use app\admin\model\Admin;
use Exception;
use app\admin\model\Order as OrderModel;
use think\facade\Db;

class Order extends BaseController
{
    /**
     * 订单手动退款
     */
    public function adminRefund()
    {
        $errors = [];
        Db::startTrans();
        try {
            $params = $this->request->param();
            
            $admin = Admin::where('id', $this->admin_id)->findOrFail();
            if (!password_verify($params['safe_word'], $admin->payment_password)) throw new Exception('资金密码错误');

            $orderList = OrderModel::whereIn('id', $params['order_id'])->get();
            foreach ($orderList as $order) {
                if ($order->return_status != 0 || $order->pay_status != 1) {
                    continue;
                }
                
                $order->status = 3;
                $order->return_status = 2;
                $order->return_operation_time = time();
                $order->save();

                $user = User::where('user_id', $order->user_id)->findOrFail();
                if (!$user) continue;
                if ($user->type == 1) {
                    FundsRecord::addData([
                        'transaction_type' => 'return_order',
                        'amount_change' => $order->amount,
                        'balance_before' => $user->money,
                        'balance_after' => bcsub($user->money, $order->amount, 2),
                        'user_id' => $user->user_id,
                    ]);
                    $user->money = bcsub($user->money, $order->amount, 2);
                    $user->save();
                }
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage(), $errors);
        }
        return $this->success();
    }

    /**
     * @api {post} /order/refund 同意退款
     * @apiGroup 订单管理
     */
    public function refund()
    {
        $errors = [];
        Db::startTrans();
        try {
            $params = $this->request->param();
            $order_id = $params['order_id'];
            $safeWord = $params['safe_word'];
            $admin = Admin::where('id', $this->admin_id)->findOrFail();
            if (!password_verify($safeWord, $admin->payment_password)) throw new Exception('资金密码错误');
            $order = OrderModel::where('id', $order_id)->findOrFail();
            if (!$order) throw new Exception('订单不存在');
            if ($order->return_status != 1 || $order->pay_status != 1) {
                $errors = ['id' => $order_id];
                throw new Exception("该订单状态无法操作");
            }
            
            $order->status = 3;
            $order->return_status = 2;
            $order->return_operation_time = time();
            $order->save();

            $user = User::where('user_id', $order->user_id)->findOrFail();
            $balanceAfter = bcadd($user->money, $order->amount, 2);
            FundsRecord::addData([
                'transaction_type' => 'return_order',
                'amount_change' => $order->amount,
                'balance_before' => $user->money,
                'balance_after' => $balanceAfter,
                'user_id' => $user->user_id,
            ]);
            $user->money = $balanceAfter;
            $user->save();

            Db::commit();
        } catch (Exception $e) {
            Db::rollBack();
            return $this->error($e->getMessage(), $errors);
        }
        return $this->success();

    }

    /**
     * 驳回退款申请
     * @apiGroup 订单管理
     */
    public function rejection()
    {
        $errors = [];
        Db::startTrans();
        try {
            $params = $this->request->param();
            if (empty($params['failure_msg'])) $params['failure_msg'] = '';

            $order = OrderModel::where('id', $params['order_id'])->findOrFail();
            if (!$order) throw new Exception('订单不存在');
            if ($order->status != 1 || $order->return_status != 1) {
                $errors = ['id' => $params['order_id']];
                throw new Exception("该订单状态无法操作");
            }
            $order->return_operation_time = time();
            $order->failure_msg = $params['failure_msg'];
            $order->save();
            Db::commit();
        } catch (Exception $e) {
            Db::rollBack();
            return $this->error($e->getMessage(), $errors);
        }
        return $this->success();
    }

    /**
     * 订单列表
     */
    public function list()
    {
        try {
            $params = $this->request->param();
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 15);

            $query = new OrderModel();
            if (!empty($params['start_time'])) {
                $startTime = strtotime($params['start_time'] . " 00:00:00");
                $query = $query->where('create_time', '>=', $startTime);
            }
            if (!empty($params['end_time'])) {
                $endTime = strtotime($params['end_time'] . " 23:59:59");
                $query = $query->where('create_time', '<=', $endTime);
            }
            if (!empty($params['id'])) {
                $query = $query->where('id', $params['id']);
            }
            if (!empty($params['order_id'])) {
                $query = $query->where('order_id', $params['order_id']);
            }
            if (!empty($params['user_id'])) {
                $query = $query->where('user_id', $params['user_id']);
            }
            if (isset($params['status'])) {
                $query = $query->where('status', $params['status']);
            }
            if (isset($params['return_status'])) {
                $query = $query->where('return_status', $params['return_status']);
            }
            if (isset($params['pay_status'])) {
                $query = $query->where('pay_status', $params['pay_status']);
            }
            if (isset($params['is_win'])) {
                $query = $query->where('is_win', $params['is_win']);
            }
            if (isset($params['settlement_status'])) {
                $query = $query->where('settlement_status', $params['settlement_status']);
            }
            if (isset($params['is_roll'])) {
                $query = $query->where('is_roll', $params['is_roll']);
            }

            $count = $query->count();
            $list = $query
                ->limit($limit)
                ->page($page)
                ->order('create_time', 'desc')
                ->select();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success(['count' => $count, 'list' => $list]);

    }

    //订单详情
    function info()
    {
        try {
            $order_id = $this->request->param('order_id');
            $order = OrderModel::where('order_id', $order_id)->findOrFail();
            if (!$order) throw new Exception('订单不存在');
            $order = $order->toArray();
            $order['detail'] = json_decode($order['detail'],true);
            $order['game_result']  = $order['game_result'] ? json_decode($order['game_result'],true) : null;
            ksort($order);
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success($order);
    }

}