<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\BaseController;
use App\Models\Good as GoodModel;
use App\Models\GoodSku;
use App\Models\UserCollect;
use App\Models\Category as CategoryModel;
use App\Models\GoodsAttr as GoodsAttrModel;
use App\Models\Kefu;
use App\Models\Merchant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class GoodController extends BaseController
{
    public function getCatGoodList(Request $request)
    {
        $cat_id = $request->cat_id ?? null;
        $pid = $request->pid ?? null;
        $kw = $request->kw ?? null;
        $order = $request->order ?? 'time';
        $sort = $request->sort ?? 'desc';
        $page = $request->page ?? 1;
        $limit = $request->limit ?? 10;
        $data = [
            'current_page' => $page,
            'total' => 0,
            'total_page' => 0,
            'list' => []
        ];
        //一级分类
        $FirstCat = CategoryModel::select(['id', 'title'])->where('parent_id', 0)->get();
        $data['firstCat'] = $FirstCat;
        if (!$pid) {
            $firstArr = $FirstCat->toArray();
            $pid = $firstArr[0]['id'];
        }

        $model = GoodModel::select(['id', 'goods_name', 'cover_img', 'goods_brief'])
            ->where(['is_show' => 1]);
        if ($cat_id) {
            $model = $model->where(['cat_id' => $cat_id]);
        }
        if ($kw) {
            $model = $model->where("goods_name", 'like', "%" . $kw . "%");
        }
        $order_by = '';
        if ($order == 'time') {
            $order_by = 'created_at';
        } else {
            $order_by = 'goods_price';
        }
        $data['total'] = $model->count();
        $data['total_page'] = ceil($data['total'] / $limit);
        //$listData = $model->paginate(10);
        $listData = $model->offset(($page - 1) * $limit)->limit($limit)->orderBy($order_by, $sort)->get();
        if ($listData->toArray()) {
            foreach ($listData as $datum) {
                $data['list'][] = [
                    'id' => $datum->id,
                    'goods_name' => $datum->goods_name,
                    'goods_price' => $datum->goods_price,
                    'goods_brief' => $datum->goods_brief,
                    'cover_img' => $datum->cover_img ? env('IMAGE_URL') . $datum->cover_img : '',
                ];
            }
        }
        return $this->JsonResponse($data);
    }
    public function getList(Request $request)
    {
        $kw = $request->kw ?? null;
        $order = $request->order ?? 'time';
        $sort = $request->sort ?? 'desc';
        $page = $request->page ?? 1;
        $limit = $request->limit ?? 10;
        $islogin = $request->islogin ?? 0;
        $mer_id = 0;
        // 获取已认证的用户,如果未认证则返回 null
        $userObj = optional(Auth::user());
        if ($userObj) {
            $mer_id = $userObj->merchant_id;
        }
        $data = [
            'current_page' => $page,
            'total' => 0,
            'total_page' => 0,
            'list' => []
        ];

        $model = GoodModel::select(['id', 'goods_name', 'cover_img', 'goods_brief', 'sku', 'tags'])
            ->where(['is_show' => 1]);
        if ($kw) {
            $model = $model->where("goods_name", 'like', "%" . $kw . "%");
        }
        $order_by = '';
        if ($order == 'time') {
            $order_by = 'created_at';
        } else {
            $order_by = 'goods_price';
        }
        $data['total'] = $model->count();
        $data['total_page'] = ceil($data['total'] / $limit);
        $listData = $model->offset(($page - 1) * $limit)->limit($limit)
            ->orderBy("sort", "desc")
            ->orderBy($order_by, $sort)
            ->get();
        if ($listData->toArray()) {
            foreach ($listData as $item) {
                $goodsObj = GoodModel::find($item->id);
                $skufield = $item->sku ? json_decode($item->sku, true) : [];
                $cg_price = $market_price = 0;
                if (isset($skufield['sku'][0]['cg_price'])) {
                    $cg_price = $skufield['sku'][0]['cg_price'];
                }
                if (isset($skufield['sku'][0]['market_price'])) {
                    $market_price = $skufield['sku'][0]['market_price'];
                }
                //标签
                $tags = $item->tags ? json_decode($item->tags, true) : [];
                $data['list'][] = [
                    'id' => $item->id,
                    'goods_name' => $item->goods_name,
                    'dg_price' => sprintf("%.2f", $cg_price),
                    'market_price' => sprintf("%.2f", $market_price),
                    'goods_price' => $mer_id ? sprintf("%.2f", $cg_price) : sprintf("%.2f", $market_price),
                    'tags' => $tags,
                    'cover_img' => (isset($goodsObj->cover_img) ? env('IMAGE_URL') . $goodsObj->cover_img : ''),
                ];
            }
        }
        return $this->JsonResponse($data);
    }

    //推荐商品
    public function getIndexGoods(Request $request)
    {
        $kw = $request->kw ?? null;
        $order = $request->order ?? 'time';
        $sort = $request->sort ?? 'desc';
        $page = $request->page ?? 1;
        $limit = $request->limit ?? 10;
        //$islogin = $request->islogin ?? 0;
        $mer_id = 0;
        $data = [];
        // 获取已认证的用户,如果未认证则返回 null
        $userObj = optional(Auth::user());
        if ($userObj) {
            $mer_id = $userObj->merchant_id;
        }

        $model = GoodModel::select(['id', 'goods_name', 'is_hot', 'cover_img', 'goods_brief', 'sku', 'tags'])
            ->where(['is_show' => 1]);
        if ($kw) {
            $model = $model->where("goods_name", 'like', "%" . $kw . "%");
        }

        $order_by = '';
        if ($order == 'time') {
            $order_by = 'created_at';
        }
        $total = $model->count();
        $data = [
            'total' => $total,
            'total_page' => ceil($total / $limit),
            'list' => []
        ];
        $listData = $model->offset(($page - 1) * $limit)->limit($limit)
            ->orderBy("is_hot", "desc")
            ->orderBy("sort", "desc")
            ->orderBy($order_by, $sort)
            //->orderBy("id", "desc")
            ->get();
        if ($listData->toArray()) {
            foreach ($listData as $datum) {
                $skufield = $datum->sku ? json_decode($datum->sku, true) : [];
                $dg_price = $market_price = 0;
                if (isset($skufield['sku'][0]['cg_price'])) {
                    $dg_price = $skufield['sku'][0]['cg_price'];
                }
                if (isset($skufield['sku'][0]['market_price'])) {
                    $market_price = $skufield['sku'][0]['market_price'];
                }
                //标签
                $tags = $datum->tags ? json_decode($datum->tags, true) : [];
                $data['list'][] = [
                    'id' => $datum->id,
                    'goods_name' => $datum->goods_name,
                    'is_hot' => $datum->is_hot,
                    'dg_price' => sprintf("%.2f", $dg_price),
                    'market_price' => sprintf("%.2f", $market_price),
                    'goods_price' => $mer_id ? sprintf("%.2f", $dg_price) : sprintf("%.2f", $market_price),
                    'tags' => $tags,
                    'cover_img' => ($datum->cover_img) ? env('IMAGE_URL') . $datum->cover_img : '',
                ];
            }
        }
        return $this->JsonResponse($data);
    }


    public function getDetail(Request $request)
    {
        $mer_id =  0; //获取绑定的商户ID
        $goods_id = $request->goods_id ?? null;
        $goods = GoodModel::find($goods_id);
        if (!$goods) {
            return $this->JsonResponse('', '参数错误', 201);
        }
        $is_collect = 0;
        //客服电话
        $kefuObj = Kefu::where('is_type', 2)->first();
        $kf_phone = $kefuObj ? $kefuObj->contact : '';
        // 获取已认证的用户,如果未认证则返回 null
        $userObj = optional(Auth::user());
        if ($userObj) {
            $mer_id = $userObj->merchant_id;
            if ($mer_id) {
                $merchantObj = Merchant::find($mer_id);
                $kf_phone = $merchantObj->phone;
            }
            //收藏
            $is_collect = UserCollect::where(['goods_id' => $goods_id, 'uid' => $userObj->id])->wherenull('deleted_at')->count();
        }
        $cover_arr = $goods->carousel ? json_decode($goods->carousel) : [];
        $cover = [];
        if (!empty($cover_arr)) {
            foreach ($cover_arr as $item) {
                $cover[] = env('IMAGE_URL') . $item;
            }
        }

        $skufield = $goods->sku ? json_decode($goods->sku, true) : [];
        $attrsVal = isset($skufield['attrs']) ? array_values($skufield['attrs']) : [];
        $skuOneData =  isset($skufield['sku'][0]) ? $skufield['sku'][0] : [];
        $attr_txt = '';
        $tmp = $attr = [];
        if (isset($skufield['attrs'])) {
            foreach ($skufield['attrs'] as $kk => $val) {
                $tmp['tname'] = $kk;
                $tmp['selectedItem'] = 0;
                $tmp['tval'] = $val;
                array_push($attr, $tmp);
            }
        }
        //规格默认选中 第一条值
        foreach ($attrsVal as $item) {
            $attr_txt .= $item[0] . ", ";
        }
        $market_price = isset($skuOneData['market_price']) ?  sprintf("%.2f", $skuOneData['market_price']) : '';
        $dg_price = isset($skuOneData['cg_price']) ?  sprintf("%.2f", $skuOneData['cg_price']) : '';
        $stock = isset($skuOneData['stock']) ?  $skuOneData['stock'] : 0;
        //标签
        $tags = $goods->tags ? json_decode($goods->tags, true) : [];
        $skuOne = [
            'goods_price' => $mer_id ? $dg_price : $market_price,
            'stock' => $stock,
            'pic' => isset($skuOneData['pic']) ? $skuOneData['pic'] : ''
        ];
        $data = [
            'id' => $goods->id,
            'goods_img' => $cover,
            'goods_price' => $mer_id ? $dg_price : $market_price,
            'market_price' => $mer_id  ? $market_price : '',
            'stock' => $stock,
            'goods_name' => $goods->goods_name,
            'sale' => $goods->sale ?? 0,
            //'sku_items' => $skufield,
            'skuOne' => $skuOne,
            'attr' => $attr,
            'attr_txt' => trim($attr_txt, ", "),
            'is_collect' => $is_collect,
            'kf_phone' => $kf_phone,
            'tags' => $tags,
            'goods_desc' => $goods->goods_desc ?? '',
            'intro_desc' => $goods->intro_desc ?? '',
            'high_opinion' => $goods->high_opinion ?? '',
        ];
        return $this->JsonResponse($data);
    }

    public function getAttrKey(Request $request)
    {
        $goods_id = $request->goods_id ?? null;
        $attr_name = $request->attr_name ?? null; //22寸,蓝色,
        $mer_id = 0;
        $goods = GoodModel::find($goods_id);
        if (!$goods) {
            return $this->JsonResponse('', '参数错误', 201);
        }
        // 获取已认证的用户,如果未认证则返回 null
        $userObj = optional(Auth::user());
        if ($userObj) {
            $mer_id = $userObj->merchant_id;
        }

        $attr_sn = '';
        if ($attr_name) {
            $attrArr = explode(",", $attr_name);
            utf8_array_asort($attrArr);
            $attrStr = join("、", $attrArr);
            $attr_sn = md5($attrStr);
        }
        if (!$attr_sn) {
            return $this->JsonResponse('', '参数错误', 201);
        }

        $attrObj = GoodSku::where('goods_id', $goods_id)->where("attr_sn", $attr_sn)->first();
        if (!$attrObj) {
            return $this->JsonResponse('', '参数错误', 201);
        }
        $market_price = $attrObj->market_price ? $attrObj->market_price : 0;
        $cg_price = $attrObj->cg_price ? $attrObj->cg_price : 0;
        $stock = $attrObj->stock ? $attrObj->stock : 0;

        $data = [
            // 'market_price' => sprintf('%.2f', $market_price),
            // 'dg_price' => sprintf('%.2f', $cg_price),
            'goods_price' => $mer_id ? sprintf('%.2f', $cg_price) : sprintf('%.2f', $market_price),
            'stock' => $stock,
            'pic' => $attrObj->pic ? env('IMAGE_URL') . $attrObj->pic  : ''
        ];
        return $this->JsonResponse($data);
    }

    public function isCollect(Request $request)
    {
        $user_id = $request->user()->id;
        $goods_id = $request->goods_id ?? null;
        //收藏
        $is_collect = 0;
        $where = [
            'goods_id' => $goods_id,
            'uid' => $user_id,
            'deleted_at' => null,
        ];
        $is_collect = UserCollect::where($where)->count();

        return $this->JsonResponse(['is_collect' => $is_collect]);
    }
}