<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */
namespace app\api\controller\twoshop;

use app\common\model\RealVerify;
use app\common\model\TwoGoods;
use app\common\model\TwoPromiseMoneyRecord;
use app\common\service\ConfigService;
use think\facade\Db;
use app\api\logic\twoshop\GoodsLogic;

class Goods  extends \app\api\controller\BaseShopController
{
    public array $notNeedLogin = ['search', 'messageList', 'detail', 'randomDetailed'];

    /**
     * 商品上下架
     */
    public function status()
    {
        $status = $this->request->param('status') == 1?1:0;

        if (isActivePluginByPluginName('realverify') && $status) {
            $mustVerifiedTypeId = ConfigService::get('twoshop', 'must_verified_type_id', 0);

            if (!empty($mustVerifiedTypeId)) {
                $realVerifyRecord = RealVerify::where('user_id', $this->userId)->whereIn('type_id', explode(',', $mustVerifiedTypeId))->where('status', 1)->find();

                if (empty($realVerifyRecord)) {
                    return show(0, '请先完成认证', [
                        'real_verify_type_id' => $mustVerifiedTypeId
                    ]);
                }
            }

            $minPromiseMoney = ConfigService::get('twoshop', 'min_promise_money', 0);

            if (!empty($minPromiseMoney)) {
                $promiseMoneyRecord = TwoPromiseMoneyRecord::where('user_id', $this->userId)->find();

                if (!$promiseMoneyRecord || $promiseMoneyRecord->money < $minPromiseMoney) {
                    return show(0, '保证金不足, 请先缴纳');
                }
            }
        }

        $goods_id = $this->request->param('id','','int');
        $res = TwoGoods::where('user_id', $this->userId)
        ->where('id',$goods_id)
        ->update(['status'=> $status]);
        if ($res) {
            return show(1,'修改成功');
        }
        return show(1,'修改失败');
    }

    /**
     * 商品上下架
     */
    public function del()
    {
        $params = $this->request->post();
        $params = (new \app\api\validate\twoshop\GoodsValidate())->post()->goCheck('del',[]);
        // 删除商品接口
        Db::startTrans();
        try {

            // 软删除商品
            $res = TwoGoods::whereIn('id',$params['ids'])->select()->delete();

            // 删掉用户购物车商品
            \app\common\model\TwoCart::where(['goods_id'=>$params['ids']])->delete();

            Db::commit();
            return show(1,'删除成功');
        }   catch (\Exception $e) {
            Db::rollback();
            return show(0,$e->getMessage());
        }
    }

    /**
     * 商品搜索
     */
    public function search()
    {
        $params = $this->request->param();

        if (!isset($params['type'])) {
            $params['type'] = 2;
        }

        $order = [
            'sort'=>'desc'
        ];
        $where = [
            ['status','=',1]
        ];

        if (isset($params['user_id'])) {
            $where[] = [
                'user_id', '=', $params['user_id']
            ];
        } else {
            $params['user_id'] = $this->userId;
        }

        if (isset($params['type'])) {
            if ($params['type'] == 2) {
                $where[]=['total_stock','>',0];
            }

            if ($params['type'] == 3) {
                $where[]=['total_stock','<=',0];
            }
        }

        if(isset($params['name'])){
            $where[]=['name','like','%'.$params['name'].'%'];
        }
        
        if(isset($params['order_by'])){
            $order[$params['order_by']]='desc';
        }
        if(isset($params['order_sort'])){
            $order[$params['order_by']]=$params['order_sort'];
        }

        if(isset($params['category_id'])){
            $where[]=['category_id','=',$params['category_id']];
        }

        $list = TwoGoods::where($where)
        ->with('user')
        ->order($order)
        ->paginate(10)
        ->toArray();

        foreach($list['data'] as &$v){
            $v['avg_comment'] = GoodsLogic::avgComment($v['user_id']);
            $v['create_time'] = formatTime($v['create_time']);
        };

       return show(1,'分类列表',$list);
    }

