<?php

    namespace plugin\admin\app\controller;

    use app\api\repositories\PayRepositories;
    use app\business\PayorderBusiness;
    use Illuminate\Support\Arr;
    use plugin\admin\app\model\ArticleType;
    use plugin\admin\app\model\Good;
    use plugin\admin\app\model\PayAisle;
    use Respect\Validation\Validator;
    use support\Db;
    use support\Request;
    use support\Response;
    use plugin\admin\app\model\Payorder;
    use plugin\admin\app\controller\Crud;
    use support\exception\BusinessException;

    /**
     * 支付订单
     */
    class PayorderController extends Crud
    {

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

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

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

        /**
         * 插入
         * @param Request $request
         * @return Response
         * @throws BusinessException
         */
        public function insert(Request $request): Response
        {
            if ($request->method() === 'POST') {
                return parent::insert($request);
            }
            return view('payorder/insert');
        }

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

        public function select(Request $request): Response
        {
            $param = $request->all();
            $data  = Payorder::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, 'order_no')) {
                    $query->where('order_no', 'like', '%' . $param['order_no'] . '%');
                }

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

                    $query->where('is_pay', $param['is_pay']);
                }
//                if (Arr::get($param, 'goods_type')) {
//                    $query->where('goods_type', $param['goods_type']);
//                }

            })->whereExists(function ($query) use ($param) {
                $query->from('wa_users')->whereRaw('wa_users.id=wa_payorder.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->orderByDesc('id');
            }
            $data = $data->paginate(Arr::get($param, 'limit', 10))->toArray();
            $arr  = [];
            $Good = Good::query();
            foreach ($data['data'] as $k => $v) {
                $pataisle = PayAisle::query()->where('characteristic', $v['pay_characteristic'])->first();
                if ($pataisle) {
                    $pay_characteristic_name = $pataisle['name'] . '--' . $pataisle['title'];
                } else {
                    $pay_characteristic_name = '';
                }
                $arr[] = [
                    'bid_name'                => (clone $Good)->where('id', $v['goods_id'])->value('name'),
                    'user_name'               => $v['user_data']['name'],
                    'user_mobile'             => $v['user_data']['mobile'],
                    'pay_no'                  => $v['pay_no'],
                    'pay_type'                => $v['pay_type'],
                    'pay_characteristic_name' => $pay_characteristic_name,
                    'pay_characteristic'      => $v['pay_characteristic'],
                    'order_no'                => $v['order_no'],
                    'money'                   => $v['money'],
                    'is_pay'                  => $v['is_pay'],
                    'created_at'              => $v['created_at'],
                    'id'                      => $v['id'],
                    'img'                     => $v['img'],
                ];


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

        /** 审核通过
         * @param Request $request
         * @return Response
         */
        public function audit(Request $request): Response
        {
            $param = $request->all();
            Db::beginTransaction();
            try {
                Validator::input($param, [
                    'id' => Validator::notEmpty()->setName('标识'),
                ]);
                $data = Payorder::query()->where('id', $param['id'])->first();
                if (empty($data)) {
                    throw new \Exception('非法操作');
                }
                if ($data->is_pay != 1) {
                    throw new \Exception('订单已处理');
                }
                PayorderBusiness::payorderSave($data->toArray());


                Db::commit();
            } catch (\Throwable $exception) {
                Db::rollBack();
                return json(['code' => 1, 'msg' => $exception->getMessage()]);
            }
            return json(['code' => 0, 'msg' => '成功']);
        }

        /** 支付渠道
         * @return void
         */
        public function addselect(Request $request): Response
        {
            $arr  = [];
            $data = PayAisle::query()->selectRaw('characteristic,name,title')->get()->toArray();
            foreach ($data as $k => $v) {
                $arr[] = [
                    'value' => $v['characteristic'],
                    'name'  => $v['name'] . '--' . $v['title'],
                ];
            }
            return json(['code' => 0, 'data' => $arr, 'msg' => 'ok']);
        }

    }
