// +---------------------------------------------------------------------- declare (strict_types=1); namespace app\store\controller; use think\db\exception\DbException; use think\response\Json; use cores\exception\BaseException; use app\store\model\Goods as GoodsModel; use app\store\model\goods\Import as ImportModel; use app\common\model\GoodsCategoryRel; use app\common\model\Category; use app\common\model\Tipoff as ModelTipoff; use app\job\controller\goods\StoreGoodsOffline as StoreGoodsOfflineJob; use app\job\controller\goods\StoreGoodsOnline as StoreGoodsOnlineJob; use app\job\controller\goods\StoreGoodsDelete as StoreGoodsDeleteJob; use app\common\service\Jd; use app\common\model\wxapp\Setting as WxappSettingModel; use EasyWeChat\Factory; /** * 商品管理控制器 * Class Goods * @package app\store\controller */ class Goods extends Controller { private static $show_content = "***"; public function getJdShortLink(int $goodsId): Json { $model = new GoodsModel; $goodsInfo = $model->getDetail($goodsId); $jd = new Jd(); //京东短链 $jd_short_url = $jd->getJdShortLink($goodsInfo->goods_no); return $this->renderSuccess(compact('jd_short_url')); } /** * 商品列表 * @return Json * @throws DbException */ public function list(): Json { // 获取列表记录 $model = new GoodsModel; $params = $this->request->param(); //$params['channel'] = 'zy'; if (!isset($params['merchant_id']) || !$params['merchant_id']) { $params['merchant_id'] = $this->merchantId; } $params['storeInfo'] = $this->storeInfo; $list = $model->getList($params, (int)$this->request->param('pageSize', 15)); if ($list->isEmpty()) { return $this->renderSuccess(compact('list')); } $list = $list->toArray(); foreach ($list['data'] as &$value) { if (!in_array($value['channel'], ['zy'])) { // $value['goods_price_min'] = self::$show_content; // $value['goods_price_max'] = self::$show_content; // $value['line_price_max'] = self::$show_content; // $value['line_price_min'] = self::$show_content; // $value['cost_price_min'] = self::$show_content; $value['goods_no'] = self::$show_content; } } return $this->renderSuccess(compact('list')); } /** * 根据商品ID集获取列表记录 * @param array $goodsIds * @return Json */ public function listByIds(array $goodsIds): Json { // 获取列表记录 $model = new GoodsModel; $list = $model->getListByIds($goodsIds); return $this->renderSuccess(compact('list')); } /** * 商品详情(详细信息) * @param int $goodsId * @return Json * @throws BaseException * @throws \think\db\exception\DataNotFoundException * @throws DbException * @throws \think\db\exception\ModelNotFoundException */ public function detail(int $goodsId): Json { // 获取商品详情 $model = new GoodsModel; $goodsInfo = $model->getDetail($goodsId); if (!in_array($goodsInfo['channel'], ['zy'])) { // $goodsInfo['goods_price_min'] = self::$show_content; // $goodsInfo['goods_price_max'] = self::$show_content; // $goodsInfo['line_price_max'] = self::$show_content; // $goodsInfo['line_price_min'] = self::$show_content; // $goodsInfo['cost_price_min'] = self::$show_content; $goodsInfo['goods_no'] = self::$show_content; // foreach ($goodsInfo['skuList'] as $key => &$value) { // $value['goods_price'] = self::$show_content; // $value['cost_price'] = self::$show_content; // } } return $this->renderSuccess(compact('goodsInfo')); } /** * 商品详情(基础信息) * @param int $goodsId * @return Json * @throws BaseException * @throws \think\db\exception\DataNotFoundException * @throws DbException * @throws \think\db\exception\ModelNotFoundException */ public function basic(int $goodsId): Json { // 获取商品详情 $model = new GoodsModel; $detail = $model->getBasic($goodsId); return $this->renderSuccess(compact('detail')); } /** * 添加商品 * @return Json * @throws BaseException * @throws \think\db\exception\DataNotFoundException * @throws DbException * @throws \think\db\exception\ModelNotFoundException */ public function add(): Json { $model = new GoodsModel; $postform = $this->postForm(); $postform['merchant_id'] = $this->merchantId; if ($model->add($postform)) { return $this->renderSuccess('添加成功'); } return $this->renderError($model->getError() ?: '添加失败'); } /** * 商品编辑 * @param int $goodsId * @return Json * @throws BaseException * @throws \think\db\exception\DataNotFoundException * @throws DbException * @throws \think\db\exception\ModelNotFoundException */ public function edit(int $goodsId): Json { // 商品详情 $model = GoodsModel::detail($goodsId); $params = $this->postForm(); if ($model->isEmpty()) { return $this->renderError("该商品已不存在!"); } if (!in_array($model->channel, ['zy'])) { $params['goods_price'] = $model->goods_price_min; $params['cost_price'] = $model->cost_price_min; $params['goods_no'] = $model->goods_no; } // echo "
";
        // print_r($params);
        // print_r($model->toArray());
        // exit();
        $params['data_type'] = $model->data_type;
        // 更新记录
        if ($model->edit($params)) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }
    /**
     * 商品入池、出池
     * @param array $goodsIds 商品id集
     * @param bool $state 为true表示上架
     * @return Json
     */
    public function pool(array $goodsIds, bool $state): Json
    {
        $model = new GoodsModel;
        //过滤其他渠道的商品,只能把自营商品加入商品池
        $list = GoodsModel::whereIn('goods_id', $goodsIds)->where('channel','zy')->select();
        if (!$list) {
            return $this->renderError("没有需要加入商品池的自营商品");
        }
        $goodsIds = array_column($list->toArray(), "goods_id");
        $state = $state ? 1 : 2;
        if (!$model->setIsPool($goodsIds, $state)) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        // 分批每次导入20条
        $limit = 20;
        // 根据商品总数量计算需要的队列任务数量
        $jobCount = \count($goodsIds) / $limit;
        // 逐次发布队列任务
        for ($i = 0; $i < $jobCount; $i++) {
            $data = array_slice($goodsIds, $i * $limit, $limit);
            if ($state == 2) {
                StoreGoodsOfflineJob::dispatch([
                        'list' => $data,
                    ]);
                
            } elseif ($state == 1) {
                StoreGoodsOnlineJob::dispatch([
                        'list' => $data,
                    ]);
            }
        }
        return $this->renderSuccess('操作成功');
    }
    /**
     * 修改商品状态(上下架)
     * @param array $goodsIds 商品id集
     * @param bool $state 为true表示上架
     * @return Json
     */
    public function state(array $goodsIds, bool $state): Json
    {
        $model = new GoodsModel;
        if (!$model->setStatus($goodsIds, $state)) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        // 分批每次导入20条
        $limit = 20;
        // 根据商品总数量计算需要的队列任务数量
        $jobCount = \count($goodsIds) / $limit;
        // 逐次发布队列任务
        for ($i = 0; $i < $jobCount; $i++) {
            $data = array_slice($goodsIds, $i * $limit, $limit);
            if ($state == false) {
                StoreGoodsOfflineJob::dispatch([
                        'list' => $data,
                    ]);
                
            } elseif ($state == true) {
                StoreGoodsOnlineJob::dispatch([
                        'list' => $data,
                    ]);
            }
        }
        return $this->renderSuccess('操作成功');
    }
    /**
     * 修改商品状态(上下架)
     * @param array $goodsIds 商品id集
     * @param bool $state 为true表示上架
     * @return Json
     */
    public function setBrand(array $goodsIds, bool $is_brand): Json
    {
        $model = new GoodsModel;
        if (!$model->setBrand($goodsIds, $is_brand)) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('操作成功');
    }
    /**
     * 修改商品状态(上下架)
     * @param array $goodsIds 商品id集
     * @param bool $state 为true表示上架
     * @return Json
     */
    public function setNew(array $goodsIds, bool $is_new): Json
    {
        $model = new GoodsModel;
        if (!$model->setNew($goodsIds, $is_new)) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('操作成功');
    }
    /**
     * 修改商品状态(上下架)
     * @param array $goodsIds 商品id集
     * @param bool $state 为true表示上架
     * @return Json
     */
    public function setInstore(array $goodsIds, bool $is_in_store): Json
    {
        $model = new GoodsModel;
        if (!$model->setInstore($goodsIds, $is_in_store)) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('操作成功');
    }
    /**
     * 修改商品状态(上下架)
     * @param array $goodsIds 商品id集
     * @param bool $state 为true表示上架
     * @return Json
     */
    public function setRank(array $goodsIds, int $paihang): Json
    {
        $model = new GoodsModel;
        if (!$model->setRank($goodsIds, $paihang)) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('操作成功');
    }
    /**
     * 商品归类
     * @param array $goodsIds 商品id集
     * @param bool $state 为true表示上架
     * @return Json
     */
    public function category(array $goodsIds, array $categoryIds): Json
    {
        $model = new GoodsModel;

        foreach ($goodsIds as $key => $goodsId) {
            $categoryIds = $model->dealCategory($categoryIds);
            \app\store\model\GoodsCategoryRel::updates($goodsId, $categoryIds);
        }
        $model->whereIn('goods_id', $goodsIds)->update(['cate_status'=>1,'update_time' => time()]);
        return $this->renderSuccess('操作成功');
    }
    /**
     * 删除商品
     * @param array $goodsIds
     * @return Json
     */
    public function delete(array $goodsIds): Json
    {
        $model = new GoodsModel;
        if (!$model->setDelete($goodsIds)) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        // 分批每次导入20条
        $limit = 20;
        // 根据商品总数量计算需要的队列任务数量
        $jobCount = \count($goodsIds) / $limit;
        // 逐次发布队列任务
        for ($i = 0; $i < $jobCount; $i++) {
            $data = array_slice($goodsIds, $i * $limit, $limit);
            StoreGoodsDeleteJob::dispatch([
                    'list' => $data,
                ]);
        }
        return $this->renderSuccess('删除成功');
    }
    public function export(){
        ini_set('memory_limit', '2024M');
        set_time_limit(0);
        $model = new GoodsModel;
        $params = $this->request->param();
        $params['store_id'] = $this->storeId;
        $perSize = 10000;
        $params['page'] = 1;
        if ($this->merchantId) {
            $params['merchantId'] = $this->merchantId;
        }
        //$params['channels'] = ['zy'];
        // echo "
";
        // print_r($params);
        //exit();
        $data = $model->getAdminListExport($params, $perSize)->toArray();
        // echo "
";
        // print_r($data['data']);
        // exit();
        if ($data['data']) {
            foreach ($data['data'] as &$value) {
                if (!in_array($value['channel'], ['zy'])) {
                    $value['goods_price_min'] = self::$show_content;
                    $value['goods_price_max'] = self::$show_content;
                    $value['line_price_max'] = self::$show_content;
                    $value['line_price_min'] = self::$show_content;
                    $value['cost_price_min'] = self::$show_content;
                    $value['goods_no'] = self::$show_content;
                }
                $cates = GoodsCategoryRel::where('goods_id', $value['goods_id'])->select()->toArray();
                $value['category_id'] = $cates ? implode(",", array_column($cates, "category_id")) : "";
                $region_text = $value['region_text'] ? json_decode($value['region_text'], true) : [];
                $str = "";
                $link = ";";
                $replace = "、";
                if ($region_text) {
                    foreach ($region_text as $key => $val) {
                        if (!$val['citys']) {
                            $str .= $val['name'].$link;
                        } else {
                            foreach ($val['citys'] as $key => $va) {
                                $str .= $val['name']."-".$va['name'].$link;
                            }
                            
                        }
                    }
                }

                $value['region_text'] =  str_replace(";", $replace, rtrim($str, $link)) ;
            }
        }
        
        $titles = [
            ['goods_id'=>'系统编码(禁止修改)'],
            ['goods_name'=>'标题'],
            ['cmmdty_model'=>'商品型号'],
            ['goods_source'=>'商品来源(GC:工厂 CC:仓储 ZC:自采 填其中一项)'],
            ['goods_no'=>'商品编码(电商平台同款编码)'],
            ['category_id'=>'分类(填写1级到现有分类代码,中间用英文小写的逗号分开)'],
            ['delivery_time'=>'发货时效(0:24小时 1:48小时 3:72小时 4:7天内 5:15天内 6:30天内 7:45天内 填写其中一项)'],
            ['is_check'=>'是否审单(是填1 否填0)'],
            ['delivery_id'=>'运费模板ID'],
            ['status'=>'商品状态 (下架填写20 上架填写10)'],
            ['cost_price_min'=>'成本价'],
            ['goods_price_min'=>'前台价'],
            ['stock_total'=>'库存量'],
            // ['stock_total'=>'库存量'],
            ['remark'=>'下单须知'],
            ['is_use_jd_stock'=>'是否使用京东库存(是填1 否填0)'],
            ['region_text'=>'销售区域'],

        ];
        
        downLoadExcel('导出数据-'.date('Y-m-d', time()),$titles,$data['data']);
    }
    //文案导出
    public function copyExport(){
        ini_set('memory_limit', '2024M');
        set_time_limit(0);
        $model = new GoodsModel;
        $params = $this->request->param();
        $params['store_id'] = $this->storeId;
        $perSize = 10000;
        $params['page'] = 1;
        if ($this->merchantId) {
            $params['merchantId'] = $this->merchantId;
        }
        //$params['channels'] = ['zy'];
        // echo "
";
        // print_r($params);
        //exit();
        $data = $model->getAdminListExport($params, $perSize)->toArray();
        // echo "
";
        // print_r($data['data']);
        // exit();
        $jd = new Jd();
        $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);
        

        if ($data['data']) {
            foreach ($data['data'] as &$value) {
                //小程序短链
                $data1 = $app->short_link->getShortLink("pages/goods/detail?refereeId=0&goodsId=".$value['goods_id'], "", true);
                $value['applet_short_url'] = "";
                if ($data1['errcode'] == 0) {
                    $value['applet_short_url'] = $data1['link'];
                }
                //京东短链
                $value['jd_short_url'] = $jd->getJdShortLink($value['goods_no']);
                $value['h5_url'] = "https://www.royaum.com.cn/mobile/#/pages/goods/detail?goodsId=".$value['goods_id']."&storeId=".$store_id;
                //分类
                $value['category_3'] = "无";
                $value['category_4'] = "无";
                $value['membership_price'] = $value['goods_price_min'];
                $cates = GoodsCategoryRel::where('goods_id', $value['goods_id'])->select()->toArray();
                if ($cates) {
                    $cateList = Category::whereIn('category_id', array_column($cates, 'category_id'))->whereIn('level',[3,4])->order("level asc")->select()->toArray();

                    $value['category_3'] = $cateList[0]['name'] ?? "无";
                    $value['category_4'] = $cateList[1]['name'] ?? "无";
                    //会员价
                    $value['membership_price'] = \app\common\model\PriceSet::membershipPrice($value['goods_price_min'], $value['cost_price_min'], array_column($cates, 'category_id'));
                }
                
                //销售区域
                $region_text = $value['region_text'] ? json_decode($value['region_text'], true) : [];
                $str = "";
                $link = ";";
                $replace = "、";
                if ($region_text) {
                    foreach ($region_text as $key => $val) {
                        if (!$val['citys']) {
                            $str .= $val['name'].$link;
                        } else {
                            foreach ($val['citys'] as $key => $va) {
                                $str .= $val['name']."-".$va['name'].$link;
                            }
                            
                        }
                    }
                }

                $value['region_text'] =  $str ? str_replace(";", $replace, rtrim($str, $link)) : "全国";
            }
        }
        
        // echo "
