<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\BaseAreaModel;
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 AddressController extends Controller
{
    /**
     * @api {get} /api/my/address/index 地址列表
     * @apiDescription 地址列表
     * @apiGroup My
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *  HTTP/1.1 200 OK
    {
        "status": true,
        "status_code": 0,
        "message": "",
        "data": [
            {
                "id": 1,
                "name": "name1",
                "tel": "13880642880",
                "area": "330104",            区域代码
                "address": "蜀西路",
                "status": "1",                1默认地址
                "addr": {
                    "merger_name": "中国,浙江省,杭州市,江干区",
                }
            }
        ]
    }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     */
    public function index()
    {
        $user = Auth::guard('api')->user();
        if (!$user) return $this->error(ErrorCode::ERROR_POWER);
        $address = WxUserAddressModel::where('wx_user_id',$user->id)->orderBy('created_at','desc')->get();
        foreach ($address as $item) {
            $arr = [] ;
            $area = BaseAreaModel::find($item['area']);
            $city =  BaseAreaModel::find($area['pid']);
            $province =  BaseAreaModel::find($city['pid']);
            $arr['province']['name'] = empty($province) ? '' : $province->name;
            $arr['province']['id'] = empty($province) ? '' : $province->id;
            $arr['city']['name'] = empty($city) ? '' : $city->name;
            $arr['city']['id'] = empty($city) ? '' : $city->id;
            $arr['district']['name'] = empty($area) ? '' : $area->name;
            $arr['district']['id'] = empty($area) ? '' : $area->id;
            $item->district = $arr;
        }
        return $this->api($address);
    }

    /**
     * @api {post} /api/my/address/update 地址编辑
     * @apiDescription 地址编辑
     * @apiGroup My
     * @apiParam {int}   [id]          主键id 存在表示修改
     * @apiParam {string}   name          收货人姓名
     * @apiParam {int}   tel         收货人电话
     * @apiParam {int}   area          省市区地址
     * @apiParam {string}   address         详细地址
     * @apiParam {int}   status          1或0  1为默认地址
     * @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 update(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user) return $this->error(ErrorCode::ERROR_POWER);
        $validator = Validator::make($request->all(),
            [
                'name'         => 'required',
                'area'         => 'required',
                'tel'         => 'required',
                'address'         => 'required',
                'status'         => 'required',
            ],
            [
                'name.required'        => '联系人不能为空',
                'area.required'        => '地址不能为空',
                'tel.required'        => '电话号码不能为空',
                'address.required'        => '地址不能为空',
                'status.required'        => '是否设为默认地址',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(),ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $id = $request->input('id');
        $status = $request->input('status');
        $tel = $request->input('tel');
        $name = $request->input('name');
        $address = $request->input('address');
        $wx_user_id = $user->id;
        $area = $request->input('area');
        if ($status==1 ) {
            WxUserAddressModel::where('wx_user_id',$user->id)->where('status',1)->update(['status'=>0]);
        }
       $arr = [
         compact('status','tel','name','address','area','wx_user_id'),
       ];
        if (!empty($id)) {
            $data = WxUserAddressModel::find($id);
            if (empty($data))  return $this->error(ErrorCode::ADDRESS_NOT_EXIST);
            if(!empty($name))  $data->name = $name;
            if(!empty($tel))  $data->tel = $tel;
            if(!empty($address))  $data->address = $address;
            if(!empty($area)) $data->area = $area;
            if(!empty($status)) $data->status = $status;
            $ok = $data->save();
        }else{
            $ok = WxUserAddressModel::create($arr[0]);
        }
        if ($ok) return $this->api('');
        return $this->error(ErrorCode::OP_ERROR);
    }

    /**
     * @api {get} /api/my/address/show 地址详情
     * @apiDescription 地址详情
     * @apiGroup My
     * @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": {
            "id": 1,
            "name": "hahahahaha",
            "tel": "13880634889",
            "area": "330104",
            "address": "三泰魔方123",
            "status": "0",
            "addr": {
                 "merger_name": "中国,浙江省,杭州市,江干区",
            }
        }
    }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
    {
    "status": false,
    "status_code": 2006,
    "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'        => '收货地址主键id不存在',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(),ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $id = $request->input('id');
        $data = WxUserAddressModel::find($id);
        $area = BaseAreaModel::find($data['area']);
        $city =  BaseAreaModel::find($area['pid']);
        $province =  BaseAreaModel::find($city['pid']);
        $arr['province']['name'] = empty($province) ? '' : $province->name;
        $arr['province']['id'] = empty($province) ? '' : $province->id;
        $arr['city']['name'] = empty($city) ? '' : $city->name;
        $arr['city']['id'] = empty($city) ? '' : $city->id;
        $arr['district']['name'] = empty($area) ? '' : $area->name;
        $arr['district']['id'] = empty($area) ? '' : $area->id;
        $data->district = $arr;
        return $this->api($data);
    }

    /**
     * @api {get} /api/my/address/delete 地址删除
     * @apiDescription 地址删除
     * @apiGroup My
     * @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 delete(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user) return $this->error(ErrorCode::ERROR_POWER);
        $validator = Validator::make($request->all(),
            [
                'id' => 'required',
            ],
            [
                'id.required' => '主键id不存在',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $id = $request->input('id');
        $data = WxUserAddressModel::find($id);
        if (empty($data))  return $this->error(ErrorCode::ADDRESS_NOT_EXIST);
        $ok = WxUserAddressModel::destroy($id);
        if($data->status==1){  //如果默认地址被删除 重新默认一个地址
            $info = WxUserAddressModel::where('wx_user_id',$user->id)->first();
            $info->status=1;
            $info->save();
        }
        if ($ok) return $this->api('');
        return $this->error(ErrorCode::OP_ERROR);
    }

    /**
     * @api {get} /api/my/address/area 返回省市区地址
     * @apiDescription 返回省市区地址
     * @apiGroup My
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *  HTTP/1.1 200 OK

     */
    public function area()
    {
        $data = Cache::get('list');
        if (empty($data)) {
            $list = BaseAreaModel::select('id','name')->where('pid',100000)->get()->toArray();
            foreach ($list as $key => $item) {
                $list[$key]['list'] = BaseAreaModel::select('id','name')->where('pid',$item['id'])->get()->toArray();
                foreach ($list[$key]['list'] as $k => $v){
                    $list[$key]['list'][$k]['list'] = BaseAreaModel::select('id','name')->where('pid',$v['id'])->get()->toArray();
                }
            }
            Cache::forever('list', $list);
        }
        return $this->api($data);
    }
    /**
     * @api {get} /api/my/address/edit 修改默认地址
     * @apiDescription 修改默认地址
     * @apiGroup My
     * @apiParam {int}   id          主键id
     * @apiParam {int}   status          1
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *  HTTP/1.1 200 OK
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     */
    public function edit(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user) return $this->error(ErrorCode::ERROR_POWER);
        $validator = Validator::make($request->all(),
            [
                'id'         => 'required',
                'status'         => 'required',
            ],
            [
                'id.required'        => '主键id不存在',
                'status.required'        => '是否设为默认地址',
            ]
        );

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(),ErrorCode::CLIENT_WRONG_PARAMS);
        }
        $id = $request->input('id');
        $status = $request->input('status');
        $data = WxUserAddressModel::find($id);
        if (empty($data))  return $this->error(ErrorCode::ADDRESS_NOT_EXIST);
        if ($status==1 ) {
            WxUserAddressModel::where('wx_user_id',$user->id)->where('status',1)->update(['status'=>0]);
             $data->status = $status;
            $ok = $data->save();
            if ($ok) return $this->api('');
            return $this->error(ErrorCode::OP_ERROR);
        }
        return $this->error(ErrorCode::OP_ERROR);
    }

}
