<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 22/05/04
 * Time: 22:00
 */

namespace App\Services\Api;

use App\Models\Goods;
use App\Models\GoodsAttr;
use App\Models\GoodsCat;
use App\Models\GoodsComment;
use App\Models\GoodsLook;
use App\Models\Order;
use App\Models\OrderComment;
use App\Models\User;
use App\Models\UserCollect;
use App\Models\UserMessage;
use App\Models\UserSearchLog;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;

class GoodsService
{
    //获取商品属性 1产地,2所在地,3容量,4桶型,5级别,6批次,7风味,8品牌
    public static function getCatList()
    {
        $list = GoodsAttr::query()
            ->whereNull('deleted_at')
            ->select('id', 'type', 'name')
            ->orderBy('type')
            ->get();

        $list = $list->isNotEmpty() ? $list->toArray() : [];
        $catList = [];
        $catList['cat_list'] = GoodsCat::query()->where('status', 1)->whereNull('deleted_at')->select('id', 'name', 'pic_url')->get();

        foreach ($list as $key => $val) {
            switch ($val['type']) {
                case 1: //原产地
                    $catList['origin_list'][] = $val;
                    break;
                case 2: //所在地
                    $catList['region_list'][] = $val;
                    break;
                case 3: //容量
                    $catList['capacity_list'][] = $val;
                    break;
                case 4: //桶型
                    $catList['barrel_list'][] = $val;
                    break;
                case 5: //级别
                    $catList['level_list'][] = $val;
                    break;
                case 6: //批次
                    $catList['batch_list'][] = $val;
                    break;
                case 7: //风味
                    $catList['flavor_list'][] = $val;
                    break;
                case 8: //品牌
                    $catList['brand_list'][] = $val;
                    break;
            }
        }

        return $catList;
    }

    //添加发布商品
    public static function add($request, $userId)
    {
        $goods = App::make('getGoodsInstance');

        $goods->user_id = $userId;
        $goods->name = $request->name; //名称
        $goods->is_old = $request->is_old; //新旧
        $goods->cat_id = $request->cat_id; //类别
        $goods->brand_id = $request->brand_id; //品牌
        $goods->barrel_id = $request->barrel_id; //桶型
        $goods->capacity_id = $request->capacity_id; //容量
        $goods->origin_place_id = $request->origin_place_id; //原产地
        $goods->region_id = $request->region_id; //所在地
        $goods->level_id = $request->level_id; //等级
        $goods->batch_id = $request->batch_id; //批次
        $goods->flavor_id = $request->flavor_id;  //风味
        $goods->alcohol_id = $request->alcohol_id;  //酒精度
        $goods->tag = $request->tag; //标签
        $goods->notice = $request->notice; //提示
        $goods->introduce = $request->introduce; //介绍
        $goods->price = $request->price; //价格
        $goods->img = $request->img; //图片
        $goods->cover_imgs = $request->cover_imgs; //封面图
        $goods->product_year = $request->product_year; //产品年份
        $goods->distill_year = $request->distill_year; //蒸馏年份
        $goods->bottling_year = $request->bottling_year; //装瓶年份

        $goods->pre_seller = $request->pre_seller ?: 0; //上一卖家(新品上架不填，售卖仓库商品必填)
        $goods->trace_code = $request->trace_code ?: self::createTraceCode($userId); //溯源码 (新品上架自动生成，售卖仓库商品填商品的)

        if (!$goods->save()) {
            return false;
        }

        return true;
    }

    //生成溯源码
    public static function createTraceCode()
    {
        return md5(date('YmdHis') . rand(1000, 9999));
    }

