<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\LhcOrder as LhcOrderModel;
use App\Models\FundsRecord;
use App\Models\Wallet;
use App\Models\LhcLottery;
use App\Models\PcIssue;
use App\Models\Issue;
use App\Models\JisuLottery;
use Exception;
use App\Constants\HttpStatus;
use Illuminate\Support\Facades\DB;

class LhcOrder extends Controller
{

    /**
     * 订单列表
     */
    public function list()
    {
        try {
            $params = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1'],
                'issue' => ['nullable', 'string'],
                'ordernum' => ['nullable', 'string'],
                'member_id' => ['nullable', 'integer'],
                'first_name' => ['nullable'],
                'game' => ['nullable', 'string'],
                'gameplay' => ['nullable', 'string'],
                'number' => ['nullable'],
                'lottery_status' => ['nullable', 'integer'],
                'is_faker' => ['nullable', 'integer'],
                'id' => ['nullable', 'integer'],
                'type' => ['nullable', 'integer'],
                'start_time' => ['nullable', 'date', 'date_format:Y-m-d', 'required_with:end_time'],
                'end_time' => ['nullable', 'date', 'date_format:Y-m-d', 'required_with:start_time', 'after_or_equal:start_time'],
                // 注册来源：users.from（-1 tg / 0 后台客服 / 1 真实用户 / 2 虚拟用户）
                'from' => ['nullable', 'integer', 'in:-1,0,1,2'],
            ]);
            $page = request()->input('page', 1);
            $limit = request()->input('limit', 15);

            $query = new LhcOrderModel();
            
