<?php

namespace app\api\controller\v1;

use app\BaseController;
use app\model\api\Product;
use app\model\system\Category as CategoryModel;
use app\model\system\ProductAttr;
use app\Request;
use library\services\UtilService;
use library\services\QrcodeService;

class Index extends BaseController
{
    /**
     * 获取产品分类
     */
    public function getCategory(){
        $category = new CategoryModel();
        $menus = $category->getArMenu('',0,1);
        return app('json')->success($menus);
    }

    /**
     * 获取产品标签
     */
    public function getKeyword($cid){
        $data = Product::where('is_del', 0)->where('is_show', 1)->where('cate_id',$cid)->where('keyword','<>',"")->group('keyword')->column('keyword');
        $keyword = [];
        foreach ($data as $k => $v) {
            $arr = explode('、',$v);
            $keyword = array_merge($keyword, $arr);
        }
        $keyword = array_unique($keyword);
        return app('json')->success($keyword);
    }

    /**
     * 获取产品列表
     */
    public function productList(Request $request){
        $data = UtilService::getMore([
            ['cid', 0],
            ['sort', ''],
            ['keyword', ''],
            ['page', 1],
            ['limit', 24]
        ], $request);
        $list = Product::getProductList($data);
        return app('json')->success($list);
    }

    /**
     * 商品详情
     * @param Request $request
     * @param $id
     * @param int $type
     * @return mixed
     */
    public function productDetail(Request $request, $id)
    {
        if (!$id || !($storeInfo = Product::getValidProduct($id))) return app('json')->fail('商品不存在或已下架');
        $storeInfo['slider_image'] = json_decode($storeInfo['slider_image'], true);
        $storeInfo['code_base'] = QrcodeService::getWechatQrcodePath($id . '_product_detail_wap.jpg', '/h5/pages/product/detail?id=' . $id);
        //替换windows服务器下正反斜杠问题导致图片无法显示
        $storeInfo['description'] = preg_replace_callback('#<img.*?src="([^"]*)"[^>]*>#i', function ($imagsSrc) {
            return isset($imagsSrc[1]) && isset($imagsSrc[0]) ? str_replace($imagsSrc[1], str_replace('\\', '/', $imagsSrc[1]), $imagsSrc[0]) : '';
        }, $storeInfo['description']);
        $data['storeInfo'] = $storeInfo;
        list($productAttr, $productValue) = ProductAttr::getProductAttrDetail($id, 0, 0);
        $data['productAttr'] = $productAttr;
        $prices = array_column($productValue, 'price');
        array_multisort($prices, SORT_ASC, SORT_NUMERIC, $productValue);
        $keys = array_keys($productValue);
        $productValue = array_combine($keys, $productValue);
        $data['productValue'] = $productValue;
        $data['priceName'] = 0;
        $data['good_list'] = Product::getGoodList(18, 'image,store_name,price,id,ot_price');
        return app('json')->successful($data);
    }

}
