<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\AlbumBannerModel;
use App\Models\AlbumCommentsModel;
use App\Models\AlbumManufacturerModel;
use App\Models\AlbumNavModel;
use App\Models\AlbumNewsModel;
use App\Models\AlbumOrderModel;
use App\Models\AlbumPartsModel;
use App\Models\AlbumProductAttrModel;
use App\Models\AlbumProgressModel;
use App\Models\AlbumReviewModel;
use App\Models\AlbumUserModel;
use App\Models\FurnitureFormidModel;
use App\Models\FurnitureGoodsModel;
use App\Models\FurnitureNewgoodsBookingModel;
use App\Models\FurnitureNewgoodsCommentModel;
use App\Models\FurnitureNewgoodsInfoModel;
use App\Models\UserInfoModel;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use MGQrCodeReader\MGQrCodeReader;
use Validator, Auth, Image;
use App\Services\Base\ErrorCode;
use EasyWeChat\Factory;
use Zxing\Qrcode\QRCodeReader;
use ZBarCodeImage, ZBarCodeScanner;


class FurnitureController extends Controller
{
    protected $app;
    private $wechat_app;


    /**
     * @api {post} /api/furniture/setting 首页基本设置
     * @apiDescription   首页基本设置
     * @apiGroup Furniture
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}     store_id             店铺ID
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *      "status_code": 0,
     *      "message": "",
     *      "data": {
     *          "setting": {
     *                  "name": "某某厂家",
     *                  "goods_app_id": "afdasfa",               //商品要跳转的appid
     *                  "goods_app_path": "page/goods/goods",               //商品要跳转的url
     *                  "illustrated_name": "在线画册",
     *                  "avatar": "http://s1.xcx.com/upload/s1test/20180716/bb123f13bf8a42f0a86b55e7bf861400.png",
     *                  "notice": "这是一条公告测试！",
     *                  "advertising_pic": ""
     *          },
     *          "banner": [                //轮播图
     * ...
     *              {
     *                  "id": 4,
     *                  "store_id": 1,
     *                  "pic_url": "https://u3.9026.com/upload/temp_pic/20171013/da1d53cd93bfa4c8ed34939314ca18fb.jpg",
     *                  "title": "轮播图测试",
     *                  "page_url": "news/news",
     *                  "sort": 87,
     *              }
     * ...
     *           ],
     *          "navbar": [               //底部导航栏
     * ...
     *              {
     *                  "id": 9,
     *                  "store_id": 1,
     *                  "name": "联系我们",
     *                  "url": "/pages/index/index",
     *                  "open_type": "1",
     *                  "pic_url": "http://s1.xcx.com/upload/agent_show/20180702/7e638f0ca464f8096fba8a658b49d556.png",
     *                  "sort": 100,
     *                  "created_at": "2018-07-16 16:05:29",
     *                  "updated_at": "2018-07-20 18:08:37",
     *                  "deleted_at": null,
     *                  "mobile": "13407570861",
     *                  "address": null,
     *                  "app_id": null,
     *                  "state": 0,
     *                  "lon": null,
     *                  "lat": null
     *              }
     * ...
     *          ],
     * "menus": [               //顶部导航栏
     * ...
     *              {
     *                  "id": 9,
     *                  "store_id": 1,
     *                  "name": "联系我们",
     *                  "url": "/pages/index/index",
     *                  "open_type": "1",
     *                  "pic_url": "http://s1.xcx.com/upload/agent_show/20180702/7e638f0ca464f8096fba8a658b49d556.png",
     *                  "sort": 100,
     *                  "created_at": "2018-07-16 16:05:29",
     *                  "updated_at": "2018-07-20 18:08:37",
     *                  "deleted_at": null,
     *                  "mobile": "13407570861",
     *                  "address": null,
     *                  "app_id": null,
     *                  "state": 1,
     *                  "lon": null,
     *                  "lat": null
     *              }
     * ...
     *          ]
     *
     *      }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function furnitureSetting(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(['name', 'goods_app_id', 'goods_app_path', 'illustrated_name', 'avatar', 'notice', 'advertising_pic']);
        //轮播图
        $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();

        $conf = AlbumManufacturerModel::where('store_id',$store_id)->first();
        $getPhone = $conf->getPhone;
        $getFocus = $conf->getFocus;
        return $this->api(compact('setting', 'banner', 'navbar', 'menus','getFocus'));
    }


    /**
     * @api {get} /api/furniture/news_detail 获取新闻详情
     * @apiDescription 获取新闻详情(news_detail)
     * @apiGroup Furniture
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    store_id  商户id
     * @apiParam {int}    newsid  新闻id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         news": {
     *              "id": 5,
     *              "store_id": 2,
     *              "title": "测试时",
     *              "thumb": null,
     *              "content": "<p>啊师傅阿凡达</p>",
     *              "bad": 0,                                  //淘汰
     *              "commonly": 0,                             //一般
     *              "like": 0,                                 //喜欢
     *              "viewed": 0,                               //浏览次数
     *              "sort": 87,
     *              "created_at": "2018-05-28 09:33:01",
     *              "updated_at": "2018-05-28 09:33:01",
     *              "avatar": "https://u3.9026.com/upload/common/20171013/137d21eb6dbaca67475c8ca27640dcfc.png"
     *              },
     *      "news_comments": {
     *          "current_page": 1,
     *          "data": [
     *               {
     *                  "id": 13,
     *                  "store_id": 2,
     *                  "user_id": 6,
     *                  "comments_id": 0,                              //被评论id 0：表示对新闻评论
     *                  "content": "adff",
     *                  "created_at": "2018-06-14 15:49:38",
     *                  "updated_at": "2018-06-14 15:49:38",
     *                  "news_id": 5,                                   //新闻id
     *                  "deleted_at": null,
     *                  "sys_reply": "",
     *                  "username": "Wesley",
     *                  "avatar": "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLnEDDuGRN9Dl7icBbph1JRvmQ7x2D4tiaGGVHApGAu9FCy9yb1bOcboIctAjRsyic4Ucn3z7K3QCUyg/132",
     *                  "replys": {
     *                      "current_page": 1,
     *                      "data": [],
     *                      "first_page_url": "http://localhost:8082/api/furniture/news_detail?page=1",
     *                      "from": null,
     *                      "last_page": 1,
     *                      "last_page_url": "http://localhost:8082/api/furniture/news_detail?page=1",
     *                      "next_page_url": null,
     *                      "path": "http://localhost:8082/api/furniture/news_detail",
     *                      "per_page": 5,
     *                      "prev_page_url": null,
     *                      "to": null,
     *                      "total": 0
     * }
     * }
     * ],
     * "first_page_url": "http://localhost:8082/api/furniture/news_detail?page=1",
     * "from": 1,
     * "last_page": 1,
     * "last_page_url": "http://localhost:8082/api/furniture/news_detail?page=1",
     * "next_page_url": null,
     * "path": "http://localhost:8082/api/furniture/news_detail",
     * "per_page": 5,
     * "prev_page_url": null,
     * "to": 1,
     * "total": 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 furnitureNewsDetail(Request $request)
    {
        $news_id = request('newsid');
        $news = AlbumNewsModel::find($news_id);
        $news->viewed += 1;
        $news->save();
        $news->avatar = AlbumManufacturerModel::where('store_id', $request->get('store_id'))->first()->avatar;
        $news_comments = AlbumCommentsModel::where('news_id', $news_id)
            ->where('comments_id', 0)
            ->orderByDesc('created_at')
            ->paginate(5);

        foreach ($news_comments as $item) {
            $user = AlbumUserModel::find($item->user_id);
            $item->username = $user->username;
            $item->avatar = $user->avatar;
            $item->replys = AlbumCommentsModel::find($item->id)->replys()->paginate(5);
            foreach ($item->replys as $i) {
                $iuser = AlbumUserModel::find($i->user_id);
                $i->username = $iuser->username;
                $i->avatar = $iuser->avatar;
            }
        }
        return $this->api(compact('news', 'news_comments'));
    }


    /**
     * @api {get} /api/furniture/news_list 获取新闻列表
     * @apiDescription 获取新闻列表(news_list)
     * @apiGroup Furniture
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    store_id  商户id 模拟值为1
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "current_page": 1,                     //当前页
     *          "data": [
     * ...
     *              {
     *                  "id": 1,
     *                  "store_id": 1,
     *                  "title": "123123",
     *                  "thumb": "http://s1.xcx.com/upload/agent_pic/20180702/19b0e148f1c9f2b6c3667c81bb06a687.jpg",
     *                  "content": "<p>1232123123123</p>",
     *                  "bad": 0,
     *                  "commonly": 0,
     *                  "like": 0,
     *                  "viewed": 133,
     *                  "sort": 127,
     *                  "created_at": "2018-05-24 15:21:42",
     *                  "updated_at": "2018-07-20 16:58:48"
     *                  },
     *...
     *          ],
     *      "first_page_url": "http://s1.xcx.com/api/furniture/news_list?page=1",       //首页url
     *      "from": 1,
     *      "last_page": 1,
     *      "last_page_url": "http://s1.xcx.com/api/furniture/news_list?page=1",        //尾页url
     *      "next_page_url": null,                                                      //下一页url
     *      "path": "http://s1.xcx.com/api/furniture/news_list",
     *      "per_page": 5,
     *      "prev_page_url": null,                                                     //上一页url
     *      "to": 3,
     *      "total": 3
     *
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function furnitureNewsList(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;
        $news = AlbumNewsModel::where('store_id', $store_id)->orderByDesc('sort')->paginate(5);

        return $this->api($news);
    }

    /**
     * @api {get} /api/furniture/add_comments 添加新闻评论
     * @apiDescription 添加新闻评论(news_list)
     * @apiGroup Furniture
     * @apiPermission Passport
     * @apiVersion 0.1.0
     * @apiParam {int}    store_id   商户ID
     * @apiParam {int}    news_id    新闻ID
     * @apiParam {int}    content    评论内容
     * @apiParam {int}    comments_id  被回复的评论ID。对新闻评论：0;  对评论回复：被回复的评论的具体ID
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "res": []//结果
     *
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     *    401                                     token已过期，请重新登录
     */
    public function furnitureAddComments(Request $request)
    {
        $user = Auth('api')->user();
        if (!$user) {
            $data = [
                'code' => 401,
                'msg' => 'token已过期，请重新登录'
            ];
            return $this->api($data);
        }
        $data = $request->all();
        if ($data['content']) {
            $data['user_id'] = $user->id;
            $res = AlbumCommentsModel::create($data);
            $res = ['state' => true, "code" => "200", "message" => "评论成功", "data" => $res];

        } else {
            $res = ['state' => false, "code" => "1000", "message" => "传入参数不正确", "data" => null];

        }

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

    /**
     * @api {get} /api/furniture/addtolike 新闻点赞
     * @apiDescription 新闻点赞
     * @apiGroup Furniture
     * @apiPermission None
     * @apiVersion 0.1.0
     * @apiParam {int}    store_id   商户ID
     * @apiParam {int}    news_id    新闻ID
     * @apiParam {int}   [like]      喜欢 （参数：1）
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "res": []//结果
     *
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function addToLike(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'newsid' => 'required',
        ], [
            'store_id.required' => '店铺信息未知',
            'newsid.required' => '评论id未知',
        ]);

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }

        $news_id = request('newsid');
        $news = AlbumNewsModel::find($news_id);
        if (request('like') == 1) {
            $news->like += 1;
        }
        $news->save();
        $data = [
            'state' => 'true',
            'code' => 200,
            'msg' => '请求成功'
        ];
        return $this->api($data);

    }

    /**
     * @api {get} /api/furniture/getmorecomments 获取全部评论/回复
     * @apiDescription 获取全部评论/回复(getmorecomments)
     * @apiGroup Furniture
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    store_id  商户id
     * @apiParam {int}    id  评论/回复 id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         comments": {
     *                  "id": 13,
     *                  "store_id": 2,
     *                  "user_id": 6,
     *                  "comments_id": 0,                              //被评论id 0：表示对新闻评论
     *                  "content": "adff",
     *                  "created_at": "2018-06-14 15:49:38",
     *                  "updated_at": "2018-06-14 15:49:38",
     *                  "news_id": 5,                                   //新闻id
     *                  "deleted_at": null,
     *                  "sys_reply": "",
     *                  "username": "Wesley",
     *                  "avatar": "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLnEDDuGRN9Dl7icBbph1JRvmQ7x2D4tiaGGVHApGAu9FCy9yb1bOcboIctAjRsyic4Ucn3z7K3QCUyg/132",
     *              },
     *      "comments_replys": {
     *          "current_page": 1,
     *          "data": [
     *               {
     *                  "id": 13,
     *                  "store_id": 2,
     *                  "user_id": 6,
     *                  "comments_id": 13,                              //被评论id 0：表示对新闻评论
     *                  "content": "adff",
     *                  "created_at": "2018-06-14 15:49:38",
     *                  "updated_at": "2018-06-14 15:49:38",
     *                  "news_id": 5,                                   //新闻id
     *                  "deleted_at": null,
     *                  "sys_reply": "",
     *                  "username": "Wesley",
     *                  "avatar": "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLnEDDuGRN9Dl7icBbph1JRvmQ7x2D4tiaGGVHApGAu9FCy9yb1bOcboIctAjRsyic4Ucn3z7K3QCUyg/132",
     *                  "replys": {
     *                      "current_page": 1,
     *                      "data": [],
     *                      "first_page_url": "http://localhost:8082/api/furniture/news_detail?page=1",
     *                      "from": null,
     *                      "last_page": 1,
     *                      "last_page_url": "http://localhost:8082/api/furniture/news_detail?page=1",
     *                      "next_page_url": null,
     *                      "path": "http://localhost:8082/api/furniture/news_detail",
     *                      "per_page": 5,
     *                      "prev_page_url": null,
     *                      "to": null,
     *                      "total": 0
     * }
     * }
     * ],
     * "first_page_url": "http://localhost:8082/api/furniture/news_detail?page=1",
     * "from": 1,
     * "last_page": 1,
     * "last_page_url": "http://localhost:8082/api/furniture/news_detail?page=1",
     * "next_page_url": null,
     * "path": "http://localhost:8082/api/furniture/news_detail",
     * "per_page": 5,
     * "prev_page_url": null,
     * "to": 1,
     * "total": 1
     *
     *     }
     * }
     */
    public function getMoreComments(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'id' => 'required',
        ], [
            'store_id.required' => '店铺信息未知',
            'id.required' => '评论id未知',
        ]);
        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }

        $store_id = $request->store_id;
        $comments = AlbumCommentsModel::find(request('id'));
        $user = AlbumUserModel::find($comments->user_id);

        $comments->avatar = $user->avatar;;
        $comments->username = $user->username;

        $comments_replys = AlbumCommentsModel::where('comments_id', $comments->id)
            ->orderByDesc('created_at')
            ->paginate(5);

        foreach ($comments_replys as $item) {
            $user = AlbumUserModel::find($item->user_id);
            $item->username = $user->username;
            $item->avatar = $user->avatar;
            $item->replys = AlbumCommentsModel::find($item->id)->replys()->paginate(5);
            foreach ($item->replys as $i) {
                $iuser = AlbumUserModel::find($i->user_id);
                $i->username = $iuser->username;
                $i->avatar = $iuser->avatar;
            }
        }

        return $this->api(compact('comments', 'comments_replys'));
    }


    /**
     * @api {get} /api/furniture/newgoods_list 新品发布列表
     * @apiDescription 获取新品发布列表(news_list)
     * @apiGroup Furniture
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    store_id  商户id 模拟值为1
     * @apiSuccessExample {json} Success-Response:
     * {
     * "status": true,
     * "status_code": 0,
     * "message": "",
     * "data": {
     * "current_page": 1,
     * "data": [
     *      {
     *          "id": 1,                    //id
     *          "title": "新品测试1",        //标题
     *          "thumb": "https://t6.9026.com/upload/img/20181119/4ee5baa103921e9d40e1c291d3c64f29.jpg",  //缩略图
     *          "content": "<p>这是一个新品测试</p>",     //详情
     *          "comments_field_1": "外观",             //用户自定义的评价字段
     *          "comments_field_2": "实用性",
     *          "comments_field_3": "质感",
     *          "comments_field_4": "舒适度",
     *          "sort": 100,
     *          "created_at": "2018-12-20 10:13:14",
     *          "updated_at": "2018-12-20 10:13:14",
     *          "store_id": 1,
     *          "comments_total": 2,                  //评价总量
     *      }
     *      ],
     *      "first_page_url": "http://local.furniture.com/api/furniture/newgoods_list?page=1",
     *      "from": 1,
     *      "last_page": 1,
     *      "last_page_url": "http://local.furniture.com/api/furniture/newgoods_list?page=1",
     *      "next_page_url": null,
     *      "path": "http://local.furniture.com/api/furniture/newgoods_list",
     *      "per_page": 10,
     *      "prev_page_url": null,
     *      "to": 1,
     *      "total": 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 newgoods_list(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;

        $list = FurnitureNewgoodsInfoModel::where('store_id', $store_id)->orderBy('sort', 'desc')->paginate(10);
        foreach ($list as $item) {
            $item->comments_total = $item->comments->count();
            unset($item->comments);
        }
        return $this->api($list);
    }


    /**
     * @api {get} /api/furniture/newgoods_index 新品发布详情
     * @apiDescription 获取新品发布详情(news_index)
     * @apiGroup Furniture
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    store_id  商户id 模拟值为1
     * @apiParam {int}    id  新品id 模拟值为1
     * @apiSuccessExample {json} Success-Response:
     * {
     * "status": true,
     * "status_code": 0,
     * "message": "",
     * "data": {
     * "newgoods": {
     * "id": 1,
     * "title": "新品测试1",         //标题
     * "thumb": "https://t6.9026.com/upload/img/20181119/4ee5baa103921e9d40e1c291d3c64f29.jpg",  //缩略图
     * "content": "<p>这是一个新品测试</p>",       //详情
     * "comments_field_1": "外观",               //评价1字段名称
     * "comments_field_2": "实用性",
     * "comments_field_3": "质感",
     * "comments_field_4": "舒适度",
     * "sort": 100,
     * "created_at": "2018-12-20 10:13:14",
     * "updated_at": "2018-12-20 10:13:14",
     * "store_id": 1,
     * "comments_avg_1": "5.0000",             //字段1平均分
     * "comments_avg_2": "4.0000",
     * "comments_avg_3": "3.0000",
     * "comments_avg_4": "3.0000"
     * },
     * "comments": [
     * {
     * "id": 2,
     * "user_id": 152,
     * "newgoods_id": 1,
     * "comments_field_1": 5,          //字段1评分
     * "comments_field_2": 4,
     * "comments_field_3": 3,
     * "comments_field_4": 3,
     * "content": "第一条评价",         //评价详情
     *  "picture": [                  //图片
     *      "https://t6.9026.com/upload/img/20181119/4ee5baa103921e9d40e1c291d3c64f29.jpg",
     *      "https://t6.9026.com/upload/img/20181119/4ee5baa103921e9d40e1c291d3c64f29.jpg",
     *      "https://t6.9026.com/upload/img/"
     * ],
     * "response": null,                //商家回复
     * "created_at": null,
     * "updated_at": null,
     * "store_id": 1,
     * "username": "哈哈哈",           //用户姓名
     * "avatar": "https://wx.qlogo.cn/mmopen/vi_32/yx8xw9O4WzvbGFLlqyRRNiciaNKM8V2wiasXrPCGUdB26D060FXUeIwiaAVzoOMibXUE9jhPkLsUz1UIpaTv71mYM4A/132"    //用户头像
     * }
     * ]
     * }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function newgoods_index(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'id' => 'required'
        ], [
            'store_id.required' => '店铺信息未知',
            'id.required' => '新品ID未知',
        ]);

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }

        $newgoods = FurnitureNewgoodsInfoModel::find($request->get('id'));
        $comments = $newgoods->comments()->paginate(10);
        foreach ($comments as $item) {
            $item->username = $item->user->username;
            $item->avatar = $item->user->avatar;
            $item->picture = explode(',', $item->picture);
            unset($item->user);
        }

        $newgoods->comments_avg_1 = FurnitureNewgoodsCommentModel::where('newgoods_id', $request->get('id'))->select(\DB::raw('AVG(comments_field_1) as field'))->first()->field;
        $newgoods->comments_avg_2 = FurnitureNewgoodsCommentModel::where('newgoods_id', $request->get('id'))->select(\DB::raw('AVG(comments_field_2) as field'))->first()->field;
        $newgoods->comments_avg_3 = FurnitureNewgoodsCommentModel::where('newgoods_id', $request->get('id'))->select(\DB::raw('AVG(comments_field_3) as field'))->first()->field;
        $newgoods->comments_avg_4 = FurnitureNewgoodsCommentModel::where('newgoods_id', $request->get('id'))->select(\DB::raw('AVG(comments_field_4) as field'))->first()->field;
        return $this->api(compact('newgoods', 'comments'));
    }


    /**
     * @api {post} /api/furniture/newgoods_addcomment 新品发布添加评论
     * @apiDescription 添加评论(newgoods_addcomment)
     * @apiGroup Furniture
     * @apiPermission passport
     * @apiVersion 0.1.0
     * @apiParam {int}    store_id  商户id 模拟值为1
     * @apiParam {int}    newgoods_id  新品id 模拟值为1
     * @apiParam {int}    comments_field_1  字段1评分 1-5
     * @apiParam {int}    comments_field_2  字段1评分 1-5
     * @apiParam {int}    comments_field_3  字段1评分 1-5
     * @apiParam {int}    comments_field_4  字段1评分 1-5
     * @apiParam {string}    [content]  评论详情
     * @apiParam {array}     [picture]  图片
     * @apiSuccessExample {json} Success-Response:
     * {
     * "status": true,
     * "status_code": 0,
     * "message": "",
     * "data": {
     * "store_id": "1",
     * "newgoods_id": "1",
     * "comments_field_1": "3",
     * "comments_field_2": "4",
     * "comments_field_3": "5",
     * "comments_field_4": "2",
     * "user_id": 151,
     * "updated_at": "2018-12-20 16:56:46",
     * "created_at": "2018-12-20 16:56:46",
     * "id": 3
     * }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function newgoods_addcomment(Request $request)
    {
        $user = Auth('api')->user();
        if (!$user) {
            $data = [
                'code' => 401,
                'msg' => 'token已过期，请重新登录'
            ];
            return $this->api($data);
        }
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'newgoods_id' => 'required',
            'comments_field_1' => 'required',
            'comments_field_2' => 'required',
            'comments_field_3' => 'required',
            'comments_field_4' => 'required',
        ], [
            'store_id.required' => '店铺信息未知',
            'newgoods_id.required' => '新品ID未知',
            'comments_field_1.required' => '字段1不能为空',
            'comments_field_2.required' => '字段2不能为空',
            'comments_field_3.required' => '字段3不能为空',
            'comments_field_4.required' => '字段4不能为空',
        ]);

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }
        $data = $request->all();

        if (isset($data['picture'])) {
            $data['picture'] = implode(',', $data['picture']);
        }
        $data['user_id'] = $user->id;

        $res = FurnitureNewgoodsCommentModel::create($data);

        return $this->api($res);
    }

    /**
     * @api {post} /api/furniture/newgoods_addbooking 新品发布添加预售
     * @apiDescription 添加预售(newgoods_addbooking)
     * @apiGroup Furniture
     * @apiPermission passport
     * @apiVersion 0.1.0
     * @apiParam {int}    store_id  商户id 模拟值为1
     * @apiParam {int}    newgoods_id  新品id 模拟值为1
     * @apiParam {int}    phone  电话
     * @apiParam {string}    receiver_name  姓名
     * @apiParam {string}    receiver_address  地址
     * @apiSuccessExample {json} Success-Response:
     * {
     * "status": true,
     * "status_code": 0,
     * "message": "",
     * "data": {
     * "store_id": "1",
     * "newgoods_id": "1",
     * "phone": 15178654534,
     * "receiver_name": '陈',
     * "receiver_address": '丽都路700号',
     * "updated_at": "2018-12-20 16:56:46",
     * "created_at": "2018-12-20 16:56:46",
     * "id": 3
     * }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function newgoods_addbooking(Request $request)
    {
        $user = Auth('api')->user();
        if (!$user) {
            $data = [
                'code' => 401,
                'msg' => 'token已过期，请重新登录'
            ];
            return $this->api($data);
        }

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'newgoods_id' => 'required',
            'phone' => 'required',
            'receiver_name' => 'required',
            'receiver_address' => 'required',

        ], [
            'store_id.required' => '店铺信息未知',
            'newgoods_id.required' => '新品ID未知',
            'phone.required' => '电话号码不能为空',
            'receiver_name.required' => '收货人不能为空',
            'receiver_address.required' => '收货地址不能为空',

        ]);

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }
        $data = $request->all();
        $data['user_id'] = $user->id;

        $res = FurnitureNewgoodsBookingModel::create($data);

        return $this->api($res);
    }

    /**
     * @api {get} /api/furniture/goods_list 获取产品列表
     * @apiDescription 获取产品列表(goods_list)
     * @apiGroup Furniture
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}    store_id  商户id 模拟值为1
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "current_page": 1,
     *          "data": [
     * ...
     *              {
     *                  "id": 1,
     *                  "goods_id":12               //要跳转的小程序id
     *                  "name": "床垫测试",
     *                  "img": "http://s1.xcx.com/upload/img/20180720/70f926022b933658d269106172e18bf0.png",
     *                  "sort": 99,
     *                  "status": 1,
     *                  "store_id": 1,
     *                  "created_at": "2018-07-20 14:56:42",
     *                  "updated_at": "2018-07-20 17:36:23",
     *                  "price": 199
     *              }
     * ...
     *          ],
     *          "first_page_url": "http://s1.xcx.com/api/furniture/goods_list?page=1",
     *          "from": 1,
     *          "last_page": 1,
     *          "last_page_url": "http://s1.xcx.com/api/furniture/goods_list?page=1",
     *          "next_page_url": null,
     *          "path": "http://s1.xcx.com/api/furniture/goods_list",
     *          "per_page": 5,
     *          "prev_page_url": null,
     *          "to": 4,
     *          "total": 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 furnitureGoodsList(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;
        $goods = FurnitureGoodsModel::where('store_id', $store_id)
            ->where('status', 1)
            ->orderByDesc('sort')
            ->paginate(5);

        return $this->api($goods);
    }


    /**
     * @api {post} /api/furniture/service_login 登陆(login)
     * @apiDescription 登陆(login)
     * @apiGroup Furniture_Service
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}     code              小程序登录生成的code
     * @apiParam {string}     nickName          微信昵称
     * @apiParam {string}     avatar            微信头像
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status": true,
     *      "status_code": 0,
     *      "message": "",
     *      "data": {
     * "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjUzMzYwMzNlNzIwOTE3YjE0NDc4YjgxMWY5MmI4MjBmMThlNDgxNjJjZGFkYmEwNGI3ZjliZTNmZjRlMTY2YjU4NGU4MzJhN2RmYzY2ZTcxIn0.eyJhdWQiOiIxIiwianRpIjoiNTMzNjAzM2U3MjA5MTdiMTQ0NzhiODExZjkyYjgyMGYxOGU0ODE2MmNkYWRiYTA0YjdmOWJlM2ZmNGUxNjZiNTg0ZTgzMmE3ZGZjNjZlNzEiLCJpYXQiOjE1MzI0MjA3NDAsIm5iZiI6MTUzMjQyMDc0MCwiZXhwIjoxNTYzOTU2NzQwLCJzdWIiOiIyIiwic2NvcGVzIjpbXX0.YnuRiJI9jlt-KeQ480UEpLWCUU8FEJvlTRtAdjOlP0BWmcdo0E9rGS4hriYnpfJOn09Cw0aRYuc4dgQYL_JWD2fodlGg1LRIvPTOtvM5TiwM86kQJawvfFw7X7p9nOhxrFa5Tyir0cdTcV0SmQbq8KIptjdR8j7wUTByKhONexBXtNnlZSpw70ckTQrAstkn97IDwPo04hhGhf6eDPc8ler0HONiAVqbRvvNG6yHShJarP1hxyXrYN2BM0N7dtLD_8Sr8XaXL6ie4rRFVM4fNwpn74DkiDwXY6-5Xet6mzPvvzARAmU5vJ7JHhcL1N7m7poNp6YCx_mZAZ1z8PGDKrtQWoVeAmIxo7qtI6jvgvUpEFnJQ-KHCunXflNBL-vIYW4o3llnYqku1pcBdAUfkYLjYUgB3EZio280_8q-6Q24VAMiHZ58AjYvHHJJssdOa3dVHGD9Iq2z1dWR6gmZ4MgGCunCcAe9L_CbDm7VtMq3nKj4a1WScRiMD5nlKAHgy4O32rtNXqDr5T-eV-QNa4ZOv4VZ1AR-WE4RkO4ArKPaFxgSa9mak98PU8NHcPaJ_B3eDbvtwtMloTXWSQP08cmUPXKjEwXvszdkUt-ZWirw5Sd22h3qMdCI3gcvzT4_rnDKCEk37P09fUIK8LZrS4s2xOhueHziMzheAF0QekI",
     *      "user": {
     *          "id": 2,
     *          "store_id": 1,
     *          "username": "roger",
     *          "role": 0,                        //用户类型：0：普通用户；1：生产部 2：包装部 3：经理
     *          "wechat_open_id": "olAS94uwfTdsL3nDnvG67p_v5Vks",
     *          "avatar": "https://wx.qlogo.cn/mmopen/vi_32/IOcxico8l4A7W3qxDeA53Id5kVAj2ibUGvQib9QibicTp5c1RNshDj6EKz2PKWp3reHfib0xxT4wa7jJzcb7a4EggkVw/132",
     *          "is_dealer": 0                 //是否经销商 0：不是 1：是
     *          },
     *      "session_key": 'pGgENkTGXLQD4hPuTF8yEw=='
     *      }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     *    40029                                   获取openid失败
     */
    public function serviceLogin(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'code' => 'required',
                'store_id' => 'required',
                'iv' => 'required',
                'encryptData' => 'required',
            ],
            [
                'code.required' => 'code不能为空!',
                'store_id.required' => 'store_id不能为空!',
                'iv.required' => '偏移量不能为空!',
                'encryptData.required' => '加密数据不能为空!',
            ]
        );


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

        $storeid = $request->get('store_id');

        $this->wechat_app = AlbumManufacturerModel::where('store_id', $storeid)->first();
        $config = [
            'app_id' => $this->wechat_app->service_app_id,
            'secret' => $this->wechat_app->service_app_secret,

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

        $code = $request->get('code');
        $iv = $request->get('iv');
        $encryptData = $request->get('encryptData');
        $session = $app->auth->session($code);
        if (!isset($session['openid'])) {
            $data = [
                'code' => 40029,
                'msg' => '获取openID失败'

            ];

            return $this->api($data);
        }
        \Log::info(json_encode($session));
        $openid = $session['openid'];
        $session_key = $session['session_key'];
        $decryptedData = $app->encryptor->decryptData($session_key, $iv, $encryptData);
       // dd($decryptedData);
        $userinfo = AlbumUserModel::where('wechat_union_id', $decryptedData['unionId'])->where('store_id', $storeid)->first(['id', 'username', 'wechat_open_id', 'avatar']);

        if (!$userinfo) {
            $data['wechat_open_id'] = $openid;
            $data['wechat_union_id'] = $decryptedData['unionId'];
            $data['username'] = $request->get('nickName');
            $data['avatar'] = $request->get('avatar');
            $data['store_id'] = $request->get('store_id');
            $data['is_dealer'] = 0;


            $userinfo = AlbumUserModel::create($data);
        }else{
            $save['wechat_open_id'] = $openid;
            AlbumUserModel::where('wechat_union_id',$decryptedData['unionId'])->update($save);
        }
        $conf = AlbumManufacturerModel::where('store_id',$request->get('store_id'))->first();
        $getPhone = $conf->getPhone;
        $getFocus = $conf->getFocus;
        if (Auth::loginUsingId($userinfo->id)) {
            $user = Auth::user();
            $token = $user->createToken($user->id . '-' . $user->openid)->accessToken;
            return $this->api(compact('token', 'user', 'session_key','getFocus'));
        } else {

            return $this->error(ErrorCode::INCORRECT_USER_OR_PASS);
        }

    }

    /**
     * @api {get} /api/furniture/getfurnitureads 获取首页广告
     * @apiDescription 获取首页广告
     * @apiGroup Furniture_Service
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}    store_id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "furniture_ads_pic": "http://s1.xcx.com/upload/img/20180720/70f926022b933658d269106172e18bf0.png"
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function getFurnitureAds(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'store_id' => 'required'
            ],
            [
                'store_id.required' => 'store_id不能为空!'
            ]
        );


        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $ads = AlbumManufacturerModel::where('store_id', request('store_id'))->first(['furniture_ads_pic']);
        return $this->api($ads);
    }

    /**
     * @api {get} /api/furniture/getattr 获取产品属性
     * @apiDescription 获取产品属性
     * @apiGroup Furniture_Service
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}    store_id
     * @apiParam {string}    [id]  默认获取品类，传品类id获取该品类的型号，传型号id获取该型号的颜色
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": [
     * ...
     *          {
     *              "id": 1,
     *              "name": "冰箱",
     *              "pid": 0,
     *              "attr_type": 0,
     *              "sort": 100,
     *              "store_id": 1,
     *              "deleted_at": null,
     *              "created_at": "2018-06-28 02:55:26",
     *              "updated_at": "2018-06-28 02:59:29"
     *          },
     * ...
     *      ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function getAttr(Request $request)
    {
        $store_id = request('store_id');
        $pid = request('id') ? request('id') : 0;
        $attr = AlbumProductAttrModel::where('store_id', $store_id)->where('pid', $pid)->orderBy('sort', 'desc')->get();
        return $this->api($attr);
    }

    /**
     * @api {post} /api/furniture/createorder 创建售后订单
     * @apiDescription 创建售后订单
     * @apiGroup Furniture_Service
     * @apiPermission Passport
     * @apiVersion 0.1.0
     * @apiParam {string}    store_id                   Store_id
     * @apiParam {string}    category                   产品类别
     * @apiParam {string}    type                       产品型号
     * @apiParam {string}    [color]                    产品颜色
     * @apiParam {string}    question                   问题描述
     * @apiParam {string}    [picture]                  图片
     * @apiParam {string}    customer_name              联系人姓名
     * @apiParam {string}    customer_phone             联系人电话
     * @apiParam {string}    customer_address           联系人地址
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "category": [
     *
     *          ]
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function createOrder(Request $request)
    {
        $user = Auth('api')->user();
        if (!$user) {
            $data = [
                'code' => 401,
                'msg' => 'token已过期，请重新登录'
            ];
            return $this->api($data);
        }

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'category' => 'required',
            'type' => 'required',
            'question' => 'required',
            'customer_name' => 'required',
            'customer_phone' => 'required|regex:/^1[345789][0-9]{9}$/',
            'customer_address' => 'required',
        ], [
            'store_id.required' => '站点信息未知',
            'category.required' => '产品分类不能为空',
            'type.required' => '产品型号不能为空',
            'question.required' => '问题描述不能为空',
            'customer_name.required' => '姓名不能为空',
            'customer_phone.required' => '联系方式不能为空',
            'customer_phone.regex' => '请输入正确的手机号码',
            'customer_address.required' => '收货地址不能为空',
        ]);
        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }

        $data = $request->all();
        $data['status'] = 0;
        $data['sno'] = date('YmdHmis');
        $data['type'] = $data['category'] . $data['type'];

        if (isset($data['picture'])) {
            $data['picture'] = implode(',', $data['picture']);
        }
        $data['user_id'] = $user->id;


        $user->phone = $data['customer_phone'];
        $user->save();

        $res = AlbumOrderModel::create($data);
        if ($res) {
            $this->getQrcode(request('store_id'), $res->id);
        }

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


    /**
     * @api {get} /api/furniture/getorder 获取订单信息
     * @apiDescription 获取订单
     * @apiGroup Furniture_Service
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}     store_id
     * @apiParam {string}    [user_id]      (填写user_id,查询用户个人订单，不填则查询店铺订单)
     * @apiParam {string}    [status](可填) (选填 0:待审核；1：待生产；2：生产中；3：待发货；4：运输中/未签收 5：已签收/待评价 6:已评价 7:已取消 null:全部订单 8:生产部全部订单/个人待发货订单 9：包装部全部订单)
     * @apiParam {string}    [expected]     (1：查询逾期的订单)
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *          "current_page": 1,
     *          "data": [
     * ...
     *              {
     *                  "id": 1,
     *                   "sno": "s1001",
     *                  "qrcode": "qr.png",
     *                  "status": 1,
     *                  "category": "冰箱",
     *                  "type": "s1002",
     *                  "color": "白色",
     *                  "picture": "1.ipg",
     *                  "question": "问题测试",
     *                  "customer_name": "wesley",
     *                  "customer_phone": "18380257014",
     *                  "customer_address": "成都市新都区",
     *                  "user_id": 1,
     *                  "producer_id": null,
     *                  "packer_id": null,
     *                  "price": 50,
     *                  "expected_time": "2018-07-05",
     *                  "remark": null,
     *                  "store_id": 1,
     *                  "created_at": "2018-07-03 17:18:26",
     *                  "updated_at": "2018-07-05 14:53:42"
     *          }
     * ...
     *      ],
     *                  "first_page_url": "http://s1.xcx.com/api/furniture/getorder?page=1",
     *                  "from": 1,
     *                  "last_page": 1,
     *                  "last_page_url": "http://s1.xcx.com/api/furniture/getorder?page=1",
     *                  "next_page_url": null,
     *                  "path": "http://s1.xcx.com/api/furniture/getorder",
     *                  "per_page": 5,
     *                  "prev_page_url": null,
     *                  "to": 2,
     *                  "total": 2                                     //订单数量
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function getOrder(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, '');
        }

        $storeid = request('store_id');
        $userid = request('user_id');
        if ($userid) {
            if (request('status') !== null) {
                if (request('status') == 8) {
                    $order = AlbumOrderModel::where('store_id', $storeid)->where('user_id', $userid)->whereIn('status', [1, 2, 3])->orderBy('updated_at', 'desc')->paginate(5);
                } else {
                    $order = AlbumOrderModel::where('store_id', $storeid)->where('user_id', $userid)->where('status', request('status'))->orderBy('updated_at', 'desc')->paginate(5);

                }
            }

            if (request('expected')) {
                $order = AlbumOrderModel::where('store_id', $storeid)
                    ->where('user_id', $userid)
                    ->where('status', '>', 0)
                    ->where('status', '<', 5)
                    ->where(DB::raw("DATEDIFF(NOW(),expected_time)"), '>', 0)
                    ->orderBy('updated_at', 'desc')->paginate(5);
            }

            if (request('status') === null && !request('expected')) {
                $order = AlbumOrderModel::where('store_id', $storeid)->where('user_id', $userid)->orderBy('updated_at', 'desc')->paginate(5);
            }

            return $this->api(compact('order'));
        } else {
            if (request('status') !== null) {
                if (request('status') == 8) {
                    $order = AlbumOrderModel::where('store_id', $storeid)->whereIn('status', [1, 2, 3])->orderBy('updated_at', 'desc')->paginate(5);
                } elseif (request('status') == 9) {
                    $order = AlbumOrderModel::where('store_id', $storeid)->whereIn('status', [3, 4, 5])->orderBy('updated_at', 'desc')->paginate(5);
                } else {
                    $order = AlbumOrderModel::where('store_id', $storeid)->where('status', request('status'))->orderBy('updated_at', 'desc')->paginate(5);
                }

            }

            if (request('expected')) {
                $order = AlbumOrderModel::where('store_id', $storeid)
                    ->where('status', '>', 0)
                    ->where('status', '<', 5)
                    ->where(DB::raw("DATEDIFF(NOW(),expected_time)"), '>', 0)
                    ->orderBy('updated_at', 'desc')->paginate(5);
            }

            if (request('status') === null && !request('expected')) {
                $order = AlbumOrderModel::where('store_id', $storeid)->orderBy('updated_at', 'desc')->paginate(5);
            }


            return $this->api($order);
        }

    }

    /**
     * @api {get} /api/furniture/getorderdetail 获取订单详情
     * @apiDescription 获取订单详情
     * @apiGroup Furniture_Service
     * @apiPermission Passport
     * @apiVersion 0.1.0
     * @apiParam {string}     store_id
     * @apiParam {string}     order_id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *          "order": {         //订单详情
     *              "id": 1,
     *              "sno": "s1001",
     *              "qrcode": "qr.png",
     *              "status": 1,
     *              "category": "冰箱",
     *              "type": "s1002",
     *              "color": "白色",
     *              "question": "问题测试",
     *              "customer_name": "wesley",
     *              "customer_phone": "18380257014",
     *              "customer_address": "成都市新都区",
     *              "user_id": 1,
     *              "producer_id": null,
     *              "packer_id": null,
     *              "price": 50,
     *              "expected_time": "2018-07-05",
     *              "remark": null,                             //备注
     *              "store_id": 1,
     *              "deleted_at": null,
     *              "created_at": "2018-07-03 17:18:26",
     *              "updated_at": "2018-07-05 14:53:42",
     *              "pcture": [
     *                  "1.png",
     *                  "2.png"
     *              ]
     *          },
     *      "progress": [            //订单进度
     * ...
     *          {
     *              "created_at": "2018-08-02 17:31:14",
     *              "description": "订单已提交，等待审核",
     *              "status": 0
     *          }
     * ...
     *      ],
     *      "parts": [               //订单配件
     * ...
     *          {
     *              "name": "螺丝刀",
     *              "count": 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 getOrderDetail(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'order_id' => 'required',

        ], [
            'store_id.required' => '站点信息未知',
            'order_id.required' => 'order id未知',
        ]);

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }

        $user = Auth('api')->user();
        if (!$user) {
            $data = [
                'code' => 401,
                'msg' => 'token已过期，请重新登录'
            ];
            return $this->api($data);
        }

        $order = AlbumOrderModel::find(request('order_id'));
        $parts = AlbumPartsModel::where('store_id', request('store_id'))->where('order_id', request('order_id'))
            ->get(['name', 'count']);
        $progress = AlbumProgressModel::where('store_id', request('store_id'))->where('order_id', request('order_id'))->orderBy('created_at', 'asc')->get(['created_at', 'description', 'status']);
        $order->picture = explode(',', $order->picture);
        return $this->api(compact('order', 'progress', 'parts'));
    }

    /**
     * @api {get} /api/furniture/getprogress 订单进度统计
     * @apiDescription 订单进度统计
     * @apiGroup Furniture_Service
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}     store_id
     * @apiParam {string}    [user_id] (查询用户个人各个订单状态数量时带上此参数)
     * @apiParam {string}    [status]( 0:待审核；1：待生产；2：生产中；3：待发货；4：未签收，不填写则返回所有状态下的订单数量)
     * @apiParam {string}    [expected] 1：逾期)
     * * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK 所有状态统计
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         ""count": [
     *               {
     *                  "status": 0,             //订单状态
     *                   "total": 1              //改状态订单数量
     *               },
     *               {
     *                   "status": 1,
     *                   "total": ''
     *               },
     *                   "status": 2,
     *                   "total": ''
     *               },
     *                   "status": 3,
     *                   "total": ''
     *               },
     *                   "status": 4,
     *                   "total": ''
     *               },
     *               {
     *               "expected": 1,
     *               "total": 1
     *               }
     *                    ]
     *     }
     * }
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK 具体状态下统计图
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "count": [
     * ...
     *               {
     *               "customer_name": "",        //联系人姓名
     *               "days": ""                  //该状态维持天数
     *               }
     * ...
     *          ]
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function getProgress(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, '');
        }

        $storeid = request('store_id');
        $status = request('status');
        $expected = request('expected');
        $user_id = request('user_id');

        if ($user_id) {
            if ($status === null && !$expected) {
                $count1 = AlbumOrderModel::where('store_id', $storeid)
                    ->where('user_id', $user_id)
                    ->groupBy('status')
                    ->select('status', DB::raw('count(*) as total'))
                    ->get()->toArray();
                $count2 = AlbumOrderModel::where('store_id', $storeid)
                    ->where('user_id', $user_id)
                    ->where('status', '>', 0)
                    ->where('status', '<', 5)
                    ->where(DB::raw("DATEDIFF(NOW(),expected_time)", '>', 0))
                    ->select('id as expected', DB::raw('count(*) as total'))
                    ->get()->toArray();
                $count2[0]['expected'] = 1;
                $count = array_merge($count1, $count2);
            }
            if ($status !== null) {
                $count = AlbumOrderModel::where('store_id', $storeid)
                    ->where('status', $status)
                    ->where('user_id', $user_id)
                    ->select('customer_name', 'updated_at')->get();
                foreach ($count as $item) {
                    $item->days = Carbon::now()->diffInDays($item->updated_at);
                    unset($item->updated_at);
                }
            }

            if ($expected) {
                $count = AlbumOrderModel::where('store_id', $storeid)
                    ->where('user_id', $user_id)
                    ->where('status', '>', 0)
                    ->where('status', '<', 5)
                    ->where(DB::raw("DATEDIFF(NOW(),expected_time)"), '>', 0)
                    ->select('customer_name', 'updated_at')
                    ->get();
                foreach ($count as $item) {
                    $item->days = Carbon::now()->diffInDays($item->updated_at);
                    unset($item->updated_at);
                }
            }
        } else {
            if ($status === null && !$expected) {
                $count1 = AlbumOrderModel::where('store_id', $storeid)->groupBy('status')->select('status', DB::raw('count(*) as total'))->get()->toArray();
                $count2 = AlbumOrderModel::where('store_id', $storeid)
                    ->where('status', '>', 0)
                    ->where('status', '<', 5)
                    ->where(DB::raw("DATEDIFF(NOW(),expected_time)"), '>', 0)
                    ->select('id as expected', DB::raw('count(*) as total'))
                    ->get()->toArray();
                $count2[0]['expected'] = 1;
                $count = array_merge($count1, $count2);
            }
            if ($status !== null) {
                $count = AlbumOrderModel::where('store_id', $storeid)->where('status', $status)->select('customer_name', 'updated_at')->get();
                foreach ($count as $item) {
                    $item->days = Carbon::now()->diffInDays($item->updated_at);
                    unset($item->updated_at);
                }
            }

            if ($expected) {
                $count = AlbumOrderModel::where('store_id', $storeid)
                    ->where('status', '>', 0)
                    ->where('status', '<', 5)
                    ->where(DB::raw("DATEDIFF(NOW(),expected_time)"), '>', 0)
                    ->select('customer_name', 'updated_at')->get();
                foreach ($count as $item) {
                    $item->days = Carbon::now()->diffInDays($item->updated_at);
                    unset($item->updated_at);
                }
            }
        }


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


    /**
     * @api {get} /api/furniture/getreviewcount 评价统计
     * @apiDescription 评价统计
     * @apiGroup Furniture_Service
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}     store_id
     * @apiParam {string}    [days](必填 0:今天；7：7天内；30：30天内
     * * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK 所有状态统计
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *          "verifier": [                             //客服部
     *                  {
     *                   "verifier_review": 0,           评价等级：0：好评 1：中评 2：差评
     *                   "verifier": 7                    评价数量
     *                   }，
     *                  {
     *                   "verifier_review": 1,
     *                   "verifier": 5
     *                   }，
     *           ],
     *          "producer": [                           //生产部
     *                  {
     *                   "producer_review": 0,
     *                   "producer": 1
     *                   },
     *             ...
     *          ],
     *          "packer": [                            //包装部
     *              {
     *               "producer_review": 0,
     *               "producer": 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 getReviewCount(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, '');
        }

        $storeid = request('store_id');
        $days = request('days') ? request('days') : 0;

        //客服部
        $verifier = AlbumReviewModel::where('store_id', $storeid)->where(DB::raw("DATEDIFF(NOW(),created_at)"), '<=', $days)->groupBy('verifier_review')->select(DB::raw('verifier_review,count(*) as verifier'))->orderBy('verifier_review', 'asc')->get()->toArray();


        //生产部
        $producer = AlbumReviewModel::where('store_id', $storeid)->where(DB::raw("DATEDIFF(NOW(),created_at)"), '<=', $days)->groupBy('producer_review')->select(DB::raw('producer_review,count(*) as producer'))->orderBy('producer_review', 'asc')->get()->toArray();

        //包装部
        $packer = AlbumReviewModel::where('store_id', $storeid)->where(DB::raw("DATEDIFF(NOW(),created_at)"), '<=', $days)->groupBy('packer_review')->select(DB::raw('packer_review,count(*) as packer'))->orderBy('packer_review', 'asc')->get()->toArray();


        return $this->api(compact('verifier', 'producer', 'packer'));
    }

    /**
     * @api {get} /api/furniture/ordercount 按产品/品类统计
     * @apiDescription 按产品/品类统计
     * @apiGroup Furniture_Service
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}     store_id
     * @apiParam {string}    [type] 按产品统计，可选值：1
     * @apiParam {string}    [category] 按品类统计，与type二选一，不能与type同时传值。可选值：1（所有品类）具体品类的值（统计具体品类）
     * @apiParam {string}    [days]    可选：0，7，30
     * * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK 所有状态统计
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     * ...
     *         {
     *           "days": "2018-07-03",  //日期
     *           "count": 2,            //数量
     *           "category": "冰箱",    //品类
     *           "type": "s1002"       //产品型号
     *           },
     * ...
     *     }
     * }
     *
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function orderCount(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, '');
        }

        $storeid = request('store_id');
        $type = request('type');
        $category = request('category');
        $days = request('days') ? request('days') : 0;
        if ($type) {
            if ($type == 1) {
                $order = AlbumOrderModel::where('store_id', $storeid)
                    ->where(DB::raw("DATEDIFF(NOW(),created_at)"), '<=', $days)
                    ->where('status', '>', 0)
                    ->where('status', '<', 7)
                    ->groupBy('days', 'type')
                    ->select(DB::raw("DATE_FORMAT(created_at,'%Y-%m-%d') as days,count('id') as count,'type',category"), 'type')
                    ->get();
            } else {
                $order = AlbumOrderModel::where('store_id', $storeid)
                    ->where(DB::raw("DATEDIFF(NOW(),created_at)"), '<=', $days)
                    ->where('status', '>', 0)
                    ->where('status', '<', 7)
                    ->where('type', $type)
                    ->groupBy('days', 'type')
                    ->select(DB::raw("DATE_FORMAT(created_at,'%Y-%m-%d') as days,count('id') as count,'type',category"), 'type')
                    ->get();
            }


        }

        if ($category) {
            if ($category == 1) {
                $order = AlbumOrderModel::where('store_id', $storeid)
                    ->where(DB::raw("DATEDIFF(NOW(),created_at)"), '<=', $days)
                    ->where('status', '>', 0)
                    ->where('status', '<', 7)
                    ->groupBy('days', 'category')
                    ->select(DB::raw("DATE_FORMAT(created_at,'%Y-%m-%d') as days,count('id') as count,category,type"), 'type')
                    ->get();
            } else {
                $order = AlbumOrderModel::where('store_id', $storeid)
                    ->where(DB::raw("DATEDIFF(NOW(),created_at)"), '<=', $days)
                    ->where('status', '>', 0)
                    ->where('status', '<', 7)
                    ->where('category', $category)
                    ->groupBy('days', 'category')
                    ->select(DB::raw("DATE_FORMAT(created_at,'%Y-%m-%d') as days,count('id') as count,category,type"), 'type')
                    ->get();
            }

        }

        return $this->api($order);

    }


    /**
     * @api {get} /api/furniture/searchlist  产品订单搜索列表页
     * @apiDescription 产品订单搜索列表页
     * @apiGroup Furniture_Service
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}     store_id
     * @apiParam {string}     [keyword]     搜索关键字
     * * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *          "current_page": 1,
     *          "data": [
     * ...
     *              {
     *                  "id": 1,
     *                   "sno": "s1001",
     *                  "qrcode": "qr.png",
     *                  "status": 1,
     *                  "category": "冰箱",
     *                  "type": "s1002",
     *                  "color": "白色",
     *                  "picture": "1.ipg",
     *                  "question": "问题测试",
     *                  "customer_name": "wesley",
     *                  "customer_phone": "18380257014",
     *                  "customer_address": "成都市新都区",
     *                  "user_id": 1,
     *                  "producer_id": null,
     *                  "packer_id": null,
     *                  "price": 50,
     *                  "expected_time": "2018-07-05",
     *                  "remark": null,
     *                  "store_id": 1,
     *                  "created_at": "2018-07-03 17:18:26",
     *                  "updated_at": "2018-07-05 14:53:42"
     *          }
     * ...
     *      ],
     *                  "first_page_url": "http://s1.xcx.com/api/furniture/getorder?page=1",
     *                  "from": 1,
     *                  "last_page": 1,
     *                  "last_page_url": "http://s1.xcx.com/api/furniture/getorder?page=1",
     *                  "next_page_url": null,
     *                  "path": "http://s1.xcx.com/api/furniture/getorder",
     *                  "per_page": 5,
     *                  "prev_page_url": null,
     *                  "to": 2,
     *                  "total": 2                                     //订单数量
     *     }
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function searchList(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, '');
        }

        $storeid = request('store_id');
        $keyword = request('keyword');
        if ($keyword) {
            $order = AlbumOrderModel::where('store_id', $storeid)
                ->where(function ($query) use ($keyword) {
                    $query->where('type', 'like', '%' . $keyword . '%')
                        ->orwhere('sno', 'like', '%' . $keyword . '%')
                        ->orwhere('customer_name', 'like', '%' . $keyword . '%')
                        ->orwhere('customer_phone', 'like', '%' . $keyword . '%');
                })
                ->orderBy('updated_at', 'desc')
                ->paginate(5);
        } else {
            $order = AlbumOrderModel::where('store_id', $storeid)
                ->orderBy('updated_at', 'desc')
                ->paginate(5);
        }

        return $this->api($order);
    }

    /**
     * @api {post} /api/furniture/addreview  添加评论
     * @apiDescription 添加评论
     * @apiGroup Furniture_Service
     * @apiPermission Passport
     * @apiVersion 0.1.0
     * @apiParam {string}     store_id
     * @apiParam {int}        order_id
     * @apiParam {int}        verifier_review      客服部评论：0：好评；1：中评：2：差评
     * @apiParam {int}        producer_review      生产部部评论：0：好评；1：中评：2：差评
     * @apiParam {int}        packer_review        包装部评论：0：好评；1：中评：2：差评
     * @apiParam {int}       [description]         评论描述
     * @apiParam {int}       [picture]             图片
     * * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK 添加评论成功
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *          "store_id": "1",
     *          "verifier_review": "0",
     *          "producer_review": "0",
     *          "packer_review": "1",
     *          "order_id": "1",
     *          "updated_at": "2018-07-26 15:03:33",
     *          "created_at": "2018-07-26 15:03:33",
     *          "id": 5
     *     }
     * }
     *
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function addReview(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'order_id' => 'required',
            'verifier_review' => 'required',
            'producer_review' => 'required',
            'packer_review' => 'required',

        ], [
            'store_id.required' => '站点信息未知',
            'order_id.required' => '未知的订单',
            'verifier_review.required' => '客服部评论未填',
            'producer_review.required' => '生产部评论未填',
            'packer_review.required' => '包装部评论未填',
        ]);

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }

        $user = Auth('api')->user();
        if (!$user) {
            $data = [
                'code' => 401,
                'msg' => 'token已过期，请重新登录'
            ];
            return $this->api($data);
        }

        $data = $request->all();

        $order = $order = AlbumOrderModel::find(request('order_id'));
        $order->status = 6;
        $order->save();

        if (isset($data['picture'])) {
            $data['picture'] = implode(',', $data['picture']);
        }
        $review = AlbumReviewModel::create($data);


        return $this->api($review);


    }

    /**
     * @api {post} /api/furniture/updatestatus  更新订单状态
     * @apiDescription 更新订单状态
     * @apiGroup Furniture_Service
     * @apiPermission Passport
     * @apiVersion 0.1.0
     * @apiParam {string}     store_id
     * @apiParam {int}        order_id
     * @apiParam {int}        status   2:开始生产 3：生产完毕并入库 4：发货 5：确认收货 7:取消订单
     * @apiParam {int}        [remark]   备注，发货时可携带此参数
     * * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK   更新状态成功
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *          "ok":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 updateStatus(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'order_id' => 'required',
            'status' => 'required|regex:/[23457]/',

        ], [
            'store_id.required' => '站点信息未知',
            'order_id.required' => 'order id未知',
            'status.required' => 'status未知',
            'status.regex' => '请填写正确的订单状态',
        ]);

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }

        $user = Auth('api')->user();
        if (!$user) {
            $data = [
                'code' => 401,
                'msg' => 'token已过期，请重新登录'
            ];
            return $this->api($data);
        }

        $storeid = request('store_id');
        $orderid = request('order_id');

        $status = request('status');
        $remark = request('remark');

        $order = AlbumOrderModel::find($orderid);

        $order->status = $status;

        if ($remark) {
            $order->remark = $remark;
        }
        if ($status == 2 || $status == 3) {
            $order->producer_id = $user->id;
        }
        if ($status == 4) {
            $order->packer_id = $user->id;
        }

        $ok = $order->save();
        $this->addProgress($status, $storeid, $orderid);


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

    /**
     * @api {post} /api/furniture/getphonenumber   获取手机号
     * @apiDescription 获取手机号
     * @apiGroup Furniture_Service
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}    store_id
     * @apiParam {string}    session_key
     * @apiParam {string}    iv
     * @apiParam {string}    encryptData
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": {
     *         "decryptedData": [
     *
     *          ]
     *
     *     }
     *
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     * 可能出现的错误代码：
     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
     */
    public function getPhoneNumber(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'session_key' => 'required',
            'iv' => 'required',
            'encryptData' => 'required',

        ], [
            'store_id.required' => '站点信息未知',
            'session_key.required' => 'session_key未知',
            'iv.required' => 'iv未知',
            'encryptData.required' => 'encryptData未知',
        ]);

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }

        $session_key = $request->get('session_key');
        $iv = $request->get('iv');
        $encryptData = $request->get('encryptData');
        $storeid = $request->get('store_id');

        $this->wechat_app = AlbumManufacturerModel::where('store_id', $storeid)->first();
        $config = [
            'app_id' => $this->wechat_app->service_app_id,
            'secret' => $this->wechat_app->service_app_secret,

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

        $decryptedData = $app->encryptor->decryptData($session_key, $iv, $encryptData);

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


    /**
     * @api {post} /api/furniture/printorder   打印订单
     * @apiDescription 打印订单
     * @apiGroup Furniture_Service
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}    store_id
     * @apiParam {string}    order_id
     * @apiParam {int}       role  1:生产部
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status": true,
     *      "status_code": 0,
     *      "message": "",
     *      "data": {
     *          "code": 200,
     *          "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 printOrder(Request $request)
    {
        header("Content-type: text/html; charset=utf-8");
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'order_id' => 'required',

        ], [
            'store_id.required' => '站点信息未知',
            'order_id.required' => 'order_id信息未知',
        ]);

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }

        $role = $request->get('role') ? $request->get('role') : 2;

        $order = AlbumOrderModel::find(request('order_id'));
        $filename = explode('/', $order->qrcode);
        $filename = end($filename);
        $qrcode = public_path() . '/download/' . $filename;

        $image = new ZBarCodeImage($qrcode);
        $scanner = new ZBarCodeScanner();
        $qrcodedata = $scanner->scan($image);
        $qrcodetext = $qrcodedata[0]['data'];

//        $QrReader = new \QrReader($qrcode);
//        $qrcodetext = $QrReader->text();

        $content = "";
        $parts = AlbumPartsModel::where('store_id', request('store_id'))->where('order_id', request('order_id'))
            ->get(['name', 'count']);

        if ($role == 2) {
            $content .= "--------------------------------<BR>";
            $content .= "<B>订单编号  #" . $order->sno . " </B><BR><BR>";
            $content .= "<B>下单时间：" . $order->created_at . "</B><BR><BR>";
            $content .= "<B>产品型号：" . $order->type . "</B><BR><BR>";
            $content .= "<B>修理费：" . $order->price . "</B><BR><BR>";
            $content .= "--------------------------------<BR>";
            $content .= "<B>送货地点：" . $order->customer_address . "</B><BR><BR>";
            $content .= "<B>联系电话：" . $order->customer_phone . "</B><BR><BR>";
            $content .= "<B>联系人：" . $order->customer_name . "</B><BR><BR>";
            if (count($parts)) {
                $content .= "配件：";
                foreach ($parts as $part) {
                    $content .= "<C>" . $part->name . '------' . $part->count . "</C><BR>";
                };
            }
        }

        if ($order->remark && $role == 2) {
            $content .= "<B>备注：" . $order->remark . "</B><BR>";
        }
        if ($role == 2) {
            $content .= "<QR>" . $qrcodetext . "</QR><BR>";
        }

        if ($role == 1) {

            $content .= "客户姓名：" . $order->customer_name . "<BR>";
            $content .= "联系方式：" . $order->customer_phone . "<BR>";
            $content .= "联系地址：" . $order->customer_address . "<BR>";

            $content .= "产品分类：" . $order->category . "<BR>";
            $content .= "产品型号：" . $order->type . "<BR>";
            $content .= "产品颜色：" . $order->color . "<BR>";
            if (count($parts)) {
                $content .= "配件：";
                foreach ($parts as $part) {
                    $content .= "<C>" . $part->name . '------' . $part->count . "</C><BR>";
                };
            }
            $content .= "逾期时间：" . $order->expected_time . "<BR>";
        }


        $setting = AlbumManufacturerModel::where('store_id', request('store_id'))->first();

        if ($setting->print_type == 2) {
            $res = $this->print_365($setting->print_no, $setting->print_key, $content, 1);
        } else {
            $res = $this->wp_print($setting->print_no, $content, 1);
        }

        if ($res) {
            $data = [
                'code' => 200,
                'msg' => '打印成功！'
            ];
            return $this->api($data);
        } else {
            $data = [
                'code' => 4,
                'msg' => '打印机连接失败！'
            ];
            return $this->api($data);
        }

    }

    function print_365($printer_sn, $print_key, $orderInfo, $times)
    {
        $selfMessage = array(
            'deviceNo' => $printer_sn,
            'printContent' => $orderInfo,
            'key' => $print_key,
            'times' => $times
        );
        $url = "http://open.printcenter.cn:8080/addOrder";
        $options = array(
            'http' => array(
                'header' => "Content-type: application/x-www-form-urlencoded ",
                'method' => 'POST',
                'content' => http_build_query($selfMessage),
            ),
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        $res = json_decode($result);

        if (isset($res->responseCode) && $res->responseCode === 0) {
            return true;
        } else {
            return false;
        }
    }


    function wp_print($printer_sn, $orderInfo, $times)
    {

        $user = '1170640404@qq.com';
        $ukey = 'ECfrLVsrd9Wq22zR';
        $stime = time();

        $content = array(
            'user' => $user,
            'stime' => $stime,
            'sig' => sha1($user . $ukey . $stime),
            'apiname' => 'Open_printMsg',

            'sn' => $printer_sn,
            'content' => $orderInfo,
            'times' => $times//打印次数
        );
        $client = new \HttpClient('api.feieyun.cn', 80);
        if (!$client->post('/Api/Open/', $content)) {
            \Log::info($client->getContent());
            return false;
        } else {
            \Log::info($client->getContent());
            return true;
        }

    }

    /**
     * @api {post} /api/furniture/saveformid   保存formid
     * @apiDescription 保存formid
     * @apiGroup Furniture_Service
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}    store_id
     * @apiParam {string}    openid
     * @apiParam {string}    formid
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status": true,
     *      "status_code": 0,
     *      "message": "",
     *     "data": {
     *          "code": 200,
     *          "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 saveFormId(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'store_id' => 'required',
            'openid' => 'required',
            'formid' => 'required',

        ], [
            'store_id.required' => '站点信息未知',
            'formid.required' => 'formid未知',
            'openid.required' => 'openid未知',
        ]);

        if ($validator->fails()) {
            return $this->validatorError($validator->messages()->all(), ErrorCode::CLIENT_WRONG_PARAMS, '');
        }

        $data = $request->all();
        $res = FurnitureFormidModel::create($data);
        if ($res) {
            $data = [
                'code' => 200,
                'msg' => '添加成功'
            ];
        }

        return $this->api($data);

    }

    public function getQrcode($store_id, $id)
    {
        $this->wechat_app = AlbumManufacturerModel::where('store_id', $store_id)->first();
        $config = [
            'app_id' => $this->wechat_app->service_app_id,
            'secret' => $this->wechat_app->service_app_secret,

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $response = $app->app_code->getQrCode('pages/search/search?order_id=' . $id, 400);
        $path = public_path() . '/download';
        $qrcode = $response->save($path, $id);

        $real_path = $path . '/' . $qrcode;

        Image::make($real_path)->crop(423, 415, 0, 0)->save($real_path);
        if ($qrcode) {
            $qrcode = env('APP_URL') . '/download/' . $id . '.jpg';
            $order = AlbumOrderModel::find($id);
            $order->qrcode = $qrcode;
            $order->save();
            return true;
        } else {
            return false;
        }
    }

    public function addProgress($status, $store_id, $order_id)
    {
        $data = [
            'status' => $status,
            'order_id' => $order_id,
            'store_id' => $store_id
        ];
        if ($status == 2) {
            $data['description'] = '订单已开始生产';
        }
        if ($status == 3) {
            $data['description'] = '完成生产，订单已下发到包装部，等待发货';
        }
        if ($status == 4) {
            $data['description'] = '包装部已发货，请等待签收';
        }
        if ($status == 5) {
            $data['description'] = '已签收,感谢您选择本公司产品！';
        }
        if ($status == 6) {
            $data['description'] = '已评价';
        }

        return AlbumProgressModel::create($data);
    }

}