<?php

/**
 * 商品服务类
 *
 * @author lixiaolin
 * @Date: 2021/07/31
 * @Time: 下午12:23
 * @Email: lixiaolin@bluearp.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;

use App\Http\Controllers\BaseController;
use App\Models\GoodCode;
use App\Models\PjGoods;
use Illuminate\Support\Facades\Log;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\DB;

class GoodsService extends Service
{
    public static $instance;
    public $modelMain = null;

    public function __construct()
    {
        $this->modelMain = new PjGoods();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }


    /**
     * 根据给出的关键字及检索条件查询商品
     * @param string $keywords
     * @param string $searchKey
     * @param int $limit
     *
     * @return array
     */
    public static function searchGoods($keywords, $searchKey = 'version', $limit = 10) {
        if (!in_array($searchKey, ['version', 'pg_series', 'brand_name'])) {
            return [];
        }
        $res = PjGoods::where($searchKey, 'like', '%' . $keywords . '%')
            ->select('brand_name', 'pg_series', 'version', 'pg_id')
            ->limit($limit)
            ->orderBy('sorting', 'DESC')
            ->get()
            ->toArray();
        foreach ($res as $k => $v) {
            $res[$k] = $v = $v->toArray();
            if ($v->pg_series == "") {
                $res[$k]['name'] = $v['brand_name'] . ' ' . $v['version'];
            } else {
                $res[$k]['name'] = $v['brand_name'] . ' ' . $v['pg_series'] . ' ' . $v['version'];
            }
        }

        return $res;
    }

    public static function syncGoods() {
        return PjGoods::where("is_delect", '1')
            ->select('pg_id', 'brand_name', 'pg_series', 'version')
            ->get()
            ->toArray();
    }

    //获取品牌数据
    public static function getInUseBrands() {
        return PjGoods::groupBy('brand_name')->select('brand_name')->get()->toArray();
    }

    //获取品牌商品数据
    public static function getBrandGoods($brandName) {
        return PjGoods::where('brand_name', $brandName)->select('pg_id', 'pg_series', 'version')->get()->toArray();
    }

    //获取部分商品
    public static function getGoodsInIds(array $goodsIds) {
        return PjGoods::whereIn('pg_id', $goodsIds)->select('pg_id','brand_name','pg_series', 'version')->get()->toArray();
    }
    /**|---------------------------------------------------------------------------------
     * @name 根据指定条件（多条件）获取商品
     * @param array $params 查询条件
     * @param array $select 查询内容
     * @retrun multitype:array
     * @author dou 2021/8/9 17:08
     * |---------------------------------------------------------------------------------
    */
    public static function getGoodsBy ( $params , $select = [] ){
        $db = new PjGoods();
        $params['is_delect'] = 1;
        if(!$select){
            $select = ['pg_id','brand_name','pg_series','version','cd_id','pg_goodsname'];
        }
        $list = CommonService::getMysqlData($db, $params,$select,[],'get','80');
        if($list){
            $list = GoodsService::addGoodsName($list,$select);
        }
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取车膜补货默认商品
     * @param array $goodsid 商品id
     * @retrun /multitype:array
     * @author dou 2021/11/10 21:22
     * |---------------------------------------------------------------------------------
    */
    public static function getSolarFilmGoods ( $goodsid ){
        foreach ($goodsid as $k => $v) {
            if (in_array($v, ['5912'])) {
                unset($goodsid[$k]);
            }
        }
        $goodsid = CommonService::resetListKey($goodsid);
        if($goodsid) {
            $good = self::getGoodsByKey('pg_id', $goodsid, ['pg_id', 'pg_parentid']);
            if ($good) {
                $pg_parentid = [];
                $ids = [];
                foreach ($good as $k => $v) {
                    $ids[] = $v['pg_id'];
                    if ($v['pg_parentid'] > 0) {
                        $ids[] = $v['pg_parentid'];
                        $pg_parentid[] = $v['pg_parentid'];
                    }
                }
                $goodid = self::getGoodsByKey('pg_parentid', $ids, ['pg_id']);
                if ($goodid) {
                    foreach ($goodid as $k => $v) {
                        $ids[] = $v['pg_id'];
                    }
                }
                $good = self::getGoodsByKey('pg_id', $ids);
            }
        }else{
            $good = [];
        }
        return $good;
    }

    /**
     * @name 获取商品信息根据单条件
     * @param  $key
     * @param  $value
     * @param  $select
     * @param string $type
     * @return
     * @author du 2021年8月19日上午10:15:04
     */
    public static function getGoodsByKey($key, $value, $select = [] , $type = 'get')
    {
    	$db = new PjGoods();
        if(is_array($value)){
            $key = $key."_searchin";
        }
    	if(in_array($key, ['pg_id'])) {
    		$type = 'first';
    	}
    	if($type == 'first') {
    		if (count($select) == 1) {
    			$type = 'value';
    		}
    	}
        if(!$select){
            $select = ['pg_id','brand_name','pg_series','version','cd_id','pg_goodsname'];
        }
    	$list = CommonService::getMysqlData($db,[$key=>$value],$select,[],$type);
        if($list){
            $list = GoodsService::addGoodsName($list,$select,$type);
        }
    	return $list;
    }
    /**|---------------------------------------------------------------------------------
     * @name 拼接商品全称
     * @param array $list 商品数据
     * @param array $select 查询字段
     * @param array $type 数据类型 1单条数据 2多条数据
     * @retrun /multitype:array
     * @author dou 2021/8/25 17:37
     * |---------------------------------------------------------------------------------
    */
    public static function addGoodsName($list, $select = [], $type = 'get') {
        if (in_array('pg_series', $select)) {
            if($type == 'get') {
                foreach ($list as $k => $v) {
                    if(isset($v['pg_goodsname']) && $v['pg_goodsname']!=''){
                        $list[$k]['good_name'] = $v['pg_goodsname'];
                    }else {
                        if ($v['pg_series'] != '') {
                            $pg_series = '-' . $v['pg_series'];
                        } else {
                            $pg_series = '';
                        }
                        $list[$k]['good_name'] = $v['brand_name'] . $pg_series . '-' . $v['version'];
                    }
                    if ($v['version'] != '') {
                        if ($v['pg_series'] != '') {
                            $list[$k]['goods_number'] = $v['pg_series'] . '-' . $v['version'];
                        } else {
                            $list[$k]['goods_number'] = $v['version'];
                        }
                    }else{
                        $list[$k]['goods_number'] = str_replace($v['brand_name'], '', $list[$k]['pg_goodsname']);
                    }
                }
            }
            if($type == 'first') {
                if(isset($list['pg_goodsname']) && $list['pg_goodsname']!=''){
                    $list['good_name'] = $list['pg_goodsname'];
                }else {
                    if ($list['version'] != '') {
                        if ($list['pg_series'] != '') {
                            $pg_series = '-' . $list['pg_series'];
                        } else {
                            $pg_series = '';
                        }
                        $list['good_name'] = $list['brand_name'] . $pg_series . '-' . $list['version'];
                    }else{
                        $list['goods_number'] = str_replace($list['brand_name'], '', $list['pg_goodsname']);
                    }
                }
                if ($list['pg_series'] != '') {
                    $list['goods_number'] = $list['pg_series'] . '-' . $list['version'];
                } else {
                    $list['goods_number'] = $list['version'];
                }
            }
        }
        return $list;
    }

    /**
     * 根据商品编码查询商品数据
     * @param string $code 商品编码
     * @param string $type 请求类型  1商品编号  2平台sku
     * @return mixed
     */
    public static function getGoodsByCode($code,$type) {
        if($type == 1) {
            $goods = DB::table('pj_goods as g')
                ->select('g.brand_name', 'g.pg_series', 'g.version', 'g.prod_code as goods_number', 'g.pg_id as goods_id','cd_id')
                ->leftjoin('pj_goodcode as gc', 'g.pg_id', '=', 'gc.pgc_pgid')
                ->where('gc.pgc_code', '=', $code)
                ->get()
                ->toArray();
        }else{
            $goods = DB::table('pj_goods as g')
                ->select('g.brand_name', 'g.pg_series', 'g.version', 'g.prod_code as goods_number', 'g.pg_id as goods_id','jd.pt_id','cd_id')
                ->leftjoin('jd_bound as jd', 'g.pg_id', '=', 'jd.goods_id')
                ->where('jd.sku_id', '=', $code)
                ->get()
                ->toArray();
        }

        if (!empty($goods)) {
            $goods = GoodsService::addGoodsName($goods, ['pg_series','brand_name','version', 'goods_number']);
            return $goods[0];

        } else {
            return false;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加或编辑商品信息erp系统
     * @param array $input 操作信息
     * @retrun /multitype:array
     * @author dou 2022/2/17 17:55
     * |---------------------------------------------------------------------------------
    */
    public static function updateWarehouseGood ( $input , $session ){
        $data = self::getGoodsByKey('zp_id',$input['zp_id'],[],'first');
        $poss = $input;
        $children_id = $input['children_id']??'';
        unset($poss['children_id']);
        $new = 'X'.$input['good_code'];
        unset($poss['good_code']);
        $brabds = PjBrandsService::getAll();
        $brabds = CommonService::jointArrayKey($brabds, 'zp_id');
        $brand = $brabds[$input['gs_bid']]['id'];
        if(!$brand){
            $goodbrand['brand_name'] = $input['brand_name'];
            $goodbrand['sord'] = 'Z';
            $goodbrand['brand_remark'] = '智配同步品牌';
            $goodbrand['zp_id'] = $input['gs_bid'];
            $addbrand = PjBrandsService::addGoodsBrand($goodbrand, $session, '');
            if($addbrand['ErrorCode']==1){
                $brand = $addbrand['Data'];
            }else{
                return $addbrand;
            }
        }
        $poss['gs_bid'] = $brand;
        $poss['cd_id'] = 3;
        $poss['gs_id'] = 0;
        $poss['general_version'] = $input['good_code'];
        $poss['sort_directory'] = '车膜';
        DB::beginTransaction(); //开启事务
        if($data){
            $poss['oper_time'] = date('Y-m-d H:i:s');
            $rea = PjGoods::where('pg_id',$data['pg_id'])->update($poss);
            $good_code = GoodCode::where('pgc_pgid',$data['pg_id'])->value('pgc_code');
            if(!$good_code){
                $res = GoodCode::insert(['pgc_pgid'=>$data['pg_id'],'pgc_type'=>1,'pgc_code'=>$input['good_code'],'new'=>$new]);
            }else{
                if($good_code != $input['good_code']){
                    $res = GoodCode::where('pgc_pgid',$data['pg_id'])->update(['pgc_code'=>$input['good_code'],'new'=>$new]);
                }else{
                    $res = 1;
                }
            }
            $reb = PjGoods::where("pg_parentid",$data['pg_id'])->update(['pg_parentid'=>0]);
            if($children_id!='') {
                $reb = PjGoods::whereIn("zp_id",explode(',', $children_id))->update(['pg_parentid'=>$rea]);
            }else{
                $reb = true;
            }
            if($rea && $res && $reb){
                $BaseController = new BaseController();
                $BaseController->insertingLog("编辑商品，",$input['sys_bh'],"库房编辑商品信息","商品管理",'',$session['admin_acc']);
                DB::commit();
                return ['Data' => [], 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
            }else{
                DB::rollback();
                return ['Data' => [], 'ErrorMessage' => '操作失败', 'ErrorCode' => 9200];
            }

        }else{
            $rea = PjGoods::insertGetId($poss);
            if($rea){
                if($children_id!='') {
                    $reb = PjGoods::whereIn("zp_id",explode(',', $children_id))->update(['pg_parentid'=>$rea]);
                }else{
                    $reb = true;
                }
                $res = GoodCode::insert(['pgc_pgid'=>$rea,'pgc_type'=>1,'pgc_code'=>$input['good_code'],'new'=>$new]);
                if($res && $reb){
                    $BaseController = new BaseController();
                    $BaseController->insertingLog("添加商品，",$input['sys_bh'],"库房添加商品信息","商品管理",'',$session['admin_acc']);
                    DB::commit();
                    return ['Data' => [], 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
                }else{
                    DB::rollback();
                    return ['Data' => [], 'ErrorMessage' => '操作失败', 'ErrorCode' => 9200];
                }
            }else{
                DB::rollback();
                return ['Data' => [], 'ErrorMessage' => '操作失败', 'ErrorCode' => 9200];
            }
        }
    }
}