    public function random()
    {
        $list = TwoGoods::field('id,name')->where('status', 1)->orderRaw('RAND()')->limit(10)->select()->toArray();
        return show(1,'商品列表',$list);
    }

    public function randomDetailed()
    {
        $list = TwoGoods::with('user')->where('status', 1)->where('total_stock', '>', 0)->orderRaw('RAND()')->limit(14)->select()->toArray();

        foreach ($list as &$item) {
            if (!empty($item['user'])) {
                $item['user']['location'] = \app\common\model\User::where('id', $item['user']['id'])->value('ip_address');
            }
        }

        return show(1,'商品列表',$list);
    }

    /**
     * @note 商品详情
     * @return \think\response\Json
     */
    public function detail()
    {
        $params =  $this->request->get();
        $params['user_id'] = $this->userId;
        $detail = (new GoodsLogic)->detail($params);
        // dd($detail);
        if (false === $detail) {
            return show(0,GoodsLogic::getError());
        }
        $detail['comment'] = GoodsLogic::avgComment($detail['user_id']);
        return show(0,'商品详情',$detail);
    }

    /**
     * 商品留言列表
     */
    public function messageList()
    {
        return $this->dataLists( new \app\api\lists\TwoGoodsMessageLists());;
    }

    /**
     * 商品评论删除
     */
    public function messageDelete()
    {
        try{
            $params = $this->request->post();
            $where = [
                'id' => $params['id'],
                'goods_id' => $params['goods_id'],
                'user_id' => $this->userId,
            ];
            $article = \app\common\model\TwoGoodsMessage::where($where)->findOrEmpty();
            if($article->isEmpty()){
                return show(config('status.error'),'删除失败');
            }

            \app\common\model\TwoGoodsMessage::destroy(['user_id' => $this->userId, 'id' => $params['id']]);
            return show(config('status.success'),'删除成功');
        }catch(\Exception $e){
            return show(config('status.error'),'删除失败');
        }
    }

    /**
     * 添加商品留言
     */
    public function addMessage()
    {
        $params = $this->request->post();

        $ip = $_SERVER['REMOTE_ADDR'];
        $ip_address = '';
        try {
            // 初始化，指定QQWry.dat文件路径
            $qqwry = new \app\common\service\QQWry('qqwry.dat');
            // 获取客户端IP
            $ip = $_SERVER['REMOTE_ADDR'];
            // 查询IP地理位置
            $location = $qqwry->getLocation($ip);
            $ip_address = $location['country'];
            
        } catch (\Exception $e) {
            return show(config('status.error'), $e->getMessage());
        }
        
        $content = $params['comment'];
        $data = [
            'ip'=>$_SERVER['REMOTE_ADDR'],
            'ip_address'=>$ip_address,
            'goods_id'           => $params['goods_id'],
            'pid'           => isset($params['pid'])  ? $params['pid'] : 0,
            'user_id'       => $this->userId,
            'comment'       => $content,
            'content'       => $content,
            'status'        => 1,
            'topic_id'      => '',
            'msg_user_ids'  => ''
        ];

        \app\common\model\TwoGoodsMessage::create($data);

        $postUserId = \app\common\model\TwoGoodsMessage::where(['id' => $params['goods_id']])->value('user_id');
        if( $postUserId  !=  $this->userId){
            // 消息通知
            event('Notice', [
                'scene_id' => 1,
                'params' => [
                    'user_id'    => $postUserId,  //帖子对应的发布者ID
                    'goods_id' => $params['goods_id'],   //回复的帖子,
                    'fans_id'    => $this->userId
                ]
            ]);
        }
        

        return show(config('status.success'),'发布成功');
    }

