<?php
declare (strict_types=1);

namespace app\api\controller;

use app\api\model\{Goods as GoodsModel, Store as StoreModel};
use app\api\model\Region;
use app\api\service\{Goods as GoodsService, User as UserService};
use app\common\library\wechat\ShortLink;
use app\common\model\GoodsImage as GoodsImageModel;
use app\common\model\UploadFile as UploadFileModel;
use app\common\model\wxapp\Setting as WxappSettingModel;
use app\common\service\qrcode\Goods as GoodsPoster;
use cores\exception\BaseException;
use think\db\exception\DbException;
use think\response\Json;
use app\common\enum\goods\GoodsDeliveryTime;
use think\facade\Cache;
use EasyWeChat\Factory;
use app\api\service\Setting as SettingService;
use app\common\service\GoodsCateEs;
use app\common\service\Jd;

/**
 * 商品控制器
 * Class Goods
 * @package app\api\controller
 */
class Goods extends Controller
{

    /**
     * 商品列表
     * @return Json
     * @throws DbException
     */
    public function list(): Json
    {

        // 获取列表数据
        $model = new GoodsModel;
        $param = $this->request->param();
        //限制过滤条件-渠道
        $param['channels'] = $this->storeInfo['open_channel'] ? array_merge(['zy'], explode(",", $this->storeInfo['open_channel'])) : [];
        //$param['p_store_id'] = $this->storeInfo->p_store_id;
        $param['storeInfo'] = $this->storeInfo;
        //分类利润-利润率
        $param['fliter_condition'] = $this->storeInfo['fliter_condition'];
        if (isset($param['keyword']) && $param['keyword']) {
            $page = $this->request->param('page', 1);
            $pageSize = $this->request->param('pageSize', 10);
            $param['status'] = 10;
            $param['store_id'] = $this->storeId;
            $goodsService = new GoodsCateEs();
            $list = $goodsService->list($param, $page, $pageSize);
        } else {
            $list = $model->getList($param, 10);
        }
        
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 获取商品详情(详细信息)
     * @param int $goodsId 商品ID
     * @param bool $verifyStatus 是否验证商品状态(上架)
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws BaseException
     */
    public function detail(int $goodsId, bool $verifyStatus = true): Json
    {
        // wmc商品详情
        $model = new GoodsModel;
        $goodsInfo = $model->getDetails($goodsId, $verifyStatus, $this->storeInfo->toArray());

        if (!empty($goodsInfo['content'])) {
            $goodsInfo['content'] = str_ireplace('onload="if(this.width>750){this.height=this.height*(750.0/this.width); this.width = 750;}', '', $goodsInfo['content']);
        }
        //苏宁的商品不展示链接
        if ($goodsInfo['channel'] == 'sn') {
            $goodsInfo['link'] = "";
        }
        //获取商户id
        $merchantId = $goodsInfo['merchant_id'];
        $storeId = $goodsInfo['store_id'];
        //获取客服设置
        $service = new SettingService;
        $setting = $service->getGoodsCustomer($merchantId,$storeId);
        
        $goodsInfo['setting'] = $setting;
        //京东短链
        $jd = new Jd();
        $jd_short_url = $jd->getJdShortLink($goodsInfo['goods_no']);
        //获取商品短链
        $goodsInfo['jd_short_url'] = $jd_short_url;
        return $this->renderSuccess(['detail' => $goodsInfo]);
    }

    /**
     * 获取商品详情(详细信息)
     * @param int $goodsId 商品ID
     * @param bool $verifyStatus 是否验证商品状态(上架)
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws BaseException
     */
    public function getGoodsStock(): Json
    {
        // wmc商品详情
        $params = $this->request->param();
        if (!$params['list'] || !$params['province'] || !$params['city'] || !$params['district']) {
            return $this->renderError('参数错误!');
        }
        $return = [];
        foreach ($params['list'] as $value) {
            $res = "无货";
            $goods = GoodsModel::withoutGlobalScope()->where('goods_id', $value['goods_id'])->find();
            if (!$goods) {
                return $this->renderError('商品不存在');
            }
            //限制销售区域
            $city = Region::withoutGlobalScope()->where('name', $params['city'])->where('level', 2)->find();
            // var_dump($goods);
            // exit();
            if ($goods['region'] && !in_array($city->id, json_decode($goods['region']))) {
                $data = [
                    'state' => "无货",
                    'goods_name' => $goods['goods_name'],
                    'goods_id' => $goods['goods_id'],
                    'promise_info' => "预计".(GoodsDeliveryTime::data()[$goods['delivery_time']]['name'] ?? "72小时")."内发货",
                ];
                $return[] = $data;
                continue;
            }
            // var_dump($goods->channel);
            // exit();
            switch ($goods->channel) {
                case 'sn':
                case 'sn1':
                    //$city = Region::withoutGlobalScope()->where('name', $params['city'])->where('level', 2)->find();
                    $district = Region::withoutGlobalScope()->where('name', $params['district'])->where('level', 3)->find();
                    $suning = new \app\common\service\Suning();
                    $goods->num = $param['num'] ?? 1;
                    $data = $suning->shoppingCartPrice([$goods->toArray()], $city->sn_code, $district->sn_code);
                    $data['goods_name'] = $goods['goods_name'];
                    $data['goods_id'] = $goods['goods_id'];
                    //$data['promise_info'] = "预计".(GoodsDeliveryTime::data()[$goods['delivery_time']] ?? "72小时")."内发货";
                    $data['promise_info'] = "预计48小时内发货";
                    break;
                case 'jd':
                case 'jd1':
                case 'jd2':
                    $province = Region::withoutGlobalScope()->where('name', $params['province'])->where('level', 1)->find();
                    $district = Region::withoutGlobalScope()->where('name', $params['district'])->where('level', 3)->find();
                    $jd = new \app\common\service\Jd();
                    $arr = [];

                    $ret = $jd->getGoodsStock($province->jd_code, $city->jd_code, $district->jd_code, $goods['goods_no'], $value['num'] ?? 1);
                    // echo "<pre>";
                    // print_r($ret);
                    //var_dump($ret);
                    if ($ret) {
                        $res = $ret['stockResp']['desc'] ?? "无货";
                        if (strpos($res, "无货") !== false) {
                            $res = "无货";
                        } elseif (strpos($res, "有货") == false) {
                            $res = "有货";
                        }
                    }
                    $data = [
                        'state' => $res,
                        'goods_name' => $goods['goods_name'],
                        'goods_id' => $goods['goods_id'],
                        //'promise_info' => $ret['promiseInfo'] ?? "预计72小时内发货",
                        'promise_info' => "预计48小时内发货",
                    ];
                    break;
                default:
                    if ($goods->is_use_jd_stock) {//是否使用京东库存
                        $province = Region::withoutGlobalScope()->where('name', $params['province'])->where('level', 1)->find();
                        $district = Region::withoutGlobalScope()->where('name', $params['district'])->where('level', 3)->find();
                        $jd = new \app\common\service\Jd();
                        $arr = [];

                        $ret = $jd->getGoodsStock($province->jd_code, $city->jd_code, $district->jd_code, $goods['goods_no'], $value['num'] ?? 1);
                        // echo "<pre>";
                        // print_r($ret);
                        //var_dump($ret);
                        if ($ret) {
                            $res = $ret['stockResp']['desc'] ?? "无货";
                            if (strpos($res, "无货") !== false) {
                                $res = "无货";
                            } elseif (strpos($res, "有货") == false) {
                                $res = "有货";
                            }
                        }
                        $data = [
                            'state' => $res,
                            'goods_name' => $goods['goods_name'],
                            'goods_id' => $goods['goods_id'],
                            //'promise_info' => $ret['promiseInfo'] ?? "预计72小时内发货",
                            'promise_info' => "预计48小时内发货",
                        ];
                    } else {
                        if ($goods->stock_total >= ($value['num'] ?? 1)) {
                            $res = "有货";
                        }
                        $data = [
                            'state' => $res,
                            'goods_name' => $goods['goods_name'],
                            'goods_id' => $goods['goods_id'],
                            'promise_info' => "预计".(GoodsDeliveryTime::data()[$goods['delivery_time']]['name'] ?? "72小时")."内发货",
                        ];
                    }
                    

                    break;
            }
            $return[] = $data;
        }

        return $this->renderSuccess($return);
    }

    public function browseLog(): Json
    {
        $model = new GoodsModel;
        $goodsInfo = $model->browseLogList();
        return $this->renderSuccess($goodsInfo);
    }

    public function presale()
    {
        $param = $this->request->param();
        $model = new GoodsModel;
        $goodsInfo = $model->presale($param);
        if ($goodsInfo) {
            return $this->renderSuccess('预约成功');
        }
        return $this->renderError('您已经预约过了');
    }

    public function browseDel()
    {
        $param = $this->request->param();
        $model = new GoodsModel;
        $goodsInfo = $model->browseDel($param);
        if ($goodsInfo) {
            return $this->renderSuccess('删除成功');
        }
        return $this->renderError('删除失败');
    }

    public function presaleList()
    {
        $param = $this->request->param();
        $model = new GoodsModel;
        $list = $model->presaleList($param)->toArray();
        if (!$list) {
            return $this->renderSuccess(compact('list'));
        }
        foreach ($list['data'] as $key => &$value) {
            $goods_image = GoodsImageModel::where('goods_id', $value['goods_id'])->find();
            $file_path = UploadFileModel::where('file_id', $goods_image['image_id'])->find();
            $value['image'] = getUrl($file_path['file_path'], $file_path['domain']);
        }
        return $this->renderSuccess(compact('list'));
    }

    public function presaleCateList()
    {
        $param = $this->request->param();
        $model = new GoodsModel;
        $list = $model->presaleCateList($param);

        return $this->renderSuccess($list);
    }

    public function presaleGoodsList(): Json
    {
        $param = $this->request->param();
        $model = new GoodsModel;
        $list = $model->presaleGoods($param);
        return $this->renderSuccess(compact('list'));
    }


    public function canlpresale()
    {
        $param = $this->request->param();
        $model = new GoodsModel;
        $goodsInfo = $model->canlpresale($param);

        if ($goodsInfo) {
            return $this->renderSuccess('成功');
        }
        return $this->renderError('失败');
    }

    /**
     * 获取商品详情(基础信息)
     * @param int $goodsId 商品ID
     * @param bool $verifyStatus 是否验证商品状态(上架)
     * @return Json
     * @throws BaseException
     */
    public function basic(int $goodsId, bool $verifyStatus = true): Json
    {
        // 获取商品详情
        $model = new GoodsModel;
        $detail = $model->getBasic($goodsId, $verifyStatus);
        return $this->renderSuccess(compact('detail'));
    }

    /**
     * 获取商品规格数据
     * @param int $goodsId
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function specData(int $goodsId): Json
    {
        // 获取商品详情
        $model = new GoodsModel;
        $specData = $model->getSpecData($goodsId);
        return $this->renderSuccess(compact('specData'));
    }

    /**
     * 获取商品的指定SKU信息
     * @param int $goodsId 商品ID
     * @param string $goodsSkuId 商品SKU标识
     * @return Json
     */
    public function skuInfo(int $goodsId, string $goodsSkuId): Json
    {
        $skuInfo = GoodsService::getSkuInfo($goodsId, $goodsSkuId);
        return $this->renderSuccess(compact('skuInfo'));
    }

    /**
     * 推荐的商品列表
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recommended(): Json
    {
        $service = new GoodsService;
        $cache_key = "goods_recommended".$this->storeId.($this->user ? $this->user->user_type : 0);
        // if(Cache::has($cache_key)) {
        //    $goodsList = Cache::get($cache_key);
        //    return $this->renderSuccess(compact('goodsList'));
        // }
        $goodsList = $service->recommended();
        //Cache::set($cache_key, $goodsList, 60*60);
        return $this->renderSuccess(compact('goodsList'));
    }
    /**
     * 推荐的商品列表
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recommendedNew(): Json
    {

        $param = $this->request->param();
        $param['storeInfo'] = $this->storeInfo;
        $service = new GoodsService;
        
        $goodsList = $service->recommendedNew($param);
        return $this->renderSuccess(compact('goodsList'));
    }
    /**
     * 商品大牌和新品
     * @return Json
     */
    public function brandList(): Json
    {
        $service = new GoodsService;
        $goodsList = $service->brandList();
        return $this->renderSuccess($goodsList);
    }


    public function getCommonConfig(): Json
    {
        $service = new GoodsService;
        $storeInfo = StoreModel::info();
        if (empty($storeInfo)) {
            return $this->renderError("商铺信息不存在");
        }
        $type = intval($this->request->get('type', 1));
        $goodsList = $service->getCommonConfig($storeInfo, $type);
        return $this->renderSuccess($goodsList);
    }


    public function charts(): Json
    {
        $service = new GoodsService;
        $storeid = request()->header()['storeid'];
        $goodsList = $service->charts($storeid);
        return $this->renderSuccess($goodsList);
    }

    /**
     * 排行行查看更多
     * @return Json
     */
    public function chartsGoodsList(): Json
    {
        $service = new GoodsService;
        $storeid = request()->header()['storeid'];
        $goodsList = $service->chartsGoodsList($storeid);
        return $this->renderSuccess($goodsList);
    }

    /**
     * 首页分类商品排行榜 默认返回3条
     * @return Json
     */
    public function chartsGoodsJing(): Json
    {
        $service = new GoodsService;
        $goodsList = $service->chartsGoodsJing();
        return $this->renderSuccess($goodsList);
    }


    public function cityInfo(): Json
    {
        $service = new GoodsService;
        $storeId = $this->request->storeId();
        $goodsList = $service->cityInfo($storeId);
        return $this->renderSuccess($goodsList);
    }

    public function hotWord(): Json
    {
        $service = new GoodsService;
        $list = $service->hotWord($this->request->param('page'));
        return $this->renderSuccess($list);
    }


    /**
     * 生成商品海报
     * @param int $goodsId 商品ID
     * @param string $channel 二维码渠道(小程序码、h5码)
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function poster(int $goodsId, string $channel = 'H5'): Json
    {
        // 获取商品详情
        $model = new GoodsModel;
        $goodsInfo = $model->setEnableGradeMoney(false)->getBasic($goodsId);
        // 生成商品海报图
        $userId = UserService::getCurrentLoginUserId();
        $Qrcode = new GoodsPoster($goodsInfo, $userId, $channel);
        return $this->renderSuccess(['imageUrl' => $Qrcode->getImage()]);
    }

    public function shortUrl(): Json
    {
        $page_url = $this->request->post('page_url');
        if (empty($page_url)) {
            return $this->renderError('缺少参数page_url');
        }
        $page_url = urldecode($page_url);
        log_record("page_url".urldecode($page_url));
        //$page_url = "pages/goods/detail?refereeId=10472&goodsId=985456";
        $page_title = $this->request->post('page_title');
        if (empty($page_title)) {
            return $this->renderError('缺少参数page_title');
        }
        $store_id = GoodsModel::$storeId;
        $wxConfig = WxappSettingModel::getConfigBasic($store_id);
        $config = [
            'app_id' => $wxConfig['app_id'],
            'secret' => $wxConfig['app_secret'],
            'response_type' => 'array',// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
            'log' => [
                'level' => 'debug',
                'file' => app()->getRuntimePath().'wechat.log',
            ],
        ];
        $app = Factory::miniProgram($config);
        $data = $app->short_link->getShortLink($page_url, "", true);
        $url = "";
        if ($data['errcode'] == 0) {
            $url = $data['link'];
        }
       
        // 请求api获取短连接
        // $link_obj = new ShortLink($wxConfig['app_id'], $wxConfig['app_secret']);
        // $url = $link_obj->shortUrl($page_url, "");
        return $this->renderSuccess(['url' => $url]);
    }

    public function detailTest(int $goodsId, bool $verifyStatus = true): Json
    {
        // wmc商品详情
        $model = new GoodsModel;
        $goodsInfo = $model->getDetails($goodsId, $verifyStatus);
        
        if (!empty($goodsInfo['content'])) {
            $goodsInfo['content'] = str_ireplace('onload="if(this.width>750){this.height=this.height*(750.0/this.width); this.width = 750;}', '', $goodsInfo['content']);
        }
        //苏宁的商品不展示链接
        if ($goodsInfo['channel'] == 'sn') {
            $goodsInfo['link'] = "";
        }
        //获取商户id
        $merchantId = $goodsInfo['merchant_id'];
        $storeId = $goodsInfo['store_id'];
        //获取客服设置
        $service = new SettingService;
        $setting = $service->getGoodsCustomer($merchantId,$storeId);
        $goodsInfo['setting'] = $setting;
        return $this->renderSuccess(['detail' => $goodsInfo]);
    }

}