    //获取商品列表
    public static function getGoodsList($map = [], $page = 1, $limit = null, $ids = [])
    {
        $limit  = $limit ?: 20;
        $offset = ($page - 1) * $limit;
        $list = Goods::query()
            ->when($map, function ($query, $map) {
                $query->where($map);
            })
            ->when($ids, function ($query, $ids) {
                $query->whereIn('id', $ids);
            })
            ->select('id', 'name', 'img', 'integral')
            ->offset($offset)
            ->limit($limit)
            ->get();

        if($list->isEmpty()){
            return [];
        }
        $list->makeHidden(['created_at', 'updated_at', 'deleted_at']);

        return $list->toArray();
    }

    //获取详情
    public static function getDetail($goodsId)
    {
        $goods = Goods::query()
            ->where('id', $goodsId)
            ->whereNull('deleted_at')
            ->first();

        $goods->makeHidden(['created_at', 'updated_at', 'deleted_at']);
        $goods =  $goods->toArray();
        $goods['cover_imgs'] = json_decode($goods['cover_imgs'], true);
        $goods['specific_list'] = json_decode($goods['specific_list'], true);

        return $goods;
    }

    //获取历史购买者信息
    public static function getHistoryBuyers($goodsId)
    {
        $list = Order::query()
            ->with('users:id,username,avatar')
            ->where('goods_id', $goodsId)
            ->whereNull('deleted_at')
            ->select('user_id', 'unit_price', 'created_at')
            ->get();

        foreach ($list as $key => $val) {
            $val['date'] = date('Y-m-d', strtotime($val['created_at']));
            unset($val['created_at']);
            $list[$key] = $val;
        }

        return $list;
    }

    //获取历史价格纪录(需要修改)
    public static function getHistoryPrices($goodsId)
    {
        $list = Order::query()->where('goods_id', $goodsId)->whereNull('deleted_at')->select('unit_price', 'created_at')->get();

        foreach ($list as $key => $val) {
            $val['date'] = date('Y-m-d', strtotime($val['created_at']));
            unset($val['created_at']);
            $list[$key] = $val;
        }

        return $list;
    }

    //获取商品收藏记录
    public static function getGoodsCollects($goodsId)
    {
        $date = Carbon::parse()->subDays(7)->toDateTimeString();

        $list = UserCollect::query()
            ->with('users:id,username,avatar')
            ->where('goods_id', $goodsId)
            ->where('status', 1)
            ->where('created_at', '>', $date)
            ->select('user_id', 'created_at')
            ->get();

        foreach ($list as $key => $val) {
            $val['date'] = date('Y-m-d', strtotime($val['created_at']));
            unset($val['created_at']);
            $list[$key] = $val;
        }

        $totalCount = UserCollect::query()->where('goods_id', $goodsId)->where('status', 1)->count('id');

        $result = [
            'list' => $list,
            'seven_count' => count($list),
            'total_count' => $totalCount
        ];

        return $result;
    }

    //获取用户浏览记录（七日）
    public static function getGoodsLooks($goods_id)
    {
        $date = Carbon::parse()->subDays(7)->toDateTimeString();
        $list = GoodsLook::query()
            ->where('goods_id', $goods_id)
            ->select(DB::raw('DATE(created_at) as date'), DB::raw('COUNT(id) as amount'))
            ->groupBy('date')
            ->having('date', '>', $date)
            ->orderBy('date', 'ASC')
            ->get();

        $list = $list->isNotEmpty() ? $list->toArray() : [];

        $sevenCount = array_sum(array_column($list, 'amount'));

        for ($i = 0; $i < 7; $i++) {
            $day = Carbon::parse('-' . $i . ' days')->toDateString();
            $arr = ['date' => $day, 'amount' => 0];
            foreach ($list as $key => $val) {
                if ($day == $val['date']) {
                    $arr['amount'] = $val['amount'];
                }
            }
            $arr['date'] = date('d', strtotime($day));
            $res[] = $arr;
        }

        $result = [
            'list' => $res,
            'seven_count' => $sevenCount
        ];

        return $result;
    }

