<?php
/**
 * Created by PhpStorm.
 * User: 思维定制
 * Date: 2019/4/11
 * Time: 17:41
 */

namespace App\Http\Controllers\Api\V1;

use App\Models\AlbumAgentModel;
use App\Models\AlbumProductModel;
use App\Models\AlbumUserModel;
use App\Models\AlbumWatchRecord;
use App\Models\CustomerDetailsModel;
use Illuminate\Http\Request;
use Validator, Response,Auth;
use App\Services\Base\ErrorCode;

class AlbumBossController extends Controller
{
    /**
     * @api {get} /api/album_boss/get_top 经销商排行榜(get_top)
     * @apiDescription 经销商排行榜(get_top)
     * @apiGroup Boss
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "agent": [
     *              {
     *                  "id": 3,
     *                  "avatar": "http://admin.xcx.com/upload/images/20180519/02f2dbe0e1046d7cea8b3b52d5642fb8.jpg",
     *                  "name": "张三",
     *                  "get_count": "客户数量",
     *              }
     *          ],
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function getTop(Request $request)
    {
        $userAuth = Auth('api')->user();
        if (!$userAuth) {
            return $this->error(ErrorCode::ERROR_POWER, '登陆过期!');
        }
        $validator = Validator::make($request->all(), [
            'store_id' => 'required'
        ], [
            'store_id.required' => '缺少商户参数',
        ]);

        if ($userAuth->role != 4) {
            return $this->error(ErrorCode::NOT_BOSS, '该用户没有Boss权限');
        }

        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $store_id = $request->input('store_id');
        $agentData = AlbumAgentModel::where('store_id', $store_id)->orderByDesc('get_count')->paginate(20);
        foreach ($agentData as $value) {
            $user = AlbumUserModel::where([['id', $value->user_id], ['store_id', $store_id]])->get(['avatar']);
            $value->avatar = $user->avatar;
        }

        return $this->api($agentData, 0, 'success');
    }

    /**
     * @api {post} /api/album_boss/agent_customer 经销商客户(agent_customer)
     * @apiDescription 经销商客户(agent_customer)
     * @apiGroup Boss
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiParam {int}    [agent_id]  经销商id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "agent": [
     *              {
     *                  "id": 3,
     *                  "avatar": "http://admin.xcx.com/upload/images/20180519/02f2dbe0e1046d7cea8b3b52d5642fb8.jpg",
     *                  "name": "张三",
     *                  "address": "四川省",
     *                  "phone": "8208208820",
     *                  "lon": "100.123123",
     *                  "lat": "123.123123",
     *              }
     *          ],
     *         "customer": [
     *              {
     *                  "id": 3,
     *                  "avatar": "http://admin.xcx.com/upload/images/20180519/02f2dbe0e1046d7cea8b3b52d5642fb8.jpg",
     *                  "name": "张三",
     *                  "address": "四川省甘肃市"
     *               }
     *          ]
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function agentCustomer(Request $request)
    {
        $userAuth = Auth('api')->user();
        if (!$userAuth) {
            return $this->error(ErrorCode::ERROR_POWER, '登陆过期!');
        }
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'agent_id' => 'required',
            'pageNum' => 'required',
        ], [
            'store_id.required' => '缺少商户参数',
            'agent_id.required' => '缺少经销商参数',
            'pageNum.required' => '缺少页码参数',
        ]);

        if ($userAuth->role != 4) {
            return $this->error(ErrorCode::NOT_BOSS, '该用户没有Boss权限');
        }

        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }

        $data = $request->input();
        $agent = AlbumAgentModel::where([['store_id', $data['store_id']], ['id', $data['agent_id']]])->first();
        $userCount = AlbumWatchRecord::where([
            ['agent_id', $agent->id], ['store_id',$data['store_id']]
        ])->groupBy('open_id')->get();
        $i = 0;
        foreach ($userCount as $value) {
            if ($i >= (($data['pageNum'] + 1) * 20)) {
                break;
            }
            if ($i >= ($data['pageNum'] * 20) && $i < (($data['pageNum'] + 1) * 20)) {
                $user = AlbumUserModel::where('open_id', $value->open_id)->first(['avatar', 'username', 'address']);
                $userComment = CustomerDetailsModel::where('open_id', $value->open_id)->first(['comment']);
                $customer[] = [
                    'name' => $userComment->comment,
                    'avatar' => $user->avatar,
                    'username' => $user->username,
                    'address' => $user->address
                ];
                $i++;
            }
        }

        return $this->api(compact('agent', 'customer'), 0, 'success');
    }



    /**
     * @api {post} /api/album_boss/agent_statistical 经销商数据(agent_statistical)
     * @apiDescription 经销商数据(agent_statistical)
     * @apiGroup Boss
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiParam {int}    [agent_id]  经销商id
     * @apiParam {int}    [start]     开始时间
     * @apiParam {int}    [end]       结束时间
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "favoriteCount":11,
     *         "downloadCount":11,
     *         "shareCount":11,
     *         "newCustomerCount":11,
     *         "totalCustomerCount":11,
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function agentStatistical(Request $request)
    {
        $userAuth = Auth('api')->user();
        if (!$userAuth) {
            return $this->error(ErrorCode::ERROR_POWER, '登陆过期!');
        }
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'agent_id' => 'required',
        ], [
            'store_id.required' => '缺少商户参数',
            'agent_id.required' => '缺少经销商参数',
        ]);

        if ($userAuth->role != 4) {
            return $this->error(ErrorCode::NOT_BOSS, '该用户没有Boss权限');
        }

        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }

        $data = $request->input();
        $end = $request->input('end');
        $start = $request->input('start');
        if (!$end) {
            $end = time();
        }
        if (!$start) {
            $start = 0;
        }
        $end = date('Y-m-d H:i:s', $end);
        $start = date('Y-m-d H:i:s', $start);
        $favoriteCount = AlbumWatchRecord::where([
            ['agent_id', $data['agent_id']],
            ['store_id', $data['store_id']],
            ['action', 1],
            ['updated_at','>=',$start],
            ['updated_at','<=',$end]
        ])->orderByDesc('id')->count();

        $downloadCount = AlbumWatchRecord::where([
            ['agent_id', $data['agent_id']],
            ['store_id', $data['store_id']],
            ['action', 9],
            ['updated_at','>=',$start],
            ['updated_at','<=',$end]
        ])->orderByDesc('id')->count();

        $shareCount = AlbumWatchRecord::where([
            ['agent_id', $data['agent_id']],
            ['store_id', $data['store_id']],
            ['action', 8],
            ['updated_at','>=',$start],
            ['updated_at','<=',$end]
        ])->orderByDesc('id')->count();

        $newCustomerCount = AlbumWatchRecord::where([
            ['agent_id', $data['agent_id']],
            ['store_id', $data['store_id']],
            ['is_new', 1],
            ['updated_at','>=',$start],
            ['updated_at','<=',$end]
        ])->orderByDesc('id')->count();

        $totalCustomerCount = AlbumWatchRecord::where([
            ['agent_id', $data['agent_id']],
            ['store_id', $data['store_id']],
            ['updated_at','>=',$start],
            ['updated_at','<=',$end]
        ])->orderByDesc('id')->groupBy('open_id')->count();

        return $this->api(compact('shareCount', 'totalCustomerCount', 'newCustomerCount', 'downloadCount', 'favoriteCount'));
    }

    /**
     * @api {post} /api/album_boss/agent_overview 经销商总览(agent_overview)
     * @apiDescription 经销商总览(agent_overview)
     * @apiGroup Boss
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiParam {int}    [start]     开始时间
     * @apiParam {int}    [end]       结束时间
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "customerFollow":11,
     *         "downloadCount":11,
     *         "shareCount":11,
     *         "newCustomerCount":11,
     *         "totalCustomerCount":11,
     *         "activeCustomers": [
     *              {
     *                  "day" : 03/25,
     *                  "num" : 111
     *              }
     *          ],
     *          "newCustomers": [
     *              {
     *                  "day" : 03/25,
     *                  "num" : 111
     *              }
     *          ]
     *          "arrFavorite": [
     *              {
     *                  'name':'asdawd',
     *                  'point':'asdawd',
     *                  'num':'1',
     *              }
     *          ]
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumOverview(Request $request)
    {

        $userAuth = Auth('api')->user();
        if (!$userAuth) {
            return $this->error(ErrorCode::ERROR_POWER, '登陆过期!');
        }
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
        ], [
            'store_id.required' => '缺少商户参数',
        ]);

        if ($userAuth->role != 4) {
            return $this->error(ErrorCode::NOT_BOSS, '该用户没有Boss权限');
        }

        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }

        $end = $request->input('end');
        $start = $request->input('start');
        $store_id = $request->input('store_id');
        if (!$end) {
            $end = time();
        }
        if (!$start) {
            $start = 0;
        }
        $end = date('Y-m-d H:i:s', $end);
        $start = date('Y-m-d H:i:s', $start);
        $resGoods = AlbumWatchRecord::where([
            ['store_id',$store_id],['action',3],['updated_at','>=',$start],
            ['updated_at','<=',$end]
        ])->get();
        $arrFavorite = array();
        $total = 0;

        foreach ($resGoods as $key => $val) {
            $goods_data = json_decode($val->detail, true);
            $goods_id = $goods_data['goods_id'];
            $goods = AlbumProductModel::find($goods_id);
            if (!$goods) {
                continue;
            }
            if (isset($arr[$goods->id])) {
                $arrFavorite[$goods->id]['num']++;
            } else {
                $arrFavorite[$goods->id]['num'] = 1;
                $arrFavorite[$goods->id]['name'] = $goods->name;
            }
            $total++;
        }
        $activeCustomers = array();
        $newCustomers = array();
        for ($d = 0; $d < 15; $d++) {
            $Start = mktime(0, 0, 0, date('m'), date('d'), date('y')) + 86400 * $d;
            $End = $Start + 86400;
            $End = date('Y-m-d H:i:s', $End);
            $Start = date('Y-m-d H:i:s', $Start);
            $customerNum = AlbumWatchRecord::where([
                ['store_id', $store_id],
                ['updated_at','>=',$Start],
                ['updated_at','<=',$End]
            ])->orderByDesc('id')->groupBy('open_id')->count();
            $newCustomer = AlbumWatchRecord::where([
                ['store_id', $store_id],
                ['is_new', 1],
                ['updated_at','>=',$Start],
                ['updated_at','<=',$End]
            ])->orderByDesc('id')->count();
            $activeCustomers[] = [
                'day' => date('m', $Start) . '-' . date('d', $End),
                'num' => $customerNum
            ];
            $newCustomers[] = [
                'day' => date('m', $Start) . '-' . date('d', $End),
                'num' => $newCustomer
            ];
        }
        $customerFollow = CustomerDetailsModel::where('store_id', $store_id)->count();
        $downloadCount = AlbumWatchRecord::where([
            ['store_id', $store_id],
            ['action', 9],
            ['updated_at','>=',$start],
            ['updated_at','<=',$end]
        ])->orderByDesc('id')->count();

        $shareCount = AlbumWatchRecord::where([
            ['store_id', $store_id],
            ['action', 8],
            ['updated_at','>=',$start],
            ['updated_at','<=',$end]
        ])->orderByDesc('id')->count();

        $newCustomerCount = AlbumWatchRecord::where([
            ['store_id', $store_id],
            ['is_new', 1],
            ['updated_at','>=',$start],
            ['updated_at','<=',$end]
        ])->orderByDesc('id')->count();

        $totalCustomerCount = AlbumWatchRecord::where([
            ['store_id', $store_id],
            ['updated_at','>=',$start],
            ['updated_at','<=',$end]
        ])->orderByDesc('id')->groupBy('open_id')->count();
        return $this->api(compact('totalCustomerCount', 'newCustomerCount', 'shareCount', 'downloadCount', 'customerFollow', 'newCustomers', 'activeCustomers', 'arrFavorite'));
    }
}