<?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\SignRecord;
    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 SignRecordController extends Crud
    {


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

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

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

        /**查询收银余额
         * @param Request $request
         * @return Response
         */
        public function select(Request $request): Response
        {
            $param = $request->all();
            $data  = SignRecord::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']);
                }

            })->whereExists(function ($query) use ($param) {
                $query->from('wa_users')->whereRaw('wa_users.id=wa_sign_record.uid');
                if (Arr::get($param, 'user_name')) {
                    $query->where('name', 'like', '%' . $param['user_name'] . '%');
                }
                if (Arr::get($param, 'mobile')) {
                    $query->where('mobile', 'like', '%' . $param['mobile'] . '%');
                }
            })->whereExists(function ($query) use ($param) {
                $query->from('wa_goods')->whereRaw('wa_goods.id=wa_sign_record.goods_id');
                if (Arr::get($param, 'name')) {
                    $query->where('name', 'like', '%' . $param['name'] . '%');
                }
            })->with(['userData:id,name,mobile','goodsData:id,name,pay_price']);
            if (Arr::get($param, 'field')) {
                $order = 'asc';
                if (Arr::get($param, 'order')) {
                    $order = 'desc';
                }
                $data = $data->orderBy($param['field'], $order);
            } else {
                $data = $data->orderByDesc('id');
            }
            $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'],
                    'money'       => $v['money'],
                    'num'         => $v['num'],
                    'goods_name'  => $v['goods_data']['name'],
                    'mobile'      => $v['mobile'],
                    'name'        => $v['name'],
                    'status'      => $v['status'],
                    'created_at'  => $v['created_at'],
                    'address'     => $v['province'] . $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('标识'),
                ]);
                $signRecordModel = SignRecord::query();
                foreach ($param['id'] as $k => $v) {
                    Db::beginTransaction();
                    try {

                        $has = (clone $signRecordModel)->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();
        }

        /** 批量发布
         * @param Request $request
         * @return Response
         */
        public function release(Request $request): Response
        {
            try {
                $param = $request->all();
                Validator::input($param, [
                    'id' => Validator::notEmpty()->ArrayType()->setName('标识'),
                ]);
                $signRecordModel = SignRecord::query();
                foreach ($param['id'] as $k => $v) {
                    Db::beginTransaction();
                    try {

                        $has = (clone $signRecordModel)->where('id', $v)->lock(true)->first();
                        if (empty($has)) {
                            throw new \Exception('申请数据不存在!');
                        }
                        if ($has->status == 3) {
                            throw new \Exception('申请数据已经处理!');
                        }
                        if ($has && $has->status == 2) {
                            $has->status     = 3;
                            $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();
        }

        /** 批量驳回
         * @param Request $request
         * @return Response
         */
        public function reject(Request $request): Response
        {
            try {
                $param = $request->all();
                Validator::input($param, [
                    'id' => Validator::notEmpty()->ArrayType()->setName('标识'),
                ]);
                $signRecordModel = SignRecord::query();

                foreach ($param['id'] as $k => $v) {
                    Db::beginTransaction();
                    try {
                        $has = (clone $signRecordModel)->where('id', $v)->lock(true)->first();
                        if (empty($has)) {
                            throw new \Exception('暂无数据');
                        }
                        if ($has->status != 1) {
                            throw new \Exception('已被审核!');
                        }
                        StreamBusiness::addStream($has->uid, $has->money, streamType18, moldType5, moldTypefild5, $has->id);
                        $has->status = 4;
                        $has->save();
                    } catch (\Throwable $exception) {
                        Db::rollBack();
                        throw new \Exception($exception->getMessage());
                    }
                    Db::commit();
                }
            } catch (\Throwable $exception) {
                return $this->fail($exception->getMessage());
            }
            return $this->success();
        }

    }
