<?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\model\system\Attachment;
use app\Request;
use EasyWeChat\Factory;
use library\services\UtilService;
use library\services\QrcodeService;
use library\services\upload\Upload as Upload;
use think\facade\Db;

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){
        $where = UtilService::getMore([
            ['cid', 0],
            ['sort', ''],
            ['keyword', ''],
            ['page', 1],
            ['limit', 24]
        ], $request);
        $data = Product::getProductList($where);
        foreach ($data['list'] as $k => $v) {
            if($v['price'] == 0) {
                $data['list'][$k]['price'] = round($v['ot_price'] * 1.15, 2);
            }
            $data['list'][$k]['market_price'] = round($data['list'][$k]['price'] * 1.2, 2);
            $score = Db::name("product_score")->where('product_id', $v['id'])->find();
            if($score) {
                $attr = json_decode($score['attribute'], true);
                $max = $attr[2]['taobao'];
                if($attr[2]['t1688'] > $max)
                    $max = $attr[2]['t1688'];
                if($attr[2]['pdd'] > $max)
                    $max = $attr[2]['pdd'];
                if($attr[2]['dy'] > $max)
                    $max = $attr[2]['dy'];
                if($attr[2]['ks'] > $max)
                    $max = $attr[2]['ks'];
                if($attr[2]['other'] > $max)
                    $max = $attr[2]['other'];
                if($max && $max > $data['list'][$k]['market_price'])
                    $data['list'][$k]['market_price'] = $max;
            }
            if($v['label'] != ""){
                $data['list'][$k]['label'] = explode('、',$v['label']);
            }else{
                $data['list'][$k]['label'] = [];
            }
            $data['list'][$k]['saler'] = random_int(1, 100);
        }
        return app('json')->success($data);
    }

    /**
     * 商品详情
     * @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['saler'] = random_int(1, 100);
        $storeInfo['slider_image'] = json_decode($storeInfo['slider_image'], true);
        $storeInfo['detail_image'] = json_decode($storeInfo['detail_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']);
        if($storeInfo['price'] == 0){
            $storeInfo['price'] = round($storeInfo['ot_price'] * 1.15, 2);
        }
        $storeInfo['market_price'] = round($storeInfo['price'] * 1.2, 2);
        $score = Db::name("product_score")->where('product_id', $id)->find();
        if($score) {
            $attr = json_decode($score['attribute'], true);
            $max = $attr[2]['taobao'];
            if($attr[2]['t1688'] > $max)
                $max = $attr[2]['t1688'];
            if($attr[2]['pdd'] > $max)
                $max = $attr[2]['pdd'];
            if($attr[2]['dy'] > $max)
                $max = $attr[2]['dy'];
            if($attr[2]['ks'] > $max)
                $max = $attr[2]['ks'];
            if($attr[2]['other'] > $max)
                $max = $attr[2]['other'];
            if($max && $max > $storeInfo['market_price'])
                $storeInfo['market_price'] = $max;
        }
        $data['storeInfo'] = $storeInfo;
        list($productAttr, $productValue, $sku) = 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['sku'] = $sku;
        $data['priceName'] = 0;
        $data['good_list'] = Product::getGoodList(18, 'image,store_name,price,id,ot_price,stock,IFNULL(sales,0) + IFNULL(ficti,0) as fsales,unit_name');
        return app('json')->successful($data);
    }

    /**
     * 商品分享二维码
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function code(Request $request, $id)
    {
        if (!$id || !($storeInfo = Product::getValidProduct($id, 'id'))) return app('json')->fail('商品不存在或已下架');
        $uid = $request->user['uid'];
        try {
            //小程序
            $name = $id . '_' . $uid . '_product.jpg';
            $imageInfo = Attachment::getInfo($name, 'name');
            if (!$imageInfo) {
                $path = 'pages/product/detail';
                $query = 'id=' . $id . '&uid=' . $uid;
                $mini = Factory::miniProgram(config('weixin')['mini_program']);
                $res = $mini->app_code->getUnlimit($query, [
                    'page'  => $path,
                    'width' => 280
                ]);
                if (!$res) return app('json')->fail('二维码生成失败');
                $upload = new Upload(2,config('qiniu')['upload']);
                $res = $upload->to('routine/product')->validate()->stream($res, $name);
                if ($res === false) {
                    return app('json')->fail($upload->getError());
                }
                $imageInfo = $upload->getUploadInfo();
                $remoteImage = UtilService::remoteImage($imageInfo['dir']);
                if (!$remoteImage['status']) return app('json')->fail('小程序二维码未能生成');
                Attachment::attachmentAdd($imageInfo['name'], $imageInfo['size'], $imageInfo['type'], $imageInfo['dir'], $imageInfo['thumb_path'], 1, 2, $imageInfo['time'], 2);
                $url = $imageInfo['dir'];
            } else $url = $imageInfo['att_dir'];
            return app('json')->successful(['code' => $url]);
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage(), [
                'code' => $e->getCode(),
                'line' => $e->getLine(),
                'message' => $e->getMessage()
            ]);
        }
    }

}
