<?php

    namespace plugin\admin\app\controller;

    use app\api\repositories\PayRepositories;
    use app\business\GoodsBusiness;
    use app\business\PayorderBusiness;
    use Illuminate\Support\Arr;
    use plugin\admin\app\model\Good;
    use plugin\admin\app\model\Payorder;
    use plugin\admin\app\model\User;
    use plugin\admin\app\model\Withdraw;
    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\MyGood;
    use plugin\admin\app\controller\Crud;
    use support\exception\BusinessException;

    /**
     * 会员产品
     */
    class MyGoodController extends Crud
    {
        /**
         * @var MyGood
         */
        protected $model = null;

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

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

        /**手动购买
         * @param Request $request
         * @return Response
         */
        public function insert(Request $request): Response
        {
            if ($request->isAjax()) {
                $param = $request->all();
                Db::beginTransaction();
                try {
                    $userData = User::query()->where('mobile', $param['mobile'])->first();
                    if (empty($userData)) {
                        throw new \Exception('会员不存在');
                    }
                    $goodsData = Good::query()->where('id', $param['goods_id'])->first();
                    if (empty($goodsData)) {
                        throw new \Exception('产品不存在');
                    }
                    $payorderId = PayorderBusiness::orderAdd([
                        'id'                 => $param['goods_id'],
                        'pay_characteristic' => 99999,
                        'user_data'          => [
                            'id' => $userData->id
                        ],
                        'num'                => $param['num'],
                        'name'               => Arr::get($param, 'name', null),
                        'mobile'             => Arr::get($param, 'mobile', null),
                        'number'             => Arr::get($param, 'number', null),
                        'address'            => Arr::get($param, 'address', null),
                    ]);
                    $payorder   = Db::table('wa_payorder')->where('id', $payorderId)->first();
                    PayorderBusiness::payorderSave(collect($payorder)->toArray());
                } catch (\Throwable $exception) {
                    Db::rollBack();
                    return $this->fail($exception->getMessage());
                }
                Db::commit();
                return $this->success();
            }
            return view('my-good/insert');
        }

        public function select(Request $request): Response
        {
            $param = $request->all();

            $data = MyGood::query()->where(function ($query) use ($param) {
                if (is_numeric(Arr::get($param, 'money.1')) && is_numeric(Arr::get($param, 'money.0'))) {
                    $query->whereBetween('money', [$param['money'][0], $param['money'][1]]);
                } elseif (is_numeric(Arr::get($param, 'money.0'))) {
                    $query->where('money', '>=', $param['money'][0]);
                } elseif (is_numeric(Arr::get($param, 'money.1'))) {
                    $query->where('money', '<=', $param['money'][1]);
                }

                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,'rebate.0') &&  Arr::get($param,'rebate.1')){
//                $query->whereBetween('bonus',[$param['rebate'][0],$param['rebate'][1]]);
//            }elseif (Arr::get($param,'rebate.0')){
//                $query->where('bonus','>=',$param['rebate'][0]);
//            }elseif (Arr::get($param,'rebate.1')){
//                $query->where('bonus','<=',$param['rebate'][1]);
//            }
            })->with('userData:id,name,mobile')
                ->whereExists(function ($query) use ($param) {
                    $query->from('wa_users')->whereRaw('wa_users.id=wa_my_goods.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'] . '%');
                    }
                });


            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();
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['user_name']   = Arr::get($v['user_data'], 'name');
                $data['data'][$k]['user_mobile'] = Arr::get($v['user_data'], 'mobile');
                if($v['status']==1){
                    $data['data'][$k]['status_name'] = '等待邮寄';
                }elseif ($v['status']==2){
                    $data['data'][$k]['status_name'] = '已发货';
                }elseif ($v['status']==2){
                    $data['data'][$k]['status_name'] = '已发货';
                }else{
                    $data['data'][$k]['status_name'] = '已发货';
                }
            }

            return json(['code' => 0, 'data' => $data['data'], 'msg' => 'ok', 'count' => $data['total']]);
        }

        /**更换产品
         * @param Request $request
         * @return Response
         */
        public function edit_shop(Request $request): Response
        {
            if ($request->isAjax()) {
                $param = $request->all();

                Db::beginTransaction();
                try {
                    Validator::input($param, [
                        'id'         => Validator::notEmpty()->setName('非法操作'),
                        'goods_id'   => Validator::notEmpty()->setName('非法操作,识别码2'),
                        'redemption' => Validator::notEmpty()->setName('换购产品'),
                    ]);
                    if ($param['goods_id'] == $param['redemption']) {
                        throw new \Exception('换购产品和当前产品一致，请更换需要换购的产品!');
                    }
                    $data = MyGood::query()->where('id', $param['id'])->first();
                    if (empty($data)) {
                        throw new \Exception('当前订单不存在!');
                    }
                    $goodsData = Good::query()->where('id', $param['redemption'])->first();
                    if (empty($goodsData)) {
                        throw new \Exception('更换产品不存在!');
                    }
                    MyGood::query()->where('id', $param['id'])->update([
                        'goods_id'   => $param['redemption'],
                        'o_goods_id' => $param['goods_id'],
                    ]);
                } catch (\Throwable $exception) {
                    Db::rollBack();
                    return $this->fail($exception->getMessage());
                }
                Db::commit();
                return $this->success();
            }
            return view('my-good/edit_shop');
        }

        /** 批量通过
         * @param Request $request
         * @return Response
         */
        public function pass(Request $request): Response
        {
            try {
                $param = $request->all();
                Validator::input($param, [
                    'id' => Validator::notEmpty()->ArrayType()->setName('标识'),
                ]);
                $withdrawModel = MyGood::query();
                foreach ($param['id'] as $k => $v) {
                    Db::beginTransaction();
                    try {
                        $has = (clone $withdrawModel)->where('id', $v)->lock(true)->first();
                        if (empty($has)) {
                            throw new \Exception('编码为:【' . $v . '】订单不存在!');
                        }
                        if ($has->status != 1) {
                            throw new \Exception('编码为:【' . $v . '】已处理请不要重复提交!');
                        }

                        if ($has && $has->status == 1) {
                            $has->status     = 3;
                            $has->updated_at = date('Y-m-d H:i:s');
                            $has->save();

                        } else {
                            throw new \Exception('编码为:【' . $v . '】已处理请不要重复提交!');
                        }

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


    }
