<?php
namespace App\Http\Controllers\Api\OtherSystemInterfaces;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;

// 速电对接 -- 商品信息
class OtherSystemGoodsController extends Controller
{
    // 获取商品信息
    public function getSystemGoods(Request $request)
    {
        // 接收数据流
        $request = file_get_contents("php://input");
        // 解析
        Common::write_log($request, 2, 'OtherSystemGoods-getSystemGoods');
        $request = json_decode($request, true);
        if (empty($request['brand_name'])  || empty($request['good_name']) || empty($request['pg_id']) || empty($request['type']) || empty($request['is_bh'])) {
            return response()->json(['code'=>202, 'msg'=>'参数错误']);
        }

        $token = md5(md5($request['time'].config('apisystem.sd_token')));
        if ($request['token'] != $token) {
            return response()->json(['code'=>203, 'msg'=>'token校验失败']);
        }
        // type类型：1添加2编辑3删除
        $sdgo_data['sygo_system_cid'] = 1;//第三方系统所属企业/品牌方id
        $sdgo_data['sygo_system_goo_id'] = $request['pg_id'];//第三方系统商品id
        $sdgo_data['sygo_name'] = $request['good_name'];//商品名称
        $sdgo_data['sygo_goods_encode'] = $request['product_version'];//商品编码
        $sdgo_data['sygo_bra_name'] = $request['brand_name'];//品牌
        $sdgo_data['sygo_cate_name'] = $request['pg_series'];//品类
        $sdgo_data['sygo_replenish_state'] = $request['is_bh'];//是否为补货商品1否2是
        // return $request;
        $system_goo_id = DB::table('system_goods')
                ->where('sygo_system_goo_id',$request['pg_id'])
                ->where('sygo_system_cid',1)
                ->value('sygo_system_goo_id');
        if (empty($system_goo_id)) {
            $sygo_id = DB::table('system_goods')->insert($sdgo_data);
        }else{
            $sdgo_data['sygo_update_time'] = date('Y-m-d H:i:s');
            $sygo_id = DB::table('system_goods')
                ->where('sygo_system_goo_id', $request['pg_id'])
                ->update($sdgo_data); 
        }
        if($request['type'] == 3){
            $id = DB::table('system_goods')
                ->where('sygo_system_goo_id', $request['pg_id'])
                ->value('sygo_system_goo_id');
            if(!empty($id)){
                $sdgo_datas['sygo_delete'] = 2;
                $sdgo_datas['sygo_update_time'] = date('Y-m-d H:i:s');
                $sygo_id = DB::table('system_goods')
                    ->where('sygo_system_goo_id', $request['pg_id'])
                    ->update($sdgo_datas);
            }else{
                $sygo_id = true;
            }
        }
        if ($sygo_id) {
            return response()->json(['code'=>200, 'msg'=>'回传成功']);
        } else {
            return response()->json(['code'=>201, 'msg'=>'回传失败']);
        }
    }
}