";
        // print_r($data);
        // exit();
        $titles = [
            ['goods_id'=>'系统编码'],
            ['category_3'=>'三级分类'],
            ['category_4'=>'四级分类'],
            ['goods_name'=>'标题'],
            ['cmmdty_model'=>'型号'],
            ['membership_price'=>'推广价'],
            ['goods_price_min'=>'市场价'],
            ['jd_short_url'=>'同款链接'],
            ['applet_short_url'=>'小程序链接'],
            ['h5_url'=>'H5链接'],
            ['region_text'=>'销售区域'],
        ];
        
        downLoadExcel('导出数据-'.date('Y-m-d', time()),$titles,$data['data']);
    }
    public function import(){
        // 新增记录
        $model = new ImportModel;
        $params = $this->postData();
        $params['channel'] = "zy";
        if ($model->storeGoodsUpdateBatch($params)) {
            return $this->renderSuccess('批量修改成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');

    }
    /**
     * 商品抓取
     * [collector description]
     * @return [type] [description]
     */
    public function collector(string $sku): Json{
        $res = getJdGoodsBySku([$sku]);
        if (!$res) {
            return $this->renderError('数据抓取失败');
        }
        // $collector = new \app\job\service\goods\Collector;
        // $url = "https://item.jd.com/{$sku}.html";
        // $res1 = $collector->collector($url, 10048);
        
        return $this->renderSuccess($res[$sku] ?? []);
    }


    //商品一键上架
    public function oneClickShelf(): Json{

        $model = new GoodsModel;
        GoodsModel::update(['status'=>10]);
        return $this->renderSuccess('操作成功');
    }
    public function oneClickOffTheShelf(): Json{
        $model = new GoodsModel;
        GoodsModel::update(['status'=>20]);
        return $this->renderSuccess('操作成功');
    }

     /**
     * 修改商品状态(上下架)
     * @param array $goodsIds 商品id集
     * @param bool $state 为true表示上架
     * @return Json
     */
    public function jingpin(array $goodsIds, int $is_jingpin): Json
    {
        $model = new GoodsModel;
        if (!$model->setIsJingpin($goodsIds, $is_jingpin)) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('操作成功');
    }


    public function addTipff()
    {
        $params = $this->postForm(); 
        $model = new GoodsModel;
        $params['store_id'] = $this->storeId;

        $Tipoff = new ModelTipoff();
        if (!$Tipoff->add($params)) {
            return $this->renderError($Tipoff->getError() ?: '操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

    public function tipOffList()
    {
        $params = $this->request->param();
        $model = new ModelTipoff;
        $result = $model->getList($params);
        return $this->renderSuccess(compact('result'));

    }

    public function deleteTipOff()
    {
        $ids = $this->postForm('ids');
        $model = new ModelTipoff;
        if(!$model->deleteTipOff($ids)){
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('操作成功');

    }
}