            $query = LhcOrderModel::with(['items'])->join('users', 'users.member_id', '=', 'lhc_order.member_id');
            if (!empty($params['id'])) {
                $query = $query->where('lhc_order.id', $params['id']);
            }
            if (!empty($params['issue'])) {
                $query = $query->where('lhc_order.issue', $params['issue']);
            }
            if (!empty($params['ordernum'])) {
                $query = $query->where('lhc_order.ordernum', $params['ordernum']);
            }
            if (!empty($params['member_id'])) {
                $query = $query->where('lhc_order.member_id', $params['member_id']);
            }
            if (isset($params['lottery_status']) && $params['lottery_status'] !== null) {
                $query = $query->where('lhc_order.lottery_status', $params['lottery_status']);
            }
            if (isset($params['is_faker']) && $params['is_faker'] !== null) {
                $query = $query->where('lhc_order.is_faker', $params['is_faker']);
            }
            if (!empty($params['game'])) {
                $query = $query->where('lhc_order.game', $params['game']);
            }
            if (!empty($params['gameplay'])) {
                $query = $query->where('lhc_order.gameplay', $params['gameplay']);
            }
            if (!empty($params['number'])) {
                $query = $query->where('lhc_order.number', $params['number']);
            }
            if (!empty($params['type'])) {
                $query = $query->where('lhc_order.type', $params['type']);
            }
            if (!empty($params['first_name'])) {
                $query = $query->where('users.first_name', 'like', "%{$params['first_name']}%");
            }
            // created_at 为 Unix 时间戳（模型 dateFormat=U）
            if (!empty($params['start_time'])) {
                $query = $query->where('lhc_order.created_at', '>=', strtotime($params['start_time'] . ' 00:00:00'));
            }
            if (!empty($params['end_time'])) {
                $query = $query->where('lhc_order.created_at', '<=', strtotime($params['end_time'] . ' 23:59:59'));
            }
            // from=0 合法，不能用 empty()
            if (array_key_exists('from', $params) && $params['from'] !== null && $params['from'] !== '') {
                $query = $query->where('users.from', (int)$params['from']);
            }
            $count = $query->count();
            $list = $query->select(
                    'lhc_order.*',
                    'users.first_name',
                    'users.member_id',
                    'users.from as user_from'
                )
                ->forPage($page, $limit)
                ->orderByDesc('lhc_order.created_at')
                ->get();
            foreach($list as &$info) {
                //六合彩彩票
                if ($info['type'] >= 1 and $info['type'] <= 4) {
                    $lottery = LhcLottery::where('type', $info['type'])->where('issue', $info['issue'])->first();
                    if ($lottery) {
                        $info['lottery'] = [
                            'open_code' => $lottery->open_code,
                            'open_code_other' => ''
                        ];
                    }
                }

                //28
                if ($info['type'] == 5 || $info['type'] == 6) {
                    if ($info['type'] == 6) {
                        $issue = PcIssue::where('issue_no', $info['issue'])->first();
                    } elseif ($info['type'] == 5)  {
                        $issue = Issue::where('issue_no', $info['issue'])->first();
                    }

                    $info['lottery'] = [
                        'open_code' => $issue->winning_numbers,
                        'open_code_other' => $issue->combo
                    ];
                }

                //极速彩票
                if ($info['type'] >= 7 and $info['type'] <= 13) {
                    $lottery = JisuLottery::where('type', $info['type'] - 6)->where('issue', $info['issue'])->first();
                    if ($lottery) {
                        $info['lottery'] = [
                            'open_code' => $lottery->open_code,
                            'open_code_other' => $lottery->open_code_other
                        ];
                    }
                }
            }
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
        return $this->success(['total' => $count, 'data' => $list]);

    }

    //订单详情
    function info()
    {
        try {
            request()->validate([
                'id' => ['required', 'integer'],
            ]);
            $id = request()->input('id');
            $info = LhcOrderModel::with(['items'])
                ->leftJoin('users', 'users.member_id', '=', 'lhc_order.member_id')
                ->where('lhc_order.id', $id)
                ->select('lhc_order.*', 'users.first_name')
                ->first();
            if (!$info) throw new Exception('订单不存在');
            $info = $info->toArray();

            //六合彩彩票
            if ($info['type'] >= 1 and $info['type'] <= 4) {
                $lottery = LhcLottery::where('type', $info['type'])->where('issue', $info['issue'])->first();
                if ($lottery) {
                    $info['lottery'] = [
                        'open_code' => $lottery->open_code,
                        'open_code_other' => ''
                    ];
                }
            }

            //28
            if ($info['type'] == 5 || $info['type'] == 6) {
                if ($info['type'] == 6) {
                    $issue = PcIssue::where('issue_no', $info['issue'])->first();
                } elseif ($info['type'] == 5)  {
                    $issue = Issue::where('issue_no', $info['issue'])->first();
                }

                $info['lottery'] = [
                    'open_code' => $issue->winning_numbers,
                    'open_code_other' => $issue->combo
                ];
            }

            //极速彩票
            if ($info['type'] >= 7 and $info['type'] <= 13) {
                $lottery = JisuLottery::where('type', $info['type'] - 6)->where('issue', $info['issue'])->first();
                if ($lottery) {
                    $info['lottery'] = [
                        'open_code' => $lottery->open_code,
                        'open_code_other' => $lottery->open_code_other
                    ];
                }
            }

        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
        return $this->success($info);
    }

    /**
     * @api {post} /lhcorder/refund 同意退款
     * @apiGroup 订单管理
     */
    public function refund()
    {
        $errors = [];
        try {
            DB::beginTransaction();
            $params = request()->validate([
                'id' => ['required', 'array', 'min:1'],
            ]);
            $orderList = LhcOrderModel::whereIn('id', $params['id'])->get();
            foreach ($orderList as $order) {
                if ($order->lottery_status != 0) {
                    continue;
                }
                
                $order->lottery_status = 4;
                $order->updated_at = time();
                $order->save();

                // 获取用户余额
                $walletInfo = Wallet::where(['member_id' => $order->member_id])->first();
                if (!$walletInfo) continue;
                
                $before = $walletInfo->available_balance;
                $after = bcsub($walletInfo->available_balance, $order->amount, 2);
                $walletInfo->available_balance = $after;
                $walletInfo->save();
                
                
                $remark = LhcOrderModel::getRemark($order->type);
                FundsRecord::addData([
                    'change_type' => $remark.'退款',
                    'amount' => $order->amount,
                    'before_balance' => $before,
                    'after_balance' => $after,
                    'member_id' => $order->member_id,
                    'related_id' => $order->id,
                    'remark' => $remark.'订单退款',
                ]);
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage(), $errors);
        }
        return $this->success();

    }

}