    //商品 收藏/取消
    public static function collectGoods($goodsId, $userId)
    {
        DB::beginTransaction();
        try {
            $collect = UserCollect::query()->where(['user_id' => $userId, 'goods_id' => $goodsId])->first();
            if ($collect) {
                $status = $collect->status;
                $collect->status = $status ? 0 : 1;
                $collect->save();
                if ($status) {
                    self::collectNumDec($goodsId);
                    UserService::collectNumDec($userId);
                } else {
                    self::collectNumInc($goodsId);
                    UserService::collectNumInc($userId);
                }
            } else {
                $collect = App::make('getUserCollectInstance');
                $collect->user_id = $userId;
                $collect->goods_id = $goodsId;
                $collect->status = 1;
                $collect->save();
                self::collectNumInc($goodsId); //商品被收藏数 +1
                UserService::collectNumInc($userId); //用户收藏商品数 +1
            }
            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            ErrorMsgServive::write($exception, request()->fullUrl());
            return false;
        }
    }

    //收藏数+1
    public static function collectNumInc($goodsId)
    {
        Goods::query()->where('id', $goodsId)->increment('collect_num');
    }

    //收藏数-1
    public static function collectNumDec($goodsId)
    {
        Goods::query()->where('id', $goodsId)->decrement('collect_num');
    }

    //增加曝光量
    public static function addOpenNum($goodsId)
    {
        Goods::query()->where('id', $goodsId)->increment('open_num');
    }

    //增加浏览记录
    public static function addGoodsLook($userId, $goodsId)
    {
        $goodsLook = App::make('getGoodsLookInstance');
        $goodsLook->user_id = $userId;
        $goodsLook->goods_id = $goodsId;
        $goodsLook->save();
    }

    //商品是否可买
    public static function isGoodsCanBuy($goodsId)
    {
        $info = Goods::query()->where('id', $goodsId)->where('status', 1)->whereNull('deleted_at')->first();

        return empty($info) ? false : $info;
    }

    //通过商品名 模糊搜索商品id
    public static function getGoodsIds($keyword)
    {
        $ids = Goods::query()
            ->where('name', 'like', '%' . $keyword . '%')
            ->pluck('id');

        return $ids->isNotEmpty() ? array_unique($ids->toArray()) : [];
    }

    //我售卖的商品id
    public static function mySellGoodsIds($userId)
    {
        $ids = Goods::query()
            ->where('user_id', $userId)
            ->pluck('id');

        return $ids->isNotEmpty() ? array_unique($ids->toArray()) : [];
    }

    //添加评论
    public static function addComment($request, $userId)
    {
        $goods = Goods::find($request->goods_id);

        $comment = App::make('getGoodsCommentInstance');
        $comment->user_id = $userId;
        $comment->goods_id = $request->goods_id;
        $comment->goods_user_id = $goods->user_id; //售卖商品的人
        $comment->score = $request->score;
        $comment->content = $request->content;
        $comment->pic_url = $request->pic_url;
        if (!$comment->save()) {
            return false;
        }
        //商品被评价进行消息通知
        $type = 'comment';
        $user = User::find($userId);
        $content = $user->username.'评价了您的商品';
        MessageService::sendNotice($goods->user_id, $userId, $type, UserMessage::TYPE[$type], $content);

        return true;
    }

    //获取评论列表 $type: 1全部，2买家评论，卖家评论
    public static function getCommentList($userId, $type = null, $page = 1)
    {
        $limit = 20;
        $offset = ($page - 1) * $limit;

        $list = GoodsComment::query()
            ->with('users:id,username,name,avatar')
            ->with('goods:id,name,img,price')
            ->where('user_id', $userId)
            ->where('is_show', 1)
            ->offset($offset)
            ->limit($limit)
            ->orderByDesc('is_top')
            ->get();

        foreach ($list as $key => $val) {
            $format = CommonService::formatTime($val['created_at']);
            $val['date_format_1'] = $format['date_format_1'];
            $val['date_format_2'] = $format['date_format_2'];
            $val['date_format_3'] = $format['date_format_3'];
            $list[$key] = $val;
        }

        return $list;
    }

}
