<?php

namespace App\Http\Controllers\Api\V1;


use App\Models\AgentBannerModel;
use App\Models\AlbumAgentModel;
use App\Models\AlbumBannerModel;
use App\Models\AlbumCatModel;
use App\Models\AlbumFavoriteModel;
use App\Models\AlbumFormId;
use App\Models\AlbumManufacturerModel;
use App\Models\AlbumNavModel;
use App\Models\AlbumNewsModel;
use App\Models\AlbumProductModel;
use App\Models\AlbumProductPriceModel;
use App\Models\AlbumProductStyleModel;
use App\Models\AlbumStatisticalModel;
use App\Models\AlbumUserModel;
use App\Models\AlbumWatchRecord;
use App\Models\CustomerCatRecordModel;
use App\Models\CustomerDetailsModel;
use EasyWeChat\Kernel\Messages\Text;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Tinify\Tinify;
use Validator, Response,Auth;
use App\Services\Base\ErrorCode;
use WXBizDataCrypt;
use EasyWeChat\Factory;

class AlbumController extends Controller
{

    private $wechat_app;


    public function albumSetting(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
        ], [
            'store_id.required' => '店铺信息未知',
        ]);
        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }
        $store_id = $request->store_id;
        //小程序設置

        $setting = AlbumManufacturerModel::where('store_id', $store_id)->first();
        //轮播图
        $banner = AlbumBannerModel::where('store_id', $store_id)->orderByDesc('sort')->get();

        //底部导航栏
        $navbar = AlbumNavModel::where([['store_id', $store_id],['state',0]])->orderByDesc('sort')->get();

        //顶部菜单栏
        $menus = AlbumNavModel::where([['store_id', $store_id],['state',1]])->orderByDesc('sort')->get();

        $news = AlbumNewsModel::where([['store_id', $store_id]])->orderByDesc('sort')->paginate(5);

        $userAuth = Auth('api')->user();
        $agent_set = array();
        if ($userAuth && $userAuth->is_dealer == 1) {
            $user_agent = AlbumAgentModel::where('user_id', $userAuth->id)->first();
            $agent_set['set_price_point'] = $user_agent->set_price_point;
            $agent_set['is_show_ma_price'] = $user_agent->is_show_ma_price;
        }

        return $this->api(compact('setting', 'banner', 'news', 'navbar', 'menus', 'agent_set'));
    }



    /**
     * @api {post} /api/album/xyx_login 登陆(xyx_login)
     * @apiDescription 登陆(xyx_login)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [code]
     * @apiParam {int}    [agent_id]  经销商id
     * @apiParam {int}    [store_id]  商户id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *           "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImIyNGI3MzY3MDNmZDg3MGFjNTg2MWIxNDUzMDcyYjljYzFmNmJhMzE2NTAxZWVlNGYzM2M5MTIzNzFmNGYzZjg2MTY1M2YxMjE2YzE4OTFiIn0.eyJhdWQiOiI5IiwianRpIjoiYjI0YjczNjcwM2ZkODcwYWM1ODYxYjE0NTMwNzJiOWNjMWY2YmEzMTY1MDFlZWU0ZjMzYzkxMjM3MWY0ZjNmODYxNjUzZjEyMTZjMTg5MWIiLCJpYXQiOjE1NDA3OTYyMTYsIm5iZiI6MTU0MDc5NjIxNiwiZXhwIjoxNTcyMzMyMjE1LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.Ruihvl_HMCAHx9XDfeckz48Q_72kfG7vWDsqDrZWbrjq-yuNpM3LrUF-nlsKjedo97BwU_Apz-jnGVqr0ONKZlH-aBKDmIgM2aUZfFADsHhHNJH_oU2fMe1bOrjfUp-PJxfVWQS8c8h5RYmeqtzAYCKaD4P7OZbLmOX0YosKghpaGtiyE65s6jtrOXRhAzXAhYsZToQNBMokFVRqGih9EWuVp6EVwRtI3cb4IV6iQf08cX9DGlLLBJJzLWR5ZWgxJLAGrj5iMCWBl4JKVR8Fsy-xnx3EtrB7ODpJH6hB_u3XnUSAFuaG-KzMPLsj45iqg2hy53er2xtcfAowQFsPoAbZZu0n8c9hWt4GLemR6N1iZ3LBViv3tL5BK52pinQzAnmvltAhJP1YhfTOOjzkxcYVh2JeJagufEoxeeUarMMn21gQSFEzKFCimI7zZQxhT9leLpUn51DLD8Mu87NpYb3JN-JFbOlIDA7bDN3bNto7uuSuC4eBwPo3Ge0StuW4kjHsDTcrVF2He_8FdrPcPpGcvQsXQgv4vwlEhbL8dTlrOodum7H_tY_qUxUG1pEg6bfpn_82ej-AOSc9xi0nrhdcS9y_Z68rcwOJu8esI1pXm9TeQdZIDG85y_t74At8XN6oFcIM__6_dTne_3DHwijW-uOLupNky-5J4ILmZck",
     *           "user": {
     *               "user_id": 1,
     *               "is_agent": 1,
     *               "agent_id": 4
     *            }
     *      }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumXyxLogin(Request $request)
    {
        $datas = $request->input();
        $validator = Validator::make($request->all(), [
            'code' => 'required',
            'agent_id' => 'required',
            'nickName' => 'required',
            'iv' => 'required',
            'encryptData' => 'required',
            'avatar' => 'required',
            'store_id' => 'required'
        ], [
            'code.required' => 'code不能为空!',
            'agent_id.required' => 'agent_id不能为空!',
            'nickName.required' => '昵称不能为空!',
            'iv.required' => '偏移量不能为空!',
            'encryptData.required' => '加密数据不能为空!',
            'avatar.required' => '头像不能为空!',
            'store_id.required' => '站点ID不能为空!'
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $this->wechat_app = AlbumManufacturerModel::where('store_id', $datas['store_id'])->first();
        if (!$this->wechat_app) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '厂家参数未初始化!', $validator->messages());
        }
        $config = [
            'app_id' => $this->wechat_app->xyx_id,
            'secret' => $this->wechat_app->xyx_secret,

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',


        ];

        $app = Factory::miniProgram($config);
        $res = $app->auth->session($datas['code']);
        if (!$res || empty($res['openid'])) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '获取用户OpenId失败!', $validator->messages());
        }

        $session = $res['session_key'];
        $decryptedData = $app->encryptor->decryptData($session, $datas['iv'], $datas['encryptData']);
        if (!isset($decryptedData['unionId'])) {
            $check = AlbumUserModel::where([['open_id', $res['openid']],['store_id',$datas['store_id']]])->first();
        } else {
            $check = AlbumUserModel::where([['wechat_union_id', $decryptedData['unionId']],['store_id',$datas['store_id']]])->first();
        }

        if (!$check) {
            $add['username'] = $datas['nickName'];
            $add['open_id'] = $res['openid'];
            $add['wechat_union_id'] = isset($decryptedData['unionId']) ? $decryptedData['unionId'] : '';
            $add['avatar'] = $datas['avatar'];
            $add['is_dealer'] = 0;
            $add['model'] = 1;
            $add['store_id'] = $datas['store_id'];
            $res = AlbumUserModel::create($add);
            if ($res) {
                $check = $res;
                $user = [
                    'user_id' => $check->id,
                    'phone' => '',
                    'is_agent' => 0,
                    'agent_id' => '',
                ];
            } else {
                $user = [
                    'error' => 1
                ];
            }
        } else {
            $save['username'] = $datas['nickName'];
            $save['avatar'] = $datas['avatar'];
            $save['model'] = 1;
            AlbumUserModel::where('open_id', $res['openid'])->update($save);
            if ($check->is_dealer == 1) {
                $user_agent = AlbumAgentModel::where([['user_id',$check->id],['status',1]])->first();
                $agent_id = $user_agent['id'];
            } else {
                $agent_id = '';
            }
            $user = [
                'user_id'  => $check->id,
                'phone'    => $check->phone,
                'is_agent' => $check->is_dealer,
                'agent_id' => $agent_id,
            ];
        }
        if (Auth::loginUsingId($check->id)) {
            $userAuth = Auth::user();
            if ($check->is_dealer == 0) {
                if ($request->input('agent_id') != 0) {
                    $userAuth->up_agent_id = $request->input('agent_id');
                }
                $add_record['agent_id'] = $userAuth->up_agent_id;
                $add_record['open_id'] = $check->open_id;
                $add_record['action'] = 4;
                $add_record['store_id'] = $datas['store_id'];
                $add_record['detail'] = null;
                $check_new_customer = AlbumWatchRecord::where([
                    ['agent_id', $userAuth->up_agent_id],['open_id', $check->open_id],['store_id', $datas['store_id']]
                ])->first();
                $check_user = AlbumWatchRecord::where([
                  ['open_id', $check->open_id],['store_id', $datas['store_id']]
                ])->first();
                \Log::info($check_user);

                if ($check_user) {
                    $add_record['is_new'] = 0;
                } else {
                    $add_record['is_new'] = 1;
                }
               // \Log::info($add_record);
                AlbumWatchRecord::create($add_record);
              //  dd($add_record);
                $user_agent = AlbumAgentModel::where([['id',$add_record['agent_id']],['store_id',$datas['store_id']]])->first();
               // dd($user_agent);
                if ($user_agent) {
                    if (empty($check_new_customer)) {
                        $user_agent->get_count++;
                    }
                    $user_agent->interactive++;
                    $user_agent->pointCount++;
                    $user_agent->newCount = $user_agent->pointCount + $user_agent->favoriteCount + $user_agent->callCount + $user_agent->share_times + $user_agent->get_count;
                    $user_agent->save();
                    $agent = AlbumUserModel::where([['id',$user_agent->user_id],['store_id',$datas['store_id']]])->first();
                    $this->sendLogsMessage($datas['store_id'], $agent->open_id, 4, $userAuth->username, $agent->g_open_id);
                } else {
                    $userAuth->up_agent_id = 0;
                }
            } else {
                $userAuth->up_agent_id = 0;
            }
            $userAuth->save();
            $user['up_agent_id'] = $userAuth->up_agent_id;
            if ($userAuth->is_boss == 1) {
                $user['role'] = 4;
            } else {
                $user['role'] = 0;
            }
            if (!file_exists(public_path() . '/base/poster/avatar/' . $datas['store_id'])) {
                mkdir(public_path() . '/base/poster/avatar/' . $datas['store_id'], 0755, true);
            }
            $res_image = getUrlImage($userAuth->avatar, public_path() . '/base/poster/avatar/' . $datas['store_id'] . "/$userAuth->id.jpg");
            imageToCircle($res_image);
            $token = $userAuth->createToken($userAuth->id . '-' . $userAuth->openid)->accessToken;
            $conf = AlbumManufacturerModel::where('store_id', $datas['store_id'])->first();
            $getPhone = $conf->getPhone;
            $getFocus = $conf->getFocus;
            return $this->api(compact('token', 'user', 'getPhone', 'getFocus'));
        } else {
            return $this->error(ErrorCode::INCORRECT_USER_OR_PASS);
        }
    }


    /**
     * @param $url
     * @return mixed
     */
    public function curlGet($url)
    {
        //初始化
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }


    /**
     * @api {get} /api/album/goods 商品列表(goods)
     * @apiDescription 商品列表(goods)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [cat_id]  分类id
     * @apiParam {string}    [keywords]  关键词.
     * @apiParam {int}    [style]  风格
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "goods": [
     *              {
     *                  "id": 3,
     *                  "cover_pic": "http://admin.xcx.com/upload/images/20180519/02f2dbe0e1046d7cea8b3b52d5642fb8.jpg",
     *                  "name": "简约",
     *                  "style": "纯白",
     *                  "hot_cake": 1,
     *                  "news": 1,
     *                  "price": ""
     *              }
     *          ],
     *         "name": 品牌名
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumGoods(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'cat_id' => 'required',
            'parent_id' => 'required',
            'store_id' => 'required',
        ], [
            'cat_id.required' => '缺少分类参数',
            'parent_id.required' => '缺少父分类参数',
            'store_id.required' => '缺少商户参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $data = $request->input();
        $cat_id = request('cat_id');
        $store_id = request('store_id');
        $parent_id = request('parent_id');


        $select_info = ['cat_id' => $cat_id,'parent_id' => $parent_id];

        if ($userAuth->up_agent_id != 0 && $cat_id != "undefined" && $parent_id != "undefined") {
            $add_record['agent_id'] = $userAuth->up_agent_id;
            $add_record['open_id'] = $userAuth->open_id;
            $add_record['action'] = 2;
            $add_record['store_id'] = $store_id;
            $add_record['detail'] = json_encode($select_info);
            AlbumWatchRecord::create($add_record);
            $user_agent = AlbumAgentModel::where('id', $userAuth->up_agent_id)->first();
            $user_agent->interactive++;
            $user_agent->save();
            $agent = AlbumUserModel::where('id', $user_agent->user_id)->first();
            try {
                $this->sendLogsMessage($store_id, $agent->open_id, 2, $userAuth->username, $agent->g_open_id);
            } catch (\Exception $e) {
                \Log::info($e);
            }
        }
        if (isset($data['keywords']) && !empty($data['keywords'])) {
            $keywords = '%' . $data['keywords'] . '%';

            $goods = AlbumProductModel::where([['name','like',$keywords],['store_id',$data['store_id']],['cat_id',$cat_id],['store_id',$store_id]]);

        } else {
            $goods = AlbumProductModel::where([['cat_id',$cat_id],['store_id',$store_id]]);
        }

        if ($userAuth->up_agent_id != 0) {
            $agent_in = AlbumAgentModel::where('id', $userAuth->up_agent_id)->first();
            $set_show_price = $agent_in->is_show_ma_price;
        } else {
            $set_show_price = 0;
        }


        if ($userAuth->is_dealer == 1) {
            $agent_me = AlbumAgentModel::where('user_id', $userAuth->id)->first();
            $set_show_price = $agent_me->is_show_ma_price;
        }


        $goods = $goods->select('id', 'cover_pic', 'thumb', 'name', 'style', 'hot_cake', 'news', 'price_default', 'ma_price', 'ma_price_comment')
            ->orderByDesc('sort')->paginate(9);


        foreach ($goods as $key => $val) {
            if ($userAuth->is_dealer != 1) {
                if ($userAuth->up_agent_id == 0) {
                    $goods[$key]['price'] = '';
                } else {
                    $check = AlbumProductPriceModel::where([['agent_id',$userAuth->up_agent_id],['store_id',$data['store_id']],['product_id',$val['id']]])->first();
                    if ($check) {
                        $goods[$key]['price'] = $check->price;
                    } else {
                        $goods[$key]['price'] = '';
                    }
                }
            } elseif ($userAuth->is_dealer == 1) {
                $user_agent = AlbumAgentModel::where('user_id', $userAuth->id)->first();
                $agent_id = $user_agent['id'];
                $check = AlbumProductPriceModel::where([['agent_id',$agent_id],['store_id',$data['store_id']],['product_id',$val['id']]])->first();
                if ($check) {
                    $goods[$key]['price'] = $check->price;
                } else {
                    $goods[$key]['price'] = '';
                }
            }
        }
        $data = AlbumManufacturerModel::where('store_id', $store_id)->first();
        $name = $data['name'];
        return $this->api(compact('goods', 'name', 'set_show_price'));
    }




    /**
     * @api {get} /api/album/goods-detail 商品详细(goods-detail)
     * @apiDescription 商品列表(goods-detail)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [goods_id]  商品id
     * @apiParam {int}    [store_id]  商户id 模拟值为0
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *          "id": 3,
     *          "store_id": 0,
     *          "cat_id": 9,
     *          "specifications_img": "http://admin.xcx.com/upload/images/20180519/02f2dbe0e1046d7cea8b3b52d5642fb8.jpg",
     *          "style": "纯白",
     *          "sort": 11,
     *          "cover_pic": "http://admin.xcx.com/upload/images/20180519/02f2dbe0e1046d7cea8b3b52d5642fb8.jpg",
     *          "hot_cake": 1,
     *          "news": 1,
     *          "detail": "<p>达达娃达娃达娃大青蛙大全大是大非如果v率v恶策但是许多女性的项目部的不行么法可没副本副本副本么方便</p>",
     *          "created_at": "2018-05-19 15:09:04",
     *          "updated_at": "2018-05-19 15:09:04",
     *          "deleted_at": null,
     *          "install_img": "http://admin.xcx.com/upload/images/20180519/02f2dbe0e1046d7cea8b3b52d5642fb8.jpg",
     *          "name": "简约",
     *          "detail_pic": ""
     *          "price": "",
     *          "price_default": "",
     *          "mobile": "",
     *          "address": "",
     *          "realname": "",
     *          "is_favorite": 1,
     *          "favorite_id": 4
     *      }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumGoodsDetail(Request $request)
    {
        //  $userAuth = AlbumXyxUserModel::find(1);
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'goods_id' => 'required',
            'store_id' => 'required',
      //      'parent_id' => 'required',
        ], [
            'goods_id.required' => '缺少商品参数',
            'store_id.required' => '缺少STORE参数',
      //      'parent_id.required' => '缺少PARENT参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $goods_id = request('goods_id');
        $parent_id = request('parent_id');
        $store_id = request('store_id');
        $select_info = ['goods_id' => $goods_id];
        if ($userAuth->up_agent_id != 0) {
            $add_record['agent_id'] = $userAuth->up_agent_id;
            $add_record['open_id'] = $userAuth->open_id;
            $add_record['action'] = 3;
            $add_record['store_id'] = $store_id;
            $add_record['detail'] = json_encode($select_info);
            AlbumWatchRecord::create($add_record);

            $user_agent = AlbumAgentModel::where('id', $userAuth->up_agent_id)->first();
            $user_agent->interactive++;
            $user_agent->save();
            $agent = AlbumUserModel::where('id', $user_agent->user_id)->first();
            try {
                $this->sendLogsMessage($store_id, $agent->open_id, 3, $userAuth->username, $agent->g_open_id);
            } catch (\Exception $e) {
                \Log::info($e);
            }
        }
        $ma = AlbumManufacturerModel::where('store_id', $store_id)->first();
        $goods = AlbumProductModel::where([['id',$goods_id],['store_id',$store_id]])->first();

        $cat_record['agent_id'] = $userAuth->up_agent_id;
        $cat_record['open_id'] = $userAuth->open_id;
        $cat_record['store_id'] = $store_id;
        $cat_record['cat_id'] = $goods->cat_id;
        $cat_record['parent_id'] = $parent_id ?? 0;
        CustomerCatRecordModel::create($cat_record);
        if (!empty($goods) && $userAuth->is_dealer != 1) {

            $address = AlbumAgentModel::where('id', $userAuth->up_agent_id)->first();
            $price = DB::table('album_product_price')->where([['agent_id',$userAuth->up_agent_id],['store_id',$store_id],['product_id',$goods['id']]])->first();
            if (!empty($price)) {
                $goods->price = $price->price;
            } else {
                $goods->price = '';
            }
            $check_favorite = AlbumFavoriteModel::where([['user_id',$userAuth->id],['store_id',$store_id],['product_id',$goods['id']]])->first();
            //dd($check_favorite);
            if ($check_favorite) {
                $goods->is_favorite = 1;
                $goods->favorite_id = $check_favorite->id;
            } else {
                $goods->is_favorite = 0;
                $goods->favorite_id = '';
            }
        } elseif (!empty($goods) && $userAuth->is_dealer == 1) {

            $address = AlbumAgentModel::where([['store_id', $store_id],['user_id', $userAuth->id]])->first();
            $price = DB::table('album_product_price')->where([['agent_id',$address->id],['store_id',$store_id],['product_id',$goods['id']]])->first();

            if (!empty($price)) {
                $goods->price = $price->price;
            } else {
                $goods->price = '';
            }

            $goods->is_favorite = 0;
            $goods->favorite_id = '';
        }
        if ($userAuth->up_agent_id == 0 || !$address) {
            $goods->price = '';
            $goods->mobile = $ma->phone;
            $goods->address = $ma->address;
            $goods->realname = $ma->name;
            $goods->avatar = $ma->avatar;
        } else {
            $agent = AlbumUserModel::where('id', $address->user_id)->first();
            $goods->mobile = $address->phone;
            $goods->address = $address->address;
            $goods->realname = $address->name;
            $goods->avatar = $agent->avatar;
        }
        return $this->api($goods);
    }

    /**
     * @api {get} /api/album/favorite_list 收藏列表(favorite_list)
     * @apiDescription 收藏列表(favorite_list)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id 模拟值为0
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": [
     *          {
     *              "id": 4,
     *              "user_id": 1,
     *              "deleted_at": null,
     *              "created_at": "2018-10-29 15:51:47",
     *              "updated_at": "2018-10-29 15:53:15",
     *              "product_id": 3,
     *              "store_id": 0,
     *              "goods": {
     *                  "id": 3,
     *                  "store_id": 0,
     *                  "cat_id": 9,
     *                  "specifications_img": "http://admin.xcx.com/upload/images/20180519/02f2dbe0e1046d7cea8b3b52d5642fb8.jpg",
     *                  "style": "纯白",
     *                  "sort": 11,
     *                  "cover_pic": "http://admin.xcx.com/upload/images/20180519/02f2dbe0e1046d7cea8b3b52d5642fb8.jpg",
     *                  "hot_cake": 1,
     *                  "news": 1,
     *                  "detail": "<p>达达娃达娃达娃大青蛙大全大是大非如果v率v恶策但是许多女性的项目部的不行么法可没副本副本副本么方便</p>",
     *                  "created_at": "2018-05-19 15:09:04",
     *                  "updated_at": "2018-05-19 15:09:04",
     *                  "deleted_at": null,
     *                  "install_img": "http://admin.xcx.com/upload/images/20180519/02f2dbe0e1046d7cea8b3b52d5642fb8.jpg",
     *                  "name": "简约",
     *                  "detail_pic": ""
     *              }
     *          }
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */

    public function albumFavoriteList(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
        ], [
            'store_id.required' => '缺少商户参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $data = $request->input();
        $favorite = AlbumFavoriteModel::where([['user_id',$userAuth->id],['store_id',$data['store_id']]])->get();
        foreach ($favorite as $key => $val) {
            $favorite[$key]['goods'] = AlbumProductModel::where([['id',$val['product_id']],['store_id',$data['store_id']]])->first();
        }
        return $this->api($favorite);
    }

    /**
     * @api {post} /api/album/get-watch-recored 查看客户浏览情况(get-watch-recored)
     * @apiDescription 查看客户浏览情况(get-watch-recored)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id 模拟值为0
     * @apiParam {int}    [type]  查询方式 1 按用户 2 按时间 3 按类型
     * @apiParam {int}    [user_id]  user_id
     * @apiParam {int}    [action]  行为类型 1 收藏  2查看类目 3查看商品 4登陆 5点击图片 6 点击导航 7一键拨号
     * @apiParam {int}    [start_time]  查询开始时间
     * @apiParam {int}    [end_time]  查询结束时间
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": [
     *        "type1":{   1 收藏  2查看类目 3查看商品 4登陆 5点击图片 6 点击导航 7一键拨号
     *              "time": 2018-1-1 10:10:12,
     *              "action": '做了什么什么都做',
     *              "user": [
     *                  "username":"王小贱",
     *                  "avatar":"awdawdawdawdawdawd",头像
     *                  "phone":"1123123123123"
     *              ]
     *          }
     *          ...
     *          "count":6;
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */

    public function albumGetWatchRecord(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'type' => 'required'
        ], [
            'store_id.required' => '缺少商户参数',
            'type.required' => '缺少类型参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $type = $request->input('type');
        $store_id = $request->input('store_id');
        if ($userAuth->is_dealer != 1) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '该用户不是经销商!', $validator->messages());
        }
        $user_agent = AlbumAgentModel::where('user_id', $userAuth->id)->first();
        $query = AlbumWatchRecord::where([['agent_id',$user_agent->id],['store_id',$store_id]]);
        switch ($type) {
            case '1':
                if (!$request->input('user_id')) {
                    return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!');
                }
                $user = AlbumUserModel::find(request('user_id'));
                $query = $query->where('open_id', $user->open_id);
                break;
            case '2':
                if (!$request->input('start_time') || !$request->input('end_time')) {
                    return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!');
                }
                $start_time = date('Y-m-d H:i:s', $request->input('start_time'));
                $end_time = date('Y-m-d H:i:s', $request->input('end_time'));
                $query = $query->where([['created_at','>=',$start_time],['created_at','<=',$end_time]]);
                break;
            case '3':
                if (!$request->input('action')) {
                    return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!');
                }
                $query = $query->where([['action',$request->input('action')]]);
                break;
        }
        $res = $query->get();
        $action = '';

        foreach ($res as $key => $val) {
            \Log::info('action:' . $val->action . ',id:' . $val->id . ';end');
            if ($val->action == 4) {
                $action = '进入我的画册';
            } elseif ($val->action == 1 || $val->action == 3) {
                $goods_data = json_decode($val->detail, true);
                $goods_id = $goods_data['goods_id'];
                $goods = AlbumProductModel::find($goods_id);
                if (!$goods) {
                    continue;
                }
                $cat = AlbumCatModel::find($goods->cat_id);
                $val->action == 1 ? $act = '收藏' : $act = '查看';
                if (empty($cat)) {
                    continue;
                }
                $action = $act . '了您的' . $cat->name . '分类下的商品 ' . $goods->name;
            } elseif ($val->action == 2) {
                $cat_data = json_decode($val->detail, true);
                if ($cat_data['cat_id'] == "undefined" || !$cat_data['cat_id']) {
                    continue;
                }
                $cat = AlbumCatModel::find($cat_data['cat_id']);
                if (empty($cat)) {
                    continue;
                }
                $action = '浏览了您的 ' . $cat->name . '分类下的商品列表';
            } elseif ($val->action == 5) {
                $goods_data = json_decode($val->detail, true);
                $goods_id = $goods_data['goods_id'];
                $goods = AlbumProductModel::find($goods_id);
                if (!$goods) {
                    continue;
                }
                $cat = AlbumCatModel::find($goods->cat_id);
                if (empty($cat)) {
                    continue;
                }
                $action = '点击了您的' . $cat->name . '分类下的商品 ' . $goods->name . '的' . $goods_data['detail'];
            } elseif ($val->action == 6) {
                $detail = json_decode($val->detail, true);
                $address = $detail['detail'];
                $action = '查看了您的地址' . $address . '，并且点击了导航';
            } elseif ($val->action == 7) {
                $detail = json_decode($val->detail, true);
                $phone = $detail['detail'];
                $action = '查看了您的电话' . $phone . '，并且点击了拨号';
            }
            $user = AlbumUserModel::where([
                ['open_id',$val->open_id],['store_id',$val->store_id]
            ])->select(['username','avatar','phone'])->first();
            $data_res[] = [
                'time'   => $val->created_at,
                'action' => $action,
                'user'   => $user
            ];
        }
        return $this->api(compact('data_res'));
    }


    /**
     * @api {post} /api/album/get_data_goods 获取访问数据(get_data_goods)
     * @apiDescription 获取访问数据(get_data_goods)
     * @apiGroup Album
     * @apiPermission 需要登录
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id 模拟值为0
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": [
     *          {
     *              "1": [
     *                  '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 albumGetDataGoods(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required'
        ], [
            'store_id.required' => '缺少商户参数'
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $store_id = $request->input('store_id');
        if ($userAuth->is_dealer != 1) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '该用户不是经销商!', $validator->messages());
        }

        $user_agent = AlbumAgentModel::where('user_id', $userAuth->id)->first();
        $res = AlbumWatchRecord::where([['agent_id',$user_agent->id],['store_id',$store_id],['action',3]])->get();
        $arr = array();
        $total = 0;
        foreach ($res 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])) {
                $arr[$goods->id]['num']++;
            } else {
                $arr[$goods->id]['num'] = 1;
                $arr[$goods->id]['name'] = $goods->name;
            }
            $total++;
        }
        foreach ($arr as $key => $val) {
            $arr[$key]['point'] = ($val['num'] / $total * 100) . '%';
        }
        return $this->api(compact('arr'));
    }


    /**
     * @api {post} /api/album/get_data_cat 获取分类访问数据(get_data_cat)
     * @apiDescription 获取分类访问数据(get_data_cat)
     * @apiGroup Album
     * @apiPermission 需要登录
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id 模拟值为0
     * @apiParam {int}    [parent_id]
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": [
     *          {
     *              "1": [
     *                  '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 albumGetDataCat(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'parent_id' => 'required'
        ], [
            'store_id.required' => '缺少商户参数',
            'parent_id.required' => '缺少风格参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $store_id = $request->input('store_id');
        $parent_id = $request->input('parent_id');
        if ($userAuth->is_dealer != 1) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '该用户不是经销商!', $validator->messages());
        }

        $user_agent = AlbumAgentModel::where('user_id', $userAuth->id)->first();
        $cat = AlbumCatModel::where([['store_id',$store_id],['parent_id', $parent_id]])->get(['name','id'])->toArray();
        $total = 0;
        foreach ($cat as $key => $val){
            $count = CustomerCatRecordModel::where([['agent_id',$user_agent->id],['store_id',$store_id],['cat_id',$val['id']]])->count();
            $total += $count;
            $cat[$key]['num'] = $count;
        }
        foreach ($cat as $key => $val) {
            if ($val['num'] == 0 || $total == 0) {
                $cat[$key]['point'] = 0;
            } else {
                $cat[$key]['point'] = ($val['num'] / $total * 100) . '%';
            }
        }
        return $this->api(compact('cat'));
    }


    /**
     * @api {post} /api/album/get_data_cat_single 单用户获取分类访问数据(get_data_cat_single)
     * @apiDescription 单用户获取分类访问数据(get_data_cat_single)
     * @apiGroup Album
     * @apiPermission 需要登录
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id 模拟值为0
     * @apiParam {int}    [open_id]
     * @apiParam {int}    [parent_id]
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": [
     *          {
     *              "1": [
     *                  '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 albumGetDataCatSingle(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'open_id' => 'required',
            'parent_id' => 'required'
        ], [
            'store_id.required' => '缺少商户参数',
            'open_id.required' => '缺少风格参数',
            'parent_id.required' => '缺少父分类参数',
            // 'end.required'=>'缺少结束时间参数',
            //'start.required'=>'缺少开始时间参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $store_id = $request->input('store_id');
        $open_id = $request->input('open_id');
        $parent_id = $request->input('parent_id');
        $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);
        if ($userAuth->is_dealer != 1) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '该用户不是经销商!', $validator->messages());
        }
        $user_agent = AlbumAgentModel::where('user_id', $userAuth->id)->first();
        $cat = AlbumCatModel::where([['store_id',$store_id],['parent_id',$parent_id]])->get(['name','id'])->toArray();
        $total = 0;
        foreach ($cat as $key => $val) {
            $count = CustomerCatRecordModel::where([['agent_id',$user_agent->id],['store_id',$store_id],['open_id',$open_id],['cat_id',$val['id']],['updated_at','>=',$start],['updated_at','<=',$end]])->count();
            $total += $count;
            $cat[$key]['num'] = $count;
        }
        foreach ($cat as $key => $val) {
            if ($val['num'] == 0 || $total == 0) {
                $cat[$key]['point'] = 0;
            } else {
                $cat[$key]['point'] = ($val['num'] / $total * 100) . '%';
            }
        }
        return $this->api(compact('cat'));
    }

    /**
     * @api {post} /api/album/get-cart-of-watch 客户浏览情况概览(get-cart-of-watch)
     * @apiDescription 客户浏览情况概览(get-cart-of-watch)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id 模拟值为0
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": [
     *         "count_today":0,
     *         "count_all":0,
     *         "count_share":0,
     *         "user": {
     *              "username":"王小贱",
     *              "avatar":"awdawdawdawdawdawd",头像
     *               "phone":"1123123123123"
     *               "open_id":"1123123123123"
     *              }
     *         "count":6,
     *         "action":[
     *              "type1":1,
     *              "type2":1,
     *              "type3":1,
     *              "type4":1,
     *              "type5":1,
     *              "type6":1,
     *              "type7":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 albumGetCartOfWatch(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'end' => 'required',
            'start' => 'required',
        ], [
            'store_id.required' => '缺少商户参数',
            'end.required' => '缺少结束时间参数',
            'start.required' => '缺少开始时间参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $store_id = $request->input('store_id');
        $end = $request->input('end');
        $start = $request->input('start');
        $end= date('Y-m-d H:i:s',$end);
        $start= date('Y-m-d H:i:s',$start);
        if($userAuth->is_dealer!=1) return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '该用户不是经销商!', $validator->messages());
        // if($userAuth->up_agent_id==0) return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '未选择经销商!', $validator->messages());
        $user_agent = AlbumAgentModel::where('user_id',$userAuth->id)->first();
        $count_user = AlbumWatchRecord::where([['agent_id',$user_agent->id],['store_id',$store_id],['updated_at','>=',$start],['updated_at','<=',$end]])->orderBy('id','DESC')->groupBy('open_id')->get();
        $checkAllstart = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $checkAllend = $checkAllstart+86400;
        $checkAllstart = date('Y-m-d H:i:s',$checkAllstart);
        $checkAllend = date('Y-m-d H:i:s',$checkAllend);
        $count_today = AlbumWatchRecord::where([['agent_id',$user_agent->id],['store_id',$store_id],['updated_at','>=',$checkAllstart],['updated_at','<=',$checkAllend]])->groupBy('open_id')->count();
        $count_list = AlbumWatchRecord::where([['agent_id',$user_agent->id],['store_id',$store_id]])->groupBy('open_id')->get();
        $count_all = count($count_list);
        $count_share = $user_agent->share_times;
        $users = Array();
        if($count_user){
            foreach($count_user as $key=>$val){
                $user = AlbumUserModel::where([['open_id',$val->open_id],['store_id',$val->store_id]])->select(['id','username','avatar','phone','open_id'])->first();
                $customer = CustomerDetailsModel::where([['store_id',$store_id],['open_id',$val->open_id],['agent_id',$user_agent->id]])->first(['purpose_level','comment','tips']);
                $user->time = $val->updated_at;
                if($customer){
                    $user->purpose_level = $customer->purpose_level;
                    $user->comment = $customer->comment;
                    $user->tips = $customer->tips;
                }else{
                    $user->purpose_level = 0;
                    $user->comment = 0;
                    $user->tips = 0;
                }
                $users[] = $user;
            }
        }
        $count = count($users);
        $action = Array();
        for($i=1;$i<=7;$i++){
            $res = AlbumWatchRecord::where([['agent_id',$user_agent->id],['store_id',$store_id],['action',$i]])->get();
            $action['type'.$i] = count($res);
        }
        return $this->api(compact('count','users','action','count_today','count_all','count_share'));
    }
    /**
     * @api {get} /api/album/checklogin 登陆应用(checklogin)
     * @apiDescription 登陆应用(checklogin)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id 模拟值为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
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */

    public function albumchecklogin(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
        ],[
            'store_id.required'=>'缺少商户参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $data = $request->input();
        $favorite = AlbumManufacturerModel::where([['store_id',$data['store_id']]])->first();

        $conf = $favorite->redirectapp;
        return $this->api($conf);
    }

    /**
     * @api {get} /api/album/favorite_del 收藏删除(favorite_del)
     * @apiDescription 收藏删除(favorite_del)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id 模拟值为0
     * @apiParam {int}    [favorite_id]  收藏id
     * @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
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */

    public function albumFavoriteDel(Request $request)
    {
        //$userAuth = AlbumXyxUserModel::find(1);
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'favorite_id' => 'required',
        ],[
            'store_id.required'=>'缺少商户参数',
            'favorite_id.required'=>'缺少收藏参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $data = $request->input();
        $favorite = AlbumFavoriteModel::find($data['favorite_id']);
        if(!$favorite){
            $d = [
                'code' =>1,
                'msg' =>'删除失败，或者该收藏已移除',
            ];
        } else {
            $res = $favorite->delete();
            if($res){
                $d = [
                    'code' =>1,
                    'msg' =>'删除成功',
                ];
            } else {
                $d = [
                    'code' =>1,
                    'msg' =>'删除失败，或者该收藏已移除',
                ];
            }
        }
        return $this->api($d);
    }


    /**
     * @api {get} /api/album/save_form_id 添加Form_id(save_form_id)
     * @apiDescription 添加Form_id(save_form_id)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiParam {int}    [form_id]  form_id
     * @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
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumSaveFormId(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'form_id' => 'required',
        ],[
            'store_id.required'=>'缺少商户参数',
            'form_id.required'=>'缺少FormId',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $data = $request->input();
        $data['open_id'] = $userAuth->open_id;
        $res = AlbumFormId::create($data);
        if($res){
            $d = [
                'code' =>0,
                'msg' =>'success',
            ];
        }else{
            $d = [
                'code' =>1,
                'msg' =>'error',
            ];
        }
        return $this->api($d);
    }

    /**
     * @api {get} /api/album/add_favorite 添加收藏(add_favorite)
     * @apiDescription 添加收藏(favorite_list)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiParam {int}    [product_id]  商品id
     * @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
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */

    public function albumAddFavorite(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'product_id' => 'required',
        ],[
            'store_id.required'=>'缺少商户参数',
            'product_id.required'=>'缺少商品参数',
        ]);

        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $data = $request->input();
        $time = mktime(0,0,0,date('m'),date('d'),date('y'));
        $check = AlbumStatisticalModel::where([['time',$time],['store_id',$data['store_id']]])->first();
        if($check){
            $check->share_times ++;
            $check->save();
        }else{
            $add['time'] = $time;
            $add['store_id'] = $data['store_id'];
            $add['share_times'] = 0;
            $add['favorite_times'] = 1;
            AlbumStatisticalModel::create($add);
        }
        $select_info = ['goods_id' => $data['product_id']];
        if ($userAuth->up_agent_id != 0) {
            $agent = AlbumAgentModel::where('id', $userAuth->up_agent_id)->first();
            $agent->favoriteCount++;
            $agent->interactive++;
            $agent->newCount = $agent->pointCount + $agent->favoriteCount + $agent->callCount + $agent->share_times + $agent->get_count;
            $agent->save();
            $add_record['agent_id'] = $userAuth->up_agent_id;
            $add_record['open_id'] = $userAuth->open_id;
            $add_record['action'] = 1;
            $add_record['store_id'] = $data['store_id'];
            $add_record['detail'] = json_encode($select_info);
            $user_agent = AlbumAgentModel::where('id',$userAuth->up_agent_id)->first();
            $agent = AlbumUserModel::where('id',$user_agent->user_id)->first();
            try{
                $this->sendLogsMessage($data['store_id'],$agent->open_id,1,$userAuth->username,$agent->g_open_id);
            }catch (\Exception $e){

            }
            AlbumWatchRecord::create($add_record);
        }
        $check_user = AlbumUserModel::find($userAuth->id);
        $check_f = AlbumFavoriteModel::where([['user_id',$userAuth->id],['product_id',$data['product_id']]])->first();
        if(!$check_user||$check_f){
            $d = [
                'code' =>1,
                'msg' =>'该用户不存在或者已添加',
            ];
            return $this->api($d);
        }
        $data['user_id'] = $userAuth->id;
        $res = AlbumFavoriteModel::create($data);
        if($res){
            $d = [
                'code' =>0,
                'id'=>$res->id,
                'msg' =>'success',
            ];
        }else{
            $d = [
                'code' =>1,

                'msg' =>'error',
            ];
        }
        return $this->api($d);
    }
    /**
     * @api {get} /api/album/cat 分类列表(cat)
     * @apiDescription 画册分类(cat)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [parent_id]  一级菜单传0 二级菜单的id从一级菜单里面获取
     * @apiParam {int}    [store_id]  商户id 模拟值为0
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": [
     *          {
     *              "id": 9,
     *              "name": "圣地亚哥",
     *              "parent_id": 0,
     *              "level": "00",
     *              "pic_url": "http://admin.xcx.com/upload/images/20180518/af6cc8fd71241744ccd638afc6ac25f2.png",
     *              "created_at": "2018-05-19 14:55:48",
     *              "updated_at": "2018-05-19 14:55:48",
     *              "store_id": 0,
     *              "deleted_at": null,
     *              "sort": 0
     *          }
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumCat(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
        ],[
            'store_id.required' => '缺少商户参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $cat_id = $request->input('cat_id') ?? 0;
        $store_id = request('store_id');
        $cats = AlbumCatModel::where([['parent_id',$cat_id],['store_id',$store_id]])->orderByDesc('sort')->get();
        return $this->api($cats);
    }

    /**
     * @api {get} /api/album/style 属性列表(style)
     * @apiDescription 分类样式(style)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id 模拟值为0
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": [
     *          {
     *              "id": 2,
     *              "name": "1111",
     *              "deleted_at": null,
     *              "created_at": "2018-06-05 17:35:08",
     *              "updated_at": "2018-06-05 17:35:08",
     *              "store_id": 0
     *          }
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumStyle(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
        ],[
            'store_id.required'=>'缺少商户参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $store_id = request('store_id');
        $style = AlbumProductStyleModel::where([['store_id',$store_id]])->orderByDesc('id')->get();
        return $this->api($style);
    }

    /**
     * @api {get} /api/album/set-price 经销商修改价格(set-price)
     * @apiDescription 画册(set-price)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [goods_id]  商品id
     * @apiParam {int}    [store_id]  商户id 模拟值为0
     * @apiParam {double}    [price]  价格
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data":[
     *          "msg":返回信息,
     *          "data":修改后价格
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumSetPrice(Request $request)
    {
        $userAuth = Auth('api')->user();
        $user_agent = AlbumAgentModel::where('user_id',$userAuth->id)->first();
        $agent_id = $user_agent['id'];
        $data = $request->all();
        $product = AlbumProductModel::where('id', $data['goods_id'])->first();
        //print_r($data);
        $save = array();
        $return_data = array();

        $save['price'] = $data['price'];
        $check = AlbumProductPriceModel::where([['agent_id',$agent_id],['store_id',$data['store_id']],['product_id',$data['goods_id']]])->first();
        if(empty($check)){
            $save['agent_id'] = $agent_id;
            $save['store_id'] = $data['store_id'];
            $save['cat_id'] = $product->cat_id;
            $save['name'] = $product->name;
            $save['product_id'] = $data['goods_id'];
            $res = AlbumProductPriceModel::create($save);
        }else{
            $res = AlbumProductPriceModel::where([['agent_id',$agent_id],['store_id',$data['store_id']],['product_id',$data['goods_id']]])->update($save);
        }
        if($res){
            $return['msg'] = 'success';
            $return_data['price'] = $data['price'];
        } else {
            $return['msg'] = 'error';
        }

        $return['data'] = $return_data;
        return $this->api($return);
    }

    /**
     * @api {post} /api/album/set-phone 获取用户号码(set-phone)
     * @apiDescription 获取用户号码(set-phone)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id 模拟值为0
     * @apiParam {string}    [code]  code
     * @apiParam {string}    [iv]  偏移量
     * @apiParam {string}    [encrypted]  加密参数
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data":[
     *          "msg":返回信息,
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumSavePhone(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'code' => 'required',
            'iv' => 'required',
            'encrypted' => 'required',
        ],[
            'store_id.required'=>'缺少商户参数',
            'code.required'=>'缺少code参数',
            'iv.required'=>'缺少偏移量参数',
            'encrypted.required'=>'缺少加密参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $this->wechat_app = AlbumManufacturerModel::where('store_id',$request->input('store_id'))->first();
        $config = [
            'app_id' => $this->wechat_app->xyx_id,
            'secret' => $this->wechat_app->xyx_secret,

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',


        ];

        $app = Factory::miniProgram($config);
        $res = $app->auth->session($request->input('code'));

        if (!$res || empty($res['openid'])) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '获取用户OpenId失败!', $validator->messages());
        }

        $session_key = $res['session_key'];
        $pc = new WXBizDataCrypt($this->wechat_app->xyx_id, $session_key);
        $errCode = $pc->decryptData($request->input('encrypted'), $request->input('iv'), $data);
        if($errCode==0){
            $data = json_decode($data,true);
            $userAuth->phone = $data['phoneNumber'];

            $res = $userAuth->save();
            if($res){
                return $this->api(['msg'=>'success']);
            }else{
                return $this->api(['msg'=>'error']);
            }
        }elseif($errCode == -41003){
            return $this->api(['msg'=>'请求错误，请重试']);
        }

    }

    /**
     * @api {post} /api/album/set-watch 获取用户操作记录(set-watch)
     * @apiDescription 获取用户操作记录(set-watch)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id 模拟值为0
     * @apiParam {string}    [detail] 详细
     * @apiParam {string}    [type]   5点击图片 6 点击导航 7一键拨号
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data":[
     *          "msg":返回信息,
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumSetWatch(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'type' => 'required',
            'detail' => 'required',
        ],[
            'store_id.required'=>'缺少商户参数',
            'type.required'=>'缺少类型参数',
            'detail.required'=>'缺少详细参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $data = $request->input();
        if($data['type']==5&&!empty($data['goods_id'])) {
            $select_info = ['goods_id'=>$data['goods_id'],'detail'=>$data['detail']];
        }elseif($data['type']==5&&empty($data['goods_id'])){
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '缺少goodsid');
        }else{
            $select_info = ['detail'=>$data['detail']];
        }
        if($userAuth->up_agent_id!=0){
            $add_record['agent_id'] = $userAuth->up_agent_id;
            $add_record['open_id'] = $userAuth->open_id;
            $add_record['action'] = $data['type'];
            $add_record['store_id'] = $data['store_id'];
            $add_record['detail'] = json_encode($select_info);
            // dd($add_record);
            $res = AlbumWatchRecord::create($add_record);
            $user_agent = AlbumAgentModel::where('id',$userAuth->up_agent_id)->first();
            if ($data['type'] == 7 || $data['type'] == 6) {
                $user_agent->callCount++;
                $user_agent->interactive++;
                $user_agent->newCount = $user_agent->pointCount + $user_agent->favoriteCount + $user_agent->callCount + $user_agent->share_times + $user_agent->get_count;
                $user_agent->save();
            }
            $agent = AlbumUserModel::where('id',$user_agent->user_id)->first();
            if($res){
                try{
                    $this->sendLogsMessage($data['store_id'],$agent->open_id,$data['type'],$userAuth->username,$agent->g_open_id);
                }catch (\Exception $e){

                }
                return $this->api(['msg'=>'success']);
            }else{
                return $this->api(['msg'=>'error']);
            }
        }
    }

    public function test()
    {
        getUrlImage('111', public_path() . '/base/poster/avatar/' . 1 . "/1.jpg");
        /*$weChatApp = AlbumManufacturerModel::where('store_id', 1)->first();\Log::info('2221');
        $config = [
            'app_id' => $weChatApp->G_app_id,
            'secret' => $weChatApp->G_app_secret,
            'response_type' => 'array',
        ];\Log::info('2224');
        $app = Factory::officialAccount($config);
        $text = new Text('111');//dd($text);
        $res_msg = $app->customer_service->message($text)->to('o_O0HuA4ugJG0npjLSL_Cd33FN8c')->send();dd($res_msg);*/
        //\Tinify\setKey('8NTpkbbHjKxSDxhWqNftM1cPDcQTs3CD');
        //$source = \Tinify\fromUrl("https://tinypng.com/images/panda-happy.png");
        //$source->toFile(public_path() . '/base/poster/download/111.png');

        echo 111;
    }

    /**
     * @param $storeid
     * @param $open_id
     * @param $action 1 收藏  2查看类目 3查看商品 4登陆 5点击图片 6 点击导航 7一键拨号
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    private function sendLogsMessage($storeid,$open_id,$action,$name,$g_open_id)
    {
        $user = AlbumUserModel::where('open_id',$open_id)->first();
        $formId = AlbumFormId::where([['open_id',$open_id]])->first();
        $content = '';
        switch ($action){
            case 1:
                $content = '收藏了您的产品';
                break;
            case 2;
                $content = '查看了您的产品列表';
                break;
            case 3;
                $content = '查看了您的商品';
                break;
            case 4;
                $content = '进入了您的画册';
                break;
            case 5;
                $content = '点击了您的某款产品详情';
                break;
            case 6;
                $content = '点击了导航到您的位置';
                break;
            case 7;
                $content = '点击了您的号码';
                break;
            case 8;
                $content = '分享了您的画册';
                break;
        }
        $weChatApp = AlbumManufacturerModel::where('store_id', $storeid)->first();\Log::info($weChatApp);

        $res_account = $this->accountMesage($open_id,$weChatApp,$name,$content);
        \Log::info($weChatApp->wxFurniture_template_id);
        \Log::info($res_account);
        if ($user && $formId && !empty($weChatApp->wxFurniture_template_id) && $res_account['errcode']!=0) {
            $config_app = [
                'app_id' => $weChatApp->app_id,
                'secret' => $weChatApp->app_secret,
                'response_type' => 'array',
            ];
            $app_x = Factory::miniProgram($config_app);
            $res = $app_x->template_message->send([
                'touser' => $open_id,
                'template_id' => $weChatApp->wxFurniture_template_id,
                'page' => 'pages/sell/sell',
                'form_id' => $formId->form_id,
                'data' => [
                    'keyword1' => $name,
                    'keyword2' => $content,
                    'keyword3' => date('Y-m-d H:i'),
                ],
            ]);
            \Log::info($res);
            //  dd($res);
            if($res){
                $formId->delete();
            }
        }

    }

    /**
     * send account message
     *
     * @param $g_open_id string
     * @param $weChatApp object
     * @param $name string
     * @param $content string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     *
     * @return array|string
     */
    private function accountMesage($open_id,$weChatApp,$name,$content)
    {
        // Cache::flush();
        $value = Cache::get($open_id);
        \Log::info($value);\Log::info('2225');
        if ($open_id && !empty($weChatApp->wxaccount_template_id) && (!$value || ($value + 60) <= time())) {
            Cache::put($open_id, time(), 1);
          /*  $config = [
                'app_id' => $weChatApp->G_app_id,
                'secret' => $weChatApp->G_app_secret,
                'response_type' => 'array',
            ];*/

            $ac = $this->getAccessToken($weChatApp);
            $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=" . $ac;
            $date = date("Y-m-d H:i");
            $page = "pages/sell/sell";
            $data = array( "touser" => $open_id,
                "mp_template_msg" => array(
                    "appid" => $weChatApp->G_app_id,
                    "url" => "http://weixin.qq.com/download",
                    "template_id" => $weChatApp->wxaccount_template_id,
                    "miniprogram" => array(
                        "appid" => $weChatApp->xyx_id,
                        "pagepath" => $page
                    ),
                    "data" => array(
                        "first" => array( "value" => "您有未读消息！", "color" => "#c27ba0" ),
                        "keyword1" => array( "value" => $name, "color" => "#93c47d" ),
                        "keyword2" => array( "value" => $date, "color" => "#0000ff" ),
                        "remark" => array( "value" => $content, "color" => "#0000ff" ),
                      //  "remark" => array( "value" => $date, "color" => "#45818e" )
                    )
                )
            );
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
            $res = $this->curlPost($url, $data);
            $res = json_decode($res, true);
           /* $app = Factory::officialAccount($config);
            $res = $app->template_message->send([
                'touser' => $g_open_id,
                'template_id' => $weChatApp->wxaccount_template_id,
                'url' => '',
                'data' => [
                    'keyword1' => $name,
                    'keyword2' => $content,
                    'keyword3' => date('Y-m-d H:i'),
                ],
                'miniprogram' => [
                    'appid' => $weChatApp->app_id,
                    'pagepath' => 'pages/sell/sell'
                ],
            ]);*/
            return $res;
        } else {
            return false;
        }

    }
    protected function curlPost($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function getAccessToken($app)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $app->xyx_id . "&secret=" . $app->xyx_secret;
        $data = $this->curlGet($url);
        $data = json_decode($data, true);
        if( !isset($data["access_token"]) )
        {
            \Log::info($data);
            return false;
        }

        $access_token = $data["access_token"];
        return $access_token;
    }


    /**
     * @api {get} /api/album/add_agent 申请经销商(add_agent)
     * @apiDescription 申请经销商(add_agent)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiParam {int}    [realname]  姓名
     * @apiParam {int}    [address]  地址
     * @apiParam {double}    [lat]  lat
     * @apiParam {double}    [lon]  lon
     * @apiParam {int}    [phone]  电话
     * @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
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */

    public function albumAddAgent(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'realname' => 'required',
            'address' => 'required',
            'phone' => 'required',
            'store_id' => 'required',
        ],[
            'address.required'=>'缺少地址参数',
            'realname.required'=>'缺少信息参数',
            'phone.required'=>'缺少电话参数',
            'store_id.required'=>'缺少商户参数',
        ]);

        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $data = $request->input();
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?address=".$data['address']."&key=".env('QQMAP');
        $local = $this->curlGet($url);
        $res = json_decode($local,true);
        $agent_check = AlbumAgentModel::where([['store_id',$data['store_id']],['user_id',$userAuth->id]])->withTrashed()->first();
        //dd($agent_check);
        if($agent_check){
            if($agent_check->status==0 && $agent_check->deleted_at == null) return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '该用户已提交申请！');
            $agent_check->phone = $data['phone'];
            $agent_check->address = $data['address'];
            if ($agent_check->deleted_at != null) {
                $agent_check->deleted_at = null;
                $agent_check->status = 0;
            }
            $agent_check->lon = $res['result']['location']['lng'];
            $agent_check->lat = $res['result']['location']['lat'];
            $agent_check->realname = $data['realname'];
            if($agent_check->save()) return $this->api([
                'code' =>0,
                'msg' =>'success',
            ]);
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '保存失败！');
        }
        $data['status'] = 0;
        $data['user_id'] = $userAuth->id;
        $data['lon'] = $res['result']['location']['lng'];
        $data['lat'] = $res['result']['location']['lat'];
        $data['name'] = $userAuth->username;
        $res = AlbumAgentModel::create($data);
        if($res){
            $d = [
                'code' =>0,
                'msg' =>'success',
            ];
        }else{
            $d = [
                'code' =>1,
                'msg' =>'error',
            ];
        }
        return $this->api($d);
    }

    /**
     * @api {get} /api/album/get-agent-address 获取经销商地址(get-agent-address)
     * @apiDescription 获取经销商地址(get-agent-address)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data":[
     *          "realname":
     *          "phone":
     *          "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 albumGetAgentAdress(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
        ],[
            'store_id.required'=>'缺少商户参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $data = $request->input();
        if($userAuth->is_dealer == 1){
            $user_agent = AlbumAgentModel::where([['store_id',$data['store_id']],['user_id',$userAuth->id]])->first(['address','phone','realname']);
        }else{
            $user_agent = null;
        }

        return $this->api(compact('user_agent'));
    }

    /**
     * @api {get} /api/album/get-banner 获取banner和視頻(get-banner)
     * @apiDescription 获取banner和視頻(get-banner)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data":[
     *          "video":{
     *              'url':22222,
     *              'name':22222,
     *              'type':22222,
     *              'agent_id':22222,
     *              }
     *          "banner":{
     *              'url':22222,
     *              'name':22222,
     *              'type':22222,
     *              'agent_id':22222,
     *              },
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */

    public function albumGetBanner(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
        ],[
            'store_id.required'=>'缺少商户参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $store_id = $request->input('store_id');


        $banner = AgentBannerModel::where([['store_id',$store_id],['type',0]])->get();
        $video = AgentBannerModel::where([['store_id',$store_id],['type',1]])->first();
        return $this->api(compact('banner','video'));
    }


    /**
     * @api {get} /api/album/get-customer 获取客户信息(get-customer)
     * @apiDescription 获取客户信息(get-customer)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiParam {string}    [openid_id]  open_id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data":[
     *          "purpose_level":
     *          "comment":
     *          "address":
     *          "phone":
     *          "tips":
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumGetCustomer(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'open_id'=>'required'
        ],[
            'store_id.required'=>'缺少商户参数',
            'open_id.required'=>'缺少用户参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $store_id = $request->input('store_id');
        $open_id = $request->input('open_id');

        if($userAuth->is_dealer!=1) return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '该用户不是经销商!', $validator->messages());
        $user_agent = AlbumAgentModel::where('user_id',$userAuth->id)->first();
        $customer = CustomerDetailsModel::where([['store_id',$store_id],['open_id',$open_id],['agent_id',$user_agent->id]])->first(['purpose_level','comment','tips','address']);
        if(!empty($customer)){
            $user = AlbumUserModel::where([['store_id',$store_id],['open_id',$open_id]])->first();
            $customer->phone = $user->phone;
            $customer->avatar = $user->avatar;
            $customer->username = $user->username;
        } else {
            $customer = (object)[
                'purpose_level' => 1,
                'comment'       => '备注名',
                'tips'          => '客户有合作意向',
                'address'       => '四川省成都市'
            ];
        }
        return $this->api(compact('customer'));
    }


    /**
     * @api {post} /api/album/set-customer 设置客户信息(set-customer)
     * @apiDescription 设置客户信息(set-customer)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiParam {string}    [openid_id]  openid
     * @apiParam {string}    [key]  键
     * @apiParam {string}    [value]  值
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data":[
     *          "purpose_level":
     *          "address":
     *          "comment":
     *          "phone":
     *          "tips":
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumSetCustomer(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'key' => 'required',
            'value' => 'required',
            'open_id' => 'required',
        ],[
            'store_id.required'=>'缺少商户参数',
            'key.required'=>'缺少键参数',
            'value.required'=>'缺少值参数',
            'open_id.required'=>'缺少用户参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $store_id = $request->input('store_id');
        $open_id = $request->input('open_id');
        $key = $request->input('key');
        $value = $request->input('value');
        if($userAuth->is_dealer != 1) return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '该用户不是经销商!', $validator->messages());
        $user_agent = AlbumAgentModel::where('user_id',$userAuth->id)->first();
        if ($key == 'phone') {
            $user = AlbumUserModel::where([['store_id',$store_id],['open_id',$open_id]])->first();
            $user->phone = $value;
            $user->save();
            return $this->api([], 0, 'success');
        }
        $customer = CustomerDetailsModel::where([['store_id',$store_id],['open_id',$open_id],['agent_id',$user_agent->id]])->first(['purpose_level','comment','tips','address']);
        if($customer){
            /// $customer->$key = $value;
            $update[$key] = $value;
            CustomerDetailsModel::where([['store_id',$store_id],['open_id',$open_id],['agent_id',$user_agent->id]])->update($update);
            //  $customer->save();
        }else{
            $add['agent_id'] = $user_agent->id;
            $add['open_id'] = $open_id;
            $add['store_id'] = $store_id;
            $add[$key] = $value;
            $user = CustomerDetailsModel::create($add);
        }
        return $this->api([],0,'success');
    }


    /**
     * @api {get} /api/album/customer-goods 获取客户浏览商品统计(customer-goods)
     * @apiDescription 获取客户浏览商品统计(customer-goods)
     * @apiGroup Album
     * @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":[
     *          {
     *              "name":
     *              "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 albumCustomerGoods(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'open_id' => 'required',
//            'end' => 'required',
//            'start' => 'required',
        ],[
            'store_id.required'=>'缺少商户参数',
            'open_id.required'=>'缺少用户参数',
//            'end.required'=>'缺少结束时间参数',
//            'start.required'=>'缺少开始时间参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $store_id = $request->input('store_id');
        $open_id = $request->input('open_id');
        $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);
        if($userAuth->is_dealer!=1) return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '该用户不是经销商!', $validator->messages());
        $user_agent = AlbumAgentModel::where('user_id',$userAuth->id)->first();
        if($user_agent) $res=  AlbumWatchRecord::where([['action',3],['store_id',$store_id],['agent_id',$user_agent->id],['open_id',$open_id],['updated_at','>=',$start],['updated_at','<=',$end]])->groupBy('detail')->get(['detail']);
        $arr = array();
        foreach ($res as $key=>$val){
            $detail = json_decode($val['detail'],true);
            //dd($detail);die;
            $goods_id = $detail['goods_id'];
            $goods = AlbumProductModel::where([['id',$goods_id]])->first();
            if($goods){
                $count=  AlbumWatchRecord::where([['action',3],['store_id',$store_id],['detail',$val['detail']],['agent_id',$user_agent->id],['open_id',$open_id]])->count();

                $arr[] = ['name'=>$goods->name,'count'=>$count];
            }
        }
        return $this->api($arr,0,'success');
    }

    /**
     * @api {post} /api/album/customer-goods-detail 获取客户浏览商品详细(customer-goods-detail)
     * @apiDescription 获取客户浏览商品详细(customer-goods-detail)
     * @apiGroup Album
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiParam {string}    [open_id]  openid
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data":[
     *          {
     *              "name":
     *              "time":
     *              "style":
     *              "cat":
     *          },
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumCustomerGoodsDetail(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'open_id' => 'required',
//            'end' => 'required',
//            'start' => 'required',
        ],[
            'store_id.required' => '缺少商户参数',
            'open_id.required' => '缺少用户参数',
//            'end.required'=>'缺少结束时间参数',
//            'start.required'=>'缺少开始时间参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $store_id = $request->input('store_id');
        $open_id = $request->input('open_id');
        $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);
        if ($userAuth->is_dealer!=1) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '该用户不是经销商!', $validator->messages());
        }
        $user_agent = AlbumAgentModel::where('user_id',$userAuth->id)->first();

        $res =  AlbumWatchRecord::where([['action',3],['store_id',$store_id],['open_id',$open_id],['agent_id',$user_agent->id],['updated_at','>=',$start],['updated_at','<=',$end]])->orderByDesc('id')->get(['detail','created_at'])->toArray();
        if (!$res) {
            return $this->api([],0,'success');
        }
        $arr = array();
        foreach ($res as $key => $val) {
            $detail = json_decode($val['detail'], true);
            //dd($detail);die;
            $goods_id = $detail['goods_id'];
            $goods = AlbumProductModel::where([['id', $goods_id]])->first();
            if($goods){
                $cat = AlbumCatModel::where([['store_id', $store_id],['id', $goods->cat_id]])->first();

                if (!$cat) {
                    continue;
                }

                if (isset($arr[date('Y-m-d H:i', strtotime($val['created_at']))])) {
                    if (isset($arr[date('Y-m-d H:i', strtotime($val['created_at']))][$goods->id])) {
                        $arr[date('Y-m-d H:i', strtotime($val['created_at']))][$goods->id]['times']++;
                    } else {
                        $arr[date('Y-m-d H:i', strtotime($val['created_at']))][$goods->id] = [
                            'name' => $goods->name,
                            'cat' => $cat->name,
                            'thumb' => $goods->thumb,
                            'time' => date('Y-m-d H:i', strtotime($val['created_at'])),
                            'times' => 1
                        ];
                    }
                } else {
                    $arr[date('Y-m-d H:i', strtotime($val['created_at']))][$goods->id] = [
                        'name' => $goods->name,
                        'cat' => $cat->name,
                        'thumb' => $goods->thumb,
                        'time' => date('Y-m-d H:i', strtotime($val['created_at'])),
                        'times' => 1
                    ];
                }

            }

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

    /**
     * @api {post} /api/album/get-count-favorite 获取客户收藏商品详细(get-count-favorite)
     * @apiDescription 获取客户收藏商品详细(get-count-favorite)
     * @apiGroup Album
     * @apiPermission AUTH
     * @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":[
     *          {
     *              "name":
     *              "count":
     *              "product_id":
     *          },
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumGetCountOfFavorite(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
        ],[
            'store_id.required'=>'缺少商户参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $store_id = $request->input('store_id');
        if($userAuth->is_dealer!=1) return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '该用户不是经销商!', $validator->messages());
        $user_agent = AlbumAgentModel::where('user_id',$userAuth->id)->first();
        $count_user = AlbumWatchRecord::where([['agent_id',$user_agent->id],['store_id',$store_id]])->orderBy('id','DESC')->groupBy('open_id')->get();

        $users = Array();
        if($count_user){
            foreach($count_user as $key=>$val){
                $user = AlbumUserModel::where([['open_id',$val->open_id],['store_id',$val->store_id]])->select(['id','username','avatar','phone','open_id'])->first();
                $users[] = $user->id;
            }
        }
        $res = AlbumFavoriteModel::whereIn('user_id',$users)->where([['store_id',$store_id]])->groupBy('product_id')->get(['product_id'])->toArray();
        foreach($res as $key=>$val){
            $goods = AlbumProductModel::where([['id',$val['product_id']],['store_id',$store_id]])->first();
            if(!$goods){
                unset($res[$key]);continue;
            }

            $res[$key]['name'] = $goods->name;
            // dd($res);
            $res[$key]['count'] = AlbumFavoriteModel::whereIn('user_id',$users)->where([['store_id',$store_id],['product_id',$val['product_id']]])->count();
        }
        return $this->api($res,0,'success');
    }

    /**
     * @api {get} /api/album/get-user-info 获取客户详细(get-user-info)
     * @apiDescription 获取客户详细(get-user-info)
     * @apiGroup Album
     * @apiPermission AUTH
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data":[
     *          {
     *              "username":
     *              "is_dealer":
     *              ...
     *          },
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumGetUserInfo(Request $request)
    {
        $userAuth = Auth('api')->user();

        if($userAuth->is_dealer == 1){
            $user_agent = AlbumAgentModel::where([['user_id',$userAuth->id],['status',1]])->first();
            $agent_id = $user_agent['id'];
        } else {
            $agent_id = '';
        }
        $user['is_agent'] = $userAuth->is_dealer;
        $user['agent_id'] = $agent_id;
        return $this->api($user,0,'success');
    }


    /**
     * @api {post} /api/album/statistical 记录分享次数(statistical)
     * @apiDescription 记录分享次数(statistical)
     * @apiGroup Album
     * @apiPermission AUTH
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiParam {int}    [goods_id]  商品id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "success",
     *     "data":[]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumStatistical(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
        ],[
            'store_id.required'=>'缺少商户参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $store_id = $request->input('store_id');
        $goods_id = $request->input('goods_id');
        if($userAuth->up_agent_id !=0){
            $user_agent = AlbumAgentModel::where([['id',$userAuth->up_agent_id],['status',1]])->first();
            $user_agent->share_times++;
            $user_agent->interactive++;
            $user_agent->newCount = $user_agent->pointCount + $user_agent->favoriteCount + $user_agent->callCount + $user_agent->share_times + $user_agent->get_count;
            $user_agent->save();
        }

        $time = mktime(0,0,0,date('m'),date('d'),date('y'));
        $check = AlbumStatisticalModel::where([['time',$time],['store_id',$store_id]])->first();
        if($check){
            $check->share_times ++;
            $check->save();
        }else{
            $add['time'] = $time;
            $add['store_id'] = $store_id;
            $add['share_times'] = 1;
            $add['favorite_times'] = 0;
            AlbumStatisticalModel::create($add);
        }
        if($userAuth->up_agent_id!=0 && !empty($goods_id)){
            $add_record['agent_id'] = $userAuth->up_agent_id;
            $add_record['open_id'] = $userAuth->open_id;
            $add_record['action'] = 8;
            $add_record['store_id'] = $store_id;
            $add_record['detail'] = $goods_id;
            $res = AlbumWatchRecord::create($add_record);
        }
        return $this->api([],0,'success');
    }


    /**
     * @api {post} /api/album/get_statistical 获取分享记录(get-statistical)
     * @apiDescription 获取分享记录(get-statistical)
     * @apiGroup Album
     * @apiPermission AUTH
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiParam {int}    [open_id]  open_id
     * @apiParam {int}    [type]  1 尺寸统计 2拨打电话 3 分享
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "success",
     *     "data":[
     *          {
     *             'content':xxxxx,
     *             'time':xxx-xx-xx,
     *          },
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumGetStatistical(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'open_id' => 'required',
            'type' => 'required',
//            'end' => 'required',
//            'start' => 'required',
        ],[
            'store_id.required'=>'缺少商户参数',
            'open_id.required'=>'缺少用户参数',
            'type.required'=>'缺少类型参数',
//            'end.required'=>'缺少结束时间参数',
//            'start.required'=>'缺少开始时间参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $data = $request->input();
        $res = array();
        $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);
        if($userAuth->is_dealer!=1) return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '该用户不是经销商!', $validator->messages());
        $user_agent = AlbumAgentModel::where('user_id',$userAuth->id)->first();
        $user = AlbumUserModel::where([['open_id',$data['open_id']],['store_id',$data['store_id']]])->first();
        if ($data['type'] == 1) {    //尺寸统计
            $record = AlbumWatchRecord::where([['open_id',$data['open_id']],['agent_id',$user_agent->id],['detail','like','%'.'u5c3a'.'%'],['action',5],['store_id',$data['store_id']],['updated_at','>=',$start],['updated_at','<=',$end]])->get();
            foreach ($record as $key=>$val){
                $detail = json_decode($val['detail'],true);
                $goods = AlbumProductModel::where([['store_id',$data['store_id']],['id',$detail['goods_id']]])->first();
                if (!$goods) {
                    continue;
                }
                $res[] = [
                    'content' => $user->username . '点击' . $goods->name . $detail['detail'],
                    'time' => date('Y-m-d H:i',strtotime($val['created_at']))
                ];
            }
        } elseif ($data['type'] == 2) {   //拨打电话
            $record = AlbumWatchRecord::where([['open_id',$data['open_id']],['agent_id',$user_agent->id],['action',7],['store_id',$data['store_id']],['updated_at','>=',$start],['updated_at','<=',$end]])->get();
            foreach ($record as $key=>$val){
                $res[] = [
                    'content' => $user->username . '拨打了经销商电话',
                    'time' => date('Y-m-d H:i',strtotime($val['created_at']))
                ];
            }
        } else {
            $record = AlbumWatchRecord::where([['open_id',$data['open_id']],['agent_id',$user_agent->id],['action',8],['store_id',$data['store_id']],['updated_at','>=',$start],['updated_at','<=',$end]])->get();
            foreach ($record as $key=>$val){
                $goods = AlbumProductModel::where([['store_id',$data['store_id']],['id',$val['detail']]])->first();
                $style = AlbumProductStyleModel::where([['store_id',$data['store_id']],['id',$goods->style]])->first();
                $cat = AlbumCatModel::where([['store_id',$data['store_id']],['id',$goods->cat_id]])->first();
                $res[] = [
                    'content' => "$user->username 分享了 $style->name $cat->name $goods->name ",
                    'time' => date('Y-m-d H:i',strtotime($val['created_at']))
                ];
            }
        }
        return $this->api(compact('res'));
    }


    /**
     * @api {post} /api/album/agent_price_set 厂家价格设置(agent_price_set)
     * @apiDescription 厂家价格设置(agent_price_set)
     * @apiGroup Album
     * @apiPermission AUTH
     * @apiVersion 0.1.0
     * @apiParam {int}    [store_id]  商户id
     * @apiParam {int}    [point]  价格设置比例 为0不设置
     * @apiParam {int}    [is_show_ma_price]  厂家价格是否可见 0 不可见 1 可见
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "success",
     *     "data":[]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function albumAgentPriceSet(Request $request)
    {
        $userAuth = Auth('api')->user();

        $validator = Validator::make($request->all(), [
            'is_show_ma_price' => 'required',
            'store_id' => 'required',
            'point' => 'required',
        ],[
            'is_show_ma_price.required'=>'缺少设置参数',
            'store_id.required' => '缺少store参数',
            'point.required'=>'缺少比例参数',
        ]);
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $data = $request->input();
        if($userAuth->is_dealer!=1) return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '该用户不是经销商!', $validator->messages());
        $user_agent = AlbumAgentModel::where('user_id',$userAuth->id)->first();
        $user_agent->is_show_ma_price = $data['is_show_ma_price'];
        $user_agent->save();


        $product = AlbumProductModel::where('store_id',$data['store_id'])->get(['id','cat_id','name','ma_price']);
        foreach ($product as $key=>$val) {
            $save['price'] = $val['ma_price'] * (1 + $data['point'] / 100);
            $check = AlbumProductPriceModel::where([['agent_id',$user_agent->id],['store_id',$data['store_id']],['product_id',$val['id']]])->first();
            if(empty($check)){
                $save['agent_id'] = $user_agent->id;
                $save['store_id'] = $data['store_id'];
                $save['cat_id'] = $val['cat_id'];
                $save['name'] = $val['name'];
                $save['product_id'] = $val['id'];
                AlbumProductPriceModel::create($save);
            }else{
                AlbumProductPriceModel::where([['agent_id',$user_agent->id],['store_id',$data['store_id']],['product_id',$val['id']]])->update($save);
            }
        }
        $user_agent->set_price_point = $data['point'];
        $user_agent->save();

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