    /* 
    *商品添加接口
    */
    public function add()
    {
        $params = $this->request->post();
        $params['user_id'] = $this->userId;

        if (isActivePluginByPluginName('realverify')) {
            $mustVerifiedTypeId = ConfigService::get('twoshop', 'must_verified_type_id', 0);

            if (!empty($mustVerifiedTypeId)) {
                $realVerifyRecord = RealVerify::where('user_id', $this->userId)->whereIn('type_id', explode(',', $mustVerifiedTypeId))->where('status', 1)->find();

                if (empty($realVerifyRecord)) {
                    return show(0, '请先完成认证', [
                        'real_verify_type_id' => $mustVerifiedTypeId
                    ]);
                }
            }
        }

        $minPromiseMoney = ConfigService::get('twoshop', 'min_promise_money', 0);

        if (!empty($minPromiseMoney)) {
            $promiseMoneyRecord = TwoPromiseMoneyRecord::where('user_id', $this->userId)->find();

            if (!$promiseMoneyRecord || $promiseMoneyRecord->money < $minPromiseMoney) {
                return show(0, '保证金不足, 请先缴纳');
            }
        }

        if ($params['spec_type'] == 2) {
            $params['server_spec_value_list'] = cartesian_product(array_converting(array_column($params['spec_value'],'spec_list')));
        }
        (new \app\api\validate\twoshop\GoodsValidate())->post()->goCheck('add');              //商品基础信息验证
        (new \app\api\validate\twoshop\GoodsItemValidate())->post()->goCheck('', $params);    //商品规格验证
        
        Db::startTrans();
        try {
            // 添加商品
            $goods = $this->setBase($params);
            // 添加商品的规格
            $this->addGoodsItem($goods,$params);
            // 记录店铺动态
            \app\common\model\TwoGoodsLog::create([
                'user_id'=>$params['user_id'],
                'goods_id'=>$goods->id,
                'name'=>$goods->name,
                'image'=>$goods->image,
                'price'=>$goods->min_price,
                'desc'=>'上新了1件宝贝',
            ]);

            Db::commit();
            return show(1,'添加成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0,$e->getMessage());
        }
    }

    /**
     * @notes 编辑商品
     * @return \think\response\Json
     */
    public function edit()
    {
        $params = $this->request->post();
        $params['user_id'] = $this->userId;

        if(isActivePluginByPluginName('realverify')) {
            $mustVerifiedTypeId = ConfigService::get('twoshop', 'must_verified_type_id', 0);

            if (!empty($mustVerifiedTypeId)) {
                $realVerifyRecord = RealVerify::where('user_id', $this->userId)->whereIn('type_id', explode(',', $mustVerifiedTypeId))->where('status', 1)->find();

                if (empty($realVerifyRecord)) {
                    return show(0, '请先完成认证', [
                        'real_verify_type_id' => $mustVerifiedTypeId
                    ]);
                }
            }
        }

        $minPromiseMoney = ConfigService::get('twoshop', 'min_promise_money', 0);

        if (!empty($minPromiseMoney)) {
            $promiseMoneyRecord = TwoPromiseMoneyRecord::where('user_id', $this->userId)->find();

            if (!$promiseMoneyRecord || $promiseMoneyRecord->money < $minPromiseMoney) {
                return show(0, '保证金不足, 请先缴纳');
            }
        }

        if (\app\common\enum\TwoGoodsEnum::SEPC_TYPE_MORE == $params['spec_type']) {
            $params['server_spec_value_list'] = cartesian_product(array_converting(array_column($params['spec_value'],'spec_list')));
        }
        (new \app\api\validate\twoshop\GoodsValidate())->post()->goCheck('edit', $params);    //商品基础信息验证        
        (new \app\api\validate\twoshop\GoodsItemValidate())->post()->goCheck('', $params);    //商品规格验证

        Db::startTrans();
        try {
            // 编辑修改商品信息
            $goods = $this->setBase($params);
            // 修改商品规格信息
            $this->editGoodsItem($goods,$params);
            //todo 其他业务逻辑

            Db::commit();
            return show(1,'修改成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0,$e->getMessage());
        }

    }

    /**
     * @notes 商品基础信息
     * @param array $params
     * @return Goods|array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function setBase(array $params)
    {
        $goods = new TwoGoods();
        $goodsImage = $params['goods_image'];
        // $goodsCategory = $params['category_id'];
        //总库存
        $totalStock = array_sum(array_column($params['spec_value_list'],'stock'));
        //售价数组
        $specPriceArray = array_column($params['spec_value_list'],'sell_price');
        //划线价数组
        $specLineationPriceArray = array_column($params['spec_value_list'],'lineation_price');
        // dd($params['id']);
        //编辑操作
        
        if(isset($params['id'])){
            $goods = $goods::find($params['id']);
            //保存改变前的规格类型
            $goods->oldSpecType = $goods->spec_type;
        }

        $isExpress = 1 == $params['type'] ? $params['is_express'] : 0 ;      //快递
        $isSelffetch =  0 ;  //自提
        $isVirtualdelivery = 0; 
        $afterPay = 0;
        $afterDelivery = 0;
        switch ($params['type']){
            case 1:
                // 实物商品
                $isExpress = $params['is_express'];
                $isSelffetch = $params['is_selffetch'];
                break;
        }
        // dd(implode(',',$params['goods_image']));
        //更新商品基础信息
        $goods->category_id             = $params['category_id'];
        $goods->user_id             = $params['user_id'];
        $goods->name                = $params['name'];
        $goods->goods_image         = implode(',',$params['goods_image']);
        // $goods->code                = $params['code'];
        $goods->type                = $goods['type'] ?? $params['type'];  //编辑不允许修改类型
        // $goods->brand_id            = $params['brand_id'];
        // $goods->supplier_id         = $params['supplier_id'];
        // $goods->unit_id             = $params['unit_id'];
        $goods->image               = $goodsImage[0]; //弹出第一张图片，设为商品主图;
        $goods->spec_type           = $params['spec_type'];
        $goods->video_source        = 2;
        $goods->video_cover         = $params['video_cover'];
        $goods->video               = $params['video'];
        $goods->poster              = $params['poster'];
        $goods->total_stock         = $totalStock;
        $goods->min_price           = min($specPriceArray);
        $goods->max_price           = max($specPriceArray);
        $goods->min_lineation_price = min($specLineationPriceArray);
        $goods->max_lineation_price = max($specLineationPriceArray);
        $goods->express_type        = $params['express_type'];
        $goods->express_money       = $params['express_money'];
        // $goods->express_template_id = $params['express_template_id'];
        $goods->stock_warning       = $params['stock_warning'];
        // $goods->virtual_sales_num   = $params['virtual_sales_num'];
        $goods->virtual_click_num   = $params['virtual_click_num'] ?? 0;
        $goods->sort                = $params['sort'] ?? 0;
        $goods->status              = $params['status'];
        $goods->content             = $params['content'];
        $goods->is_express          = $isExpress;                   //快递配送
        $goods->is_selffetch        = $isSelffetch;                 //
        $goods->is_virtualdelivery  = $isVirtualdelivery;           //
        $goods->after_pay           = $afterPay;                    //买家付款后：1-自动发货，2-手动发货
        $goods->after_delivery      = $afterDelivery;               //发货后：1-自动完成订单，2-需要买家确认
        $goods->delivery_content    = $params['delivery_content'];  //发货内容
        $goods->is_address          = $params['is_address'] ?? 0;
        $goods->type_ids            = $params['type_ids'] ?? '';
        $goods->address             = $params['address'];
        $goods->lng                 = $params['lng'] ?? null;
        $goods->lat                 = $params['lat'] ?? null;

        $ip = $_SERVER['REMOTE_ADDR'];
        $ip_address = '';
        try {
            // 初始化，指定QQWry.dat文件路径
            $qqwry = new \app\common\service\QQWry('qqwry.dat');
            // 获取客户端IP
            $ip = $_SERVER['REMOTE_ADDR'];
            // 查询IP地理位置
            $location = $qqwry->getLocation($ip);
            $ip_address = $location['country'];
            
        } catch (\Exception $e) {
            echo "发生错误: " . $e->getMessage();
        }

        $goods->ip = $ip;
        $goods->ip_address = $ip_address;
        
        $goods->save();

        return $goods;
    }

    /**
     * @notes 添加商品规格信息
     * @param Goods $goods
     * @param array $params
     */
    private function addGoodsItem(TwoGoods $goods,array $params)
    {
        $specType = $params['spec_type'];
        //添加商品规格
        if(1 == $specType) {

            //单规格商品
            $specValueList = $params['spec_value_list'];
            foreach ($specValueList as $spec) {

                $goodsSpec = new \app\common\model\TwoGoodsSpec();
                $goodsSpec->goods_id = $goods->id;
                $goodsSpec->name = '默认';
                $goodsSpec->save();

                $goodsSpecValue = new \app\common\model\TwoGoodsSpecValue();
                $goodsSpecValue->save([
                    'goods_id'  => $goodsSpec->goods_id,
                    'spec_id'   => $goodsSpec->id,
                    'value'     => '默认',
                ]);

                $specValueData = [
                    'goods_id'         => $goods->id,
                    'spec_value_ids'   => $goodsSpecValue->id,
                    'spec_value_str'   => '默认',
                    'image'            => $spec['image'],
                    'sell_price'       => $spec['sell_price'],
                    'lineation_price'  => $spec['lineation_price'],
                    'cost_price'       => $spec['cost_price'],
                    'stock'            => $spec['stock'],
                    'volume'           => $spec['volume'],
                    'weight'           => $spec['weight'],
                    'bar_code'         => $spec['bar_code'],
                ];
                (new \app\common\model\TwoGoodsItem())->save($specValueData);
            }


        } else {

            //添加多规格项
            $postSpecValue = $params['spec_value'];
            $specData = [];
            foreach ($postSpecValue as $sepcKey => $specVal) {
                $goodsSpec = new \app\common\model\TwoGoodsSpec();
                $goodsSpec->goods_id = $goods->id;
                $goodsSpec->name = $specVal['name'];
                $goodsSpec->save();
                //处理规格值
                array_walk($specVal['spec_list'], function ($spec) use ($goodsSpec,&$specData){
                    $specData[] = ['spec_id'=>$goodsSpec->id,'value'=>$spec['value']];

                });

            }
            // dd($specData);
            // 添加规格项的值
            $res = $goods->specValueSpec()->saveAll($specData);

            //添加规格信息
            $serverSpecValueList = $params['server_spec_value_list'];
            //改变数据结构，ids为索引
            $postSpecValueList = array_column($params['spec_value_list'], null, 'ids');
            $goodsSpecValueList = \app\common\model\TwoGoodsSpecValue::where(['goods_id'=>$goods->id])
                        ->group('spec_id')
                        ->column(' GROUP_CONCAT(value Separator \',\') as spec_values,GROUP_CONCAT(id Separator \',\') as spec_ids');


            $specValueData = [];

            foreach ($serverSpecValueList as $serverValue) {

                $specValueList = $postSpecValueList[$serverValue['ids']];
                $specValue = explode(\app\common\enum\TwoGoodsEnum::SPEC_SEPARATOR, $serverValue['spec_value']);
                $specIds = [];

                //获取规格值对应的id
                foreach ($specValue as $specIndex => $specVal){
                    $specListValues = explode(',',$goodsSpecValueList[$specIndex]['spec_values']);
                    $specListIds = explode(',',$goodsSpecValueList[$specIndex]['spec_ids']);
                    $specValueIds = array_combine($specListValues,$specListIds);
                    $specIds[] = $specValueIds[$specVal];
                }

                $specValueData[] = [
                    'spec_value_ids'    => implode(\app\common\enum\TwoGoodsEnum::SPEC_SEPARATOR, $specIds),
                    'spec_value_str'    => $serverValue['spec_value'],
                    'image'             => $specValueList['image'],
                    'sell_price'        => $specValueList['sell_price'],
                    'lineation_price'   => $specValueList['lineation_price'],
                    'cost_price'        => $specValueList['cost_price'],
                    'stock'             => $specValueList['stock'],
                    'volume'            => $specValueList['volume'],
                    'weight'            => $specValueList['weight'],
                    'bar_code'          => $specValueList['bar_code'],
                ];

            }
            $goods->specValueList()->saveAll($specValueData);
        }
    }

    /**
     * @notes 编辑商品规格信息
     * @param Goods $goods
     * @param array $params
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function editGoodsItem(TwoGoods $goods, array $params)
    {
        $specType = $params['spec_type'];         //编辑后的规格类型
        $oldSpecType = $goods->oldSpecType;       //原来的规格类型
        
        //编辑商品规格
        if (1 == $specType) { //修改成单规格

            //原来单规格，更新规格信息 goods_item
            $specValueList = $params['spec_value_list'][0];//新规格信息
            // dd($specValueList);
            if(\app\common\enum\TwoGoodsEnum::SEPC_TYPE_SIGNLE == $oldSpecType) {

                \app\common\model\TwoGoodsItem::where('id', $specValueList['id'])
                    ->update([
                        'sell_price' => $specValueList['sell_price'],
                        'lineation_price' => $specValueList['lineation_price'],
                        'cost_price' => $specValueList['cost_price'],
                        'image' => $specValueList['image'],
                        'stock' => $specValueList['stock'],
                        'volume' => $specValueList['volume'],
                        'weight' => $specValueList['weight'],
                        'bar_code' => $specValueList['bar_code'],
                    ]);

            } else {
                
                // echo '原来多规格，删除多规格数据';die;
                \app\common\model\TwoGoodsSpec::where(['goods_id' => $goods->id])->delete();
                \app\common\model\TwoGoodsSpecValue::where(['goods_id' => $goods->id])->delete();
                \app\common\model\TwoGoodsItem::where(['goods_id' => $goods->id])->delete();

                //写入单规格数据
                $goodsSpec = new \app\common\model\TwoGoodsSpec();
                $goodsSpec->goods_id = $goods->id;
                $goodsSpec->name = '默认';
                $goodsSpec->save();
                $goodsSpecValue = new \app\common\model\TwoGoodsSpecValue();
                $goodsSpecValue->save([
                    'goods_id' => $goodsSpec->goods_id,
                    'spec_id' => $goodsSpec->id,
                    'value' => '默认',
                ]);

                $specValueData = [
                    'goods_id' => $goods->id,
                    'spec_value_ids' => $goodsSpecValue->id,
                    'spec_value_str' => '默认',
                    'image' => $specValueList['image'],
                    'sell_price' => $specValueList['sell_price'],
                    'lineation_price' => $specValueList['lineation_price'],
                    'cost_price' => $specValueList['cost_price'],
                    'stock' => $specValueList['stock'],
                    'volume' => $specValueList['volume'],
                    'weight' => $specValueList['weight'],
                    'bar_code' => $specValueList['bar_code'],
                ];
                (new \app\common\model\TwoGoodsItem())->save($specValueData);

            }

        } else {// 修改成多规格
            

            //原单规格
            if (\app\common\enum\TwoGoodsEnum::SEPC_TYPE_SIGNLE == $oldSpecType) {

                // echo '单规格项修改';die;

                //原来单规格，删除单规格数据
                \app\common\model\TwoGoodsSpec::where(['goods_id' => $goods->id])->delete();
                \app\common\model\TwoGoodsSpecValue::where(['goods_id' => $goods->id])->delete();
                \app\common\model\TwoGoodsItem::where(['goods_id' => $goods->id])->delete();

                //添加规格项
                $postSpecValue = $params['spec_value'];
                $specData = [];
                foreach ($postSpecValue as $specVal) {
                    $goodsSpec = new \app\common\model\TwoGoodsSpec();
                    $goodsSpec->goods_id = $goods->id;
                    $goodsSpec->name = $specVal['name'];
                    $goodsSpec->save();

                    //处理规格值
                    array_walk($specVal['spec_list'], function ($spec) use ($goodsSpec, &$specData) {
                        $specData[] = ['spec_id' => $goodsSpec->id, 'value' => $spec['value']];
                    });

                }

                $goods->specValueSpec()->saveAll($specData);

                //添加规格信息
                $serverSpecValueList = $params['server_spec_value_list'];
                //改变数据结构，ids为索引
                $postSpecValueList = array_column($params['spec_value_list'], null, 'ids');
                $goodsSpecValueList = \app\common\model\TwoGoodsSpecValue::where(['goods_id' => $goods->id])
                    ->group('spec_id')
                    ->column(' GROUP_CONCAT(value Separator \',\') as spec_values,GROUP_CONCAT(id Separator \',\') as spec_ids');
                $specValueData = [];

                foreach ($serverSpecValueList as $serverValue) {

                    $specValueList = $postSpecValueList[$serverValue['ids']];
                    $specValue = explode(\app\common\enum\TwoGoodsEnum::SPEC_SEPARATOR, $serverValue['spec_value']);
                    $specIds = [];

                    //获取规格值对应的id
                    foreach ($specValue as $specIndex => $specVal) {
                        $specListValues = explode(',', $goodsSpecValueList[$specIndex]['spec_values']);
                        $specListIds = explode(',', $goodsSpecValueList[$specIndex]['spec_ids']);
                        $specValueIds = array_combine($specListValues, $specListIds);
                        $specIds[] = $specValueIds[$specVal];


                    }

                    $specValueData[] = [
                        'spec_value_ids' => implode(\app\common\enum\TwoGoodsEnum::SPEC_SEPARATOR, $specIds),
                        'spec_value_str' => $serverValue['spec_value'],
                        'image' => $specValueList['image'],
                        'sell_price' => $specValueList['sell_price'],
                        'lineation_price' => $specValueList['lineation_price'],
                        'cost_price' => $specValueList['cost_price'],
                        'stock' => $specValueList['stock'],
                        'volume' => $specValueList['volume'],
                        'weight' => $specValueList['weight'],
                        'bar_code' => $specValueList['bar_code'],
                    ];

                }
                $goods->specValueList()->saveAll($specValueData);


            } else {

                // echo '原来多规格，改变后还是多规格';die;
                $goodsSpecIds = \app\common\model\TwoGoodsSpec::where(['goods_id' => $goods->id])->column('id');
                $goodsSpecValueIds = \app\common\model\TwoGoodsSpecValue::where(['goods_id' => $goods->id])->column('id');
                $goodsItemIds = \app\common\model\TwoGoodsItem::where(['goods_id' => $goods->id])->column('id');
                $postSpecValue = $params['spec_value'];
                $postGoodsSpecValueIds = [];


                foreach ($postSpecValue as $spec) {

                    $goodsSpec = new \app\common\model\TwoGoodsSpec();
                    //存在规格id,进行更新操作
                    if ($spec['id'] > 0) {
                        $goodsSpec = $goodsSpec->find($spec['id']);
                    }
                    $goodsSpec->goods_id = $goods->id;
                    $goodsSpec->name = $spec['name'];
                    $goodsSpec->save();
                    //合并规格值id
                    $postGoodsSpecValueIds = array_merge($postGoodsSpecValueIds, array_column($spec['spec_list'], 'id'));

                    //写入规格，存在则更新
                    array_walk($spec['spec_list'], function ($specVal) use ($goodsSpec, &$specList) {
                        $goodsSpecValue = new \app\common\model\TwoGoodsSpecValue();
                        //存在规格值id，进行更新操作
                        if ($specVal['id'] > 0) {
                            $goodsSpecValue = $goodsSpecValue->find($specVal['id']);
                        }
                        $goodsSpecValue->save([
                            'goods_id' => $goodsSpec->goods_id,
                            'spec_id' => $goodsSpec->id,
                            'value' => $specVal['value'],
                        ]);

                    });
                }

                //添加规格信息
                $serverSpecValueList = $params['server_spec_value_list'];

                //改变数据结构，ids为索引
                $postSpecValueList = array_column($params['spec_value_list'], null, 'ids');
                $specValues = array_column($serverSpecValueList, 'spec_value');
                $specValues = implode(',', $specValues);
                $goodsSpecValueList = \app\common\model\TwoGoodsSpecValue::where(['goods_id' => $goods->id])
                    ->where('value', 'in', $specValues)
                    ->group('spec_id')
                    ->column(' GROUP_CONCAT(value Separator \',\') as spec_values,GROUP_CONCAT(id Separator \',\') as spec_ids');

                $specValueData = [];

                foreach ($serverSpecValueList as $serverValue) {

                    $specValueList = $postSpecValueList[$serverValue['ids']];
                    $specValue = explode(\app\common\enum\TwoGoodsEnum::SPEC_SEPARATOR, $serverValue['spec_value']);
                    $specIds = [];

                    //获取规格值对应的id
                    foreach ($specValue as $specIndex => $specVal) {

                        $specListValues = explode(',', $goodsSpecValueList[$specIndex]['spec_values']);
                        $specListIds = explode(',', $goodsSpecValueList[$specIndex]['spec_ids']);
                        $specValueIds = array_combine($specListValues, $specListIds);
                        $specIds[] = $specValueIds[$specVal];

                    }

                    //添加的数据
                    $itemData = [
                        'spec_value_ids' => implode(\app\common\enum\TwoGoodsEnum::SPEC_SEPARATOR, $specIds),
                        'spec_value_str' => $serverValue['spec_value'],
                        'image' => $specValueList['image'],
                        'sell_price' => $specValueList['sell_price'],
                        'lineation_price' => $specValueList['lineation_price'],
                        'cost_price' => $specValueList['cost_price'],
                        'stock' => $specValueList['stock'],
                        'volume' => $specValueList['volume'],
                        'weight' => $specValueList['weight'],
                        'bar_code' => $specValueList['bar_code'],
                    ];
                    //更新规格
                    if ($specValueList['id'] > 0) {
                        $itemData['id'] = $specValueList['id'];
                    }
                    $specValueData[] = $itemData;

                }

                $goods->specValueList()->saveAll($specValueData);


                $postSpecIds = array_column($postSpecValue, 'id');
                $postItemIds = array_column($params['spec_value_list'], 'id');
                //对比规格是否需要删除
                $delSpecIds = array_diff($goodsSpecIds, $postSpecIds);

                $delSpecValyeIds = array_diff($goodsSpecValueIds, $postGoodsSpecValueIds);

                $delItemIds = array_diff($goodsItemIds, $postItemIds);

                //需要删除规格名
                if ($delSpecIds) {
                    \app\common\model\TwoGoodsSpec::where(['id' => array_values($delSpecIds)])->delete();
                }
                //删除规格值
                if ($delSpecValyeIds) {
                    \app\common\model\TwoGoodsSpecValue::where(['id' => array_values($delSpecValyeIds)])->delete();
                }
                //删除规格信息
                if ($delItemIds) {
                    \app\common\model\TwoGoodsItem::where(['id' => array_values($delItemIds)])->delete();
                }
            }

        }

    }

    /**
     * 根据商品查询商品评论
     */
    public function goodsCommentList()
    {
        $params = $this->request->get();
        // 查询订单是否已收获
        $data = \app\common\model\TwoGoodsComment::with('user')
        ->where([
            ['goods_id','=',$params['goods_id']],
            ['status','=',1]
        ])
        ->order(['id'=>'desc','create_time'=>'desc'])
        ->paginate(10);
        return show(1,'商品评论列表',$data);
    }

}