<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\BaseAreaModel;
use App\Models\S1CartInfoModel;
use App\Models\S1GoodsInfoModel;
use App\Models\S1OrderGoodsModel;
use App\Models\S1OrderInfoModel;
use App\Models\S1OrderRefundModel;
use App\Models\WxUserAddressModel;
use App\Services\Base\ErrorCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class OrderController extends Controller
{
    /**
     * @api {get} /api/order/sure 立即购买(或是购物车结算)
     * @apiDescription 立即购买(或是购物车结算)
     * @apiGroup Order
     * @apiParam {string}   appid          appid
     * @apiParam {int}     [id]        商品id
     * @apiParam {int}    [number]         商品数量
     * @apiParam {array}    [cart_id]         购物车id
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *  HTTP/1.1 200 OK
    {
        "status": true,
        "status_code": 0,
        "message": "",
        "data": {
            "goods": {                           购买商品
                "name": "商品1",
                "sure_number": "12",              确认数量
                "attr_info": "属性",              已选属性
                "pic": "/upload/s1/goods/face/20171013/effbecdc6d9de83d0128e3f08ec6d636.jpg",
            },
            "address": {                         默认地址
                "name": "hahahahaha",
                "tel": "134324",
                "area": "23423423",
                "address": "address",
            }
        }
    }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     */
    public function sure(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user) return $this->error(ErrorCode::ERROR_POWER);
        $validator = Validator::make($request->all(),
            [
                'appid' => 'required',
            ],
            [
                'appid.required' => 'appid不存在',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $goods = [];
        $id = $request->input('id');
        if ($id) {   //商品id存在就是在商品页立即购买
            $goodsinfo = S1GoodsInfoModel::find($id);
            \Log::info(Cache::get('attr_info'));
            if (Cache::get('attr_info') && Cache::get('attr_info')['user_id']==$user->id && Cache::get('attr_info')['goods_id']==$id) {
                $goodsinfo->attr_info = Cache::get('attr_info')['attr_info'];
            }else{
                $goodsinfo->attr_info = null;
            }
            $goodsinfo->sure_number = $request->input('number');
            $goods[] = $goodsinfo;
        }else{            //购物车购买
            $cart_ids = json_decode($request->input('cart_id'),true);
            if (is_array($cart_ids)) {
                foreach ($cart_ids as $value) {
                    $car = S1CartInfoModel::find($value);
                    $goods_info = S1GoodsInfoModel::find($car->s1_goods_id);
                    $goods_info->sure_number = $car->goods_num;
                    $goods_info->attr_info = $car->attr_info;
                    $goods[] = $goods_info;
                }
            }
        }

        $address = WxUserAddressModel::where('wx_user_id',$user->id)->where('status',1)->first();
        return $this->api(compact('goods','address'));
    }



    /**
     * @api {get} /api/order/create 创建订单
     * @apiDescription   创建订单
     * @apiGroup Order
     * @apiParam {string}     appid        appid
     * @apiParam {int}     address_id        收货地址id
     * @apiParam {int}     [id]        商品id
     * @apiParam {int}    [number]         商品数量
     * @apiParam {array}    [attr]         商品属性
     *   //购物车id列表或是商品id
     * @apiParam {array}    [cart_id_list]         购物车id
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *  HTTP/1.1 200 OK
    {
        "status": true,
        "status_code": 0,
        "message": "",
        "data": {
            "s1_order_id": 15
        }
    }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
    {
        "status": false,
        "status_code": 2004,
        "message": "数据异常",
        "data": null
    }
     */
    public function create(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user) return $this->error(ErrorCode::ERROR_POWER);
        $validator = Validator::make($request->all(),
            [
                'appid' => 'required',
                'address_id' => 'required',
            ],
            [
                'appid.required' => 'appid不存在',
                'address_id.required' => '请选择收货地址',
            ]
        );
        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $attr = json_decode($request->input('attr'),true);
        $appid = $request->input('appid');
        $wx_address_id = $request->input('address_id');
        $wx_user_id = $user->id;
        $id = $request->input('id');
        $number = $request->input('number');
        $cart_id_list =json_decode($request->input('cart_id_list'),true);
        $last_id = S1OrderInfoModel::orderBy('id','desc')->first();
        if(empty($last_id)) {
            $next_id = 1;
        }else{
            $next_id = $last_id->id + 1;
        }
        $trade_no = 'WX_'.date('YmdHis').$next_id;
        $order_time = date('Y-m-d H:i:s');
        if (!empty($id)) {   //商品详情处创建订单
            $attr_info = '';
            if (is_array($attr)) {
                foreach ($attr as $k => $v){
                    $attr_info .= $v['attr_group_name'].':'.$v['attr_name'].',';
                }
            }
            $goods = S1GoodsInfoModel::find($id);
            $amount = $goods->price * $number;
            $arr = compact('appid','wx_user_id','wx_address_id','trade_no','amount','order_time');
            $order = S1OrderInfoModel::create($arr);
            $s1_order_id = $order->id;
            $order_info = compact('s1_order_id','s1_goods_id','number','attr_info');
            S1OrderGoodsModel::create($order_info);
            return $this->api(compact('s1_order_id'));
        }elseif(is_array($cart_id_list)){         //购物车创建订单(购物车id)
            $carts = S1CartInfoModel::whereIn('id',$cart_id_list)->with(['goods'=> function ($query) {
                $query->select('id','price');
            }])->get()->toArray();
            $amount = collect($carts)->sum(function ($item) {
                return $item['goods_num']*$item['goods']['price'];
            });
            $arr = compact('appid','wx_user_id','wx_address_id','trade_no','amount','order_time');
            $order = S1OrderInfoModel::create($arr);
            $s1_order_id = $order->id;
            foreach ($carts as $cart) {
                $order_info[] = ['s1_order_id'=>$s1_order_id,'s1_goods_id'=>$cart['s1_goods_id'],
                    'number'=>$cart['goods_num'],'attr_info'=>$cart['attr_info'],'created_at'=>date('Y-m-d H:i:s')
                ];
            }
            S1OrderGoodsModel::insert($order_info);
            return $this->api(compact('s1_order_id'));
        }else{  //参数错误
           return $this->error(ErrorCode::CAT_ERROR);
        }

    }
    /**
     * @api {post} /api/order/pay 支付
     * @apiDescription 支付
     * @apiGroup Order
     * @apiParam {int}   id          订单id
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *  HTTP/1.1 200 OK
    {
        "status": true,
        "status_code": 0,
        "message": "",
        "data": ""
    }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
    {
        "status": false,
        "status_code": 2006,
        "message": "操作失败",
        "data": null
    }
     */
    public function pay(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user) return $this->error(ErrorCode::ERROR_POWER);
        $validator = Validator::make($request->all(),
            [
                'id' => 'required',
            ],
            [
                'id.required' => '订单不存在',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $id = $request->input('id');
        $order = S1OrderInfoModel::find($id);
        if (empty($order)) return $this->error(ErrorCode::ORDER_NOT_EXIST);
            //        支付逻辑
        $order->status = 2;
        $order->pay_time = date('Y-m-d H:i:s');
        $ok = $order->save();
        if ($ok) return $this->api('');
        return $this->error(ErrorCode::OP_ERROR);
    }

    /**
     * @api {post} /api/order/refund 申请售后
     * @apiDescription 申请售后
     * @apiGroup Order
     * @apiParam {int}   order_id          订单id
     * @apiParam {int}   refund_type          售后类型
     * @apiParam {int}   [refund_price]          价格
     * @apiParam {string}   refund_desc          原因
     * @apiParam {array}   pic_list          凭证
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *  HTTP/1.1 200 OK
    {
        "status": true,
        "status_code": 0,
        "message": "",
        "data": ""
    }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
    {
        "status": false,
        "status_code": 2006,
        "message": "操作失败",
        "data": null
    }
     */
    public function refund(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user) return $this->error(ErrorCode::ERROR_POWER);
        $validator = Validator::make($request->all(),
            [
                'order_id' => 'required',
                'refund_desc' => 'required',
                'pic_list' => 'required',
                'refund_type' => 'required',
            ],
            [
                'order_id.required' => '订单不存在',
                'refund_desc.required' => '请填写原因',
                'pic_list.required' => '请上传凭证',
                'refund_type.required' => '请选择售后类型',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $order_id = $request->input('order_id');
        $refund_desc = $request->input('refund_desc');
        $refund_type = $request->input('refund_type');
        $pic_list = json_encode($request->input('pic_list'));
        $order = S1OrderInfoModel::find($order_id);
        if(empty($order)) return $this->error(ErrorCode::ORDER_NOT_EXIST);
        $arr = compact('order_id','refund_desc','refund_type','pic_list');
        $ok = S1OrderRefundModel::firstOrCreate($arr);
        if ($ok) {
            $order->status = 4;
            $order->apply_time = date('Y-m-d H:i:s');
            $order->save();
            return $this->api('');
        }else{
            return $this->error(ErrorCode::OP_ERROR);
        }
    }

    /**
     * @api {get} /api/order/show 订单详情
     * @apiDescription 订单详情
     * @apiGroup Order
     * @apiParam {int}   id          订单id
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *  HTTP/1.1 200 OK
    {
    "status": true,
    "status_code": 0,
    "message": "",
        "data": {
            "user_name": "hahahahaha",
            "address": "中国,浙江省,杭州市,江干区三泰魔方123",
            "trade_no": "123123",
            "order_time": "2017-10-13 09:55:00",
            "amount": "10000",
            "goods_number": 2
        }
    }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
    {
    "status": false,
    "status_code": 2009,
    "message": "订单没有找到",
    "data": null
    }
     */
    public function show(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user) return $this->error(ErrorCode::ERROR_POWER);
        $validator = Validator::make($request->all(),
            [
                'id' => 'required',
            ],
            [
                'id.required' => '订单不存在',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $id = ($request->input('id'));
        $order = S1OrderInfoModel::with('address','goods')->find($id);
        if(empty($order)) return $this->error(ErrorCode::ORDER_NOT_EXIST);
        $arr = [];
        $area = BaseAreaModel::find($order['address']['area']);
        if (!empty($area)){
            $info = explode(',',$area['merger_name']);
            unset($info[0]);
            $info = join('',$info);
        }else{
            $info = '';
        }
        $address = empty($area) ? $order['address']['address'] : $info.$order['address']['address'];
        /* $arr['user_name'] = $order['address']['name'];
         $arr['trade_no'] = $order['trade_no'];
         $arr['order_time'] = $order->order_time;
         $arr['amount'] = $order['amount'];
         $arr['goods_number'] = count($order['goods']);*/
        $order->address_info = $address;
        return $this->api($order);
    }
}
