<?php

namespace plugin\admin\app\controller;

use app\api\repositories\MoneyLogRepositories;
use app\business\StreamBusiness;
use Illuminate\Support\Arr;
use plugin\admin\app\model\ApplyRecord;
use plugin\admin\app\model\UserCark;
use plugin\admin\app\repositories\WithdrawRepositories;
use Respect\Validation\Validator;
use support\Db;
use support\Log;
use support\Request;
use support\Response;
use plugin\admin\app\model\Withdraw;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 提现列表
 */
class UserCarkController extends Crud
{


    /**
     * @var UserCark
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new UserCark();
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('usercark/index');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('usercark/update');
    }

    /**查询收银余额
     * @param Request $request
     * @return Response
     */
    public function select(Request $request): Response
    {
        $param = $request->all();
        $data  = UserCark::query()->where(function ($query) use ($param) {
            if (Arr::get($param, 'created_at.0') && Arr::get($param, 'created_at.1')) {
                $query->whereBetween('created_at', [$param['created_at'][0], $param['created_at'][1]]);
            } elseif (Arr::get($param, 'created_at.0')) {
                $query->where('created_at', '>=', $param['created_at'][0]);
            } elseif (Arr::get($param, 'created_at.1')) {
                $query->where('created_at', '<=', $param['created_at'][1]);
            }

            if (Arr::get($param, 'status')) {
                $query->where('status', $param['status']);
            }
            if (Arr::get($param, 'id')) {
                $query->where('id', $param['id']);
            }

        })->whereExists(function ($query) use ($param) {
            $query->from('wa_users')->whereRaw('wa_users.id=wa_user_social_cark.user_id');
            if (Arr::get($param, 'user_name')) {
                $query->where('name', 'like', '%' . $param['user_name'] . '%');
            }
            if (Arr::get($param, 'user_mobile')) {
                $query->where('mobile', 'like', '%' . $param['user_mobile'] . '%');
            }
        })
            ->with('userData:id,name,mobile');
        if (Arr::get($param, 'field')) {
            $order = 'asc';
            if (Arr::get($param, 'order')) {
                $order = 'desc';
            }
            $data = $data->orderBy($param['field'], $order);
        } else {
            $data = $data->orderBy('updated_at', 'desc');
        }
        $data = $data->paginate(Arr::get($param, 'limit', 10))->toArray();
        $arr  = [];
        foreach ($data['data'] as $k => $v) {

            $arr[] = [
                'id'          => $v['id'],
                'user_name'   => $v['user_data']['name'],
                'user_mobile' => $v['user_data']['mobile'],
                'name'        => $v['name'],
                'number'      => $v['number'],
                'mobile'      => $v['mobile'],
                'card_num'    => $v['card_num'],
                'status'      => $v['status'],
                'created_at'  => $v['created_at'],
                'updated_at'  => $v['updated_at'],
                'address'     => $v['address'],
            ];
        }
        return json(['code' => 0, 'data' => $arr, 'msg' => 'ok', 'count' => $data['total']]);
    }

    /** 批量通过
     * @param Request $request
     * @return Response
     */
    public function pass(Request $request): Response
    {
        try {
            $param = $request->all();
            Validator::input($param, [
                'id' => Validator::notEmpty()->ArrayType()->setName('标识'),
            ]);
            $applyRecordModel = UserCark::query();
            foreach ($param['id'] as $k => $v) {
                Db::beginTransaction();
                try {
                    $system = Db::table('wa_system')->first();

                    $has = (clone $applyRecordModel)->where('id', $v)->lock(true)->first();
                    if (empty($has)) {
                        throw new \Exception('数据不存在!');
                    }
                    if ($has->status != 1) {
                        throw new \Exception('数据已经处理!');
                    }
                    if ($has && $has->status == 1) {
                        $has->status     = 2;
                        $has->updated_at = date('Y-m-d H:i:s');
                        $has->save();

                    } else {
                        throw new \Exception('已处理请不要重复提交!');
                    }

                    Db::commit();
                } catch (\Throwable $exception) {
                    Db::rollBack();
                    throw new \Exception($exception->getMessage());
                }
            }
        } catch (\Throwable $exception) {
            return $this->fail($exception->getMessage());
        }
        return $this->success();
    }

}
