<?php


namespace App\Services\goods;


use Api\PhpServices\Idgen\Idgen;
use Api\PhpServices\Ksy\Ks3Api;
use Api\PhpServices\Ksy\Ksyun;
use Api\PhpServices\Sensitive\Sensitive;
use Api\PhpUtils\Common\BaseConvert;
use Api\PhpUtils\Common\GoodsSkuId;
use Api\PhpUtils\Http\HttpUtil;
use App\Exception\custom\GoodsException;
use App\Exception\custom\MarketingException;
use App\Models\goods\mysql\Category;
use App\Models\goods\mysql\GoodsOperationRecord;
use App\Models\goods\mysql\GoodsSku;
use App\Models\goods\mysql\GoodsSkuPicRecord;
use App\Models\goods\mysql\GoodsSkuSubShop;
use App\Models\goods\mysql\GoodsSnapshot;
use App\Models\goods\mysql\GoodsSpu;
use App\Models\goods\mysql\LifeAccountShopNum;
use App\Models\goods\mysql\Ota;
use App\Models\goods\mysql\PaySuccessGoodsCallbackRecord;
use App\Models\goods\mysql\PindanGoodsSku;
use App\Models\goods\mysql\Shop;
use App\Models\marketing\mysql\Distributor;
use App\Models\marketing\mysql\Marketing;
use App\Models\marketing\mysql\MarketingGoods;
use App\Models\marketing\mysql\MarketingPindan;
use App\Models\shop\mysql\SubShop;
use App\Services\marketing\DistributorService;
use App\Services\marketing\MarketingGoodsService;
use App\Services\shop\ShopService;
use App\Services\common\CommonService;

use Api\PhpUtils\Http\Request;
use App\Exception\custom\InterfaceException;


class GoodsService
{
    const CHARGEFEE = 0.006;
    /**
     * 通过发号器拿 id （非雪花）
     * number，获取店铺shop_id用生活号id后两位，商品相关的这里是shop_id的后两位
     * @param $number
     * @param $type
     * @param int $count
     * @return array|mixed
     */
    public static function getIdgenId($number, $type, $count = 1)
    {
        $res = Idgen::get(appConfig('idgen.partner'), appConfig('idgen.key'), [], [[
            "type" => $type,
            'number' => (int)$number,
            "count" => $count]]);
        return $res['id_datetime'][$type] ?? [];
    }

    /**
     * 雪花id
     * @param $type
     * @param int $count
     * @return array|mixed
     */
    public static function getSnowIdgenId($type, $count = 1)
    {
        $res = Idgen::get(appConfig('idgen.partner'), appConfig('idgen.key'), [[
            "type" => $type,
            "count" => $count]], []);
        return $res['id_snow'][$type] ?? [];
    }

    /**
     * 添加商品
     * @param array $params
     * @return mixed
     * @throws GoodsException
     */
    public static function addGoods($params = [])
    {
        $marketingType = !empty($params['marketing_type']) ? $params['marketing_type'] : 0;
        if ($marketingType == Marketing::MARKETING_TYPE_PINDAN) {
            return MarketingPindanGoodsService::pindanMarketingAddGoods($params);
        } else {
            return self::generalAddGoods($params);
        }
    }

    /**
     * 普通商品
     * @param $params
     * @return mixed
     * @throws GoodsException
     * @throws InterfaceException
     */
    private static function generalAddGoods($params)
    {
        GoodsSpu::beginTransaction();

        //生活号信息
        $url = config('interface', 'merchant.lifeaccount.get_life_account_by_id');
        if (empty($url)) {
            throw new InterfaceException(['cus' => 0]);
        }
        $lifeAccountRes = (new Request())->get($url, ["life_account_id" => $params["life_account_id"]]);
        if (empty($lifeAccountRes["response"]["result"])) {
            throw new GoodsException(['cus' => 29]);
        }

        $lifeAccount = [
            "life_account_id" => $params["life_account_id"],
            "merchant_id" => $lifeAccountRes["response"]["result"]["merchant_id"],
        ];
        $shopId = self::addShop($lifeAccount);
        $spuData = self::addGoodsSpu($shopId, $params);
        $skuId = self::addGoodsSku($spuData, $shopId, $params);

        //门店
        $subShopIdStr = $params["sub_shop_ids"];//逗号分割
        self::addDealSubShopList($subShopIdStr, $shopId, $skuId);

        //商品操作记录
        $record = [
            "goods_spu_id" => $spuData["goods_spu_id"],
            "goods_sku_id" => $skuId,
            "operator_id" => $params["publish_user_id"],
            "operator_name" => $params["user_name"],
            "goods_status" => GoodsSku::STATUS_AUDIT,
            "online_status" => GoodsSku::ONLINE_STATUS_NO_ONLINE,
            "before_version" => 1,
            "after_version" => 1,
            "note" => empty($params["rejected_reason"]) ? "" : $params["rejected_reason"],
        ];
        GoodsOperationRecord::insertRecord($record);

        if (!GoodsSpu::commit()) {
            GoodsSpu::rollback();
            throw new GoodsException(["cus" => 0]);
        }
        return $skuId;
    }

    /**
     * 添加spu
     * @param $shopId
     * @param array $spuData
     * @return mixed
     * @throws GoodsException
     */
    public static function addGoodsSpu($shopId, $spuData = [])
    {
        $res = self::getIdgenId(substr($shopId, -2), "goods");
        if (empty($res)) {
            throw new GoodsException(['cus' => 2]);
        }
        $spuId = $res[0];
        $spuParams = [
            "goods_spu_id" => $spuId,
            "shop_id" => $shopId,
            "life_account_id" => $spuData["life_account_id"],
            "publish_user_id" => $spuData["publish_user_id"],
            "goods_name" => $spuData["goods_name"],
            "desc_pic_url" => $spuData["desc_pic_url"],
            "desc" => $spuData["desc"],
            "goods_type" => GoodsSpu::TYPE_VIRTUAL,
            "goods_sub_type" => GoodsSpu::SUB_TYPE_TO_SHOP,
            "goods_sale_type" => empty($spuData["setmeal"]) ? GoodsSpu::SALE_TYPE_NO_COMBINATION : GoodsSpu::SALE_TYPE_COMBINATION,
            "rule_limit" => $spuData["rule_limit"],
            "rule_desc" => $spuData["rule_desc"],
            "rule_refund" => $spuData["rule_refund"],
        ];
        GoodsSpu::save($spuParams);
        return $spuParams;
    }

    /**
     * 添加sku
     * @param $spuId
     * @param $shopId
     * @param array $skuData
     * @return mixed
     * @throws GoodsException
     */
    private static function addGoodsSku($spuData, $shopId, $skuData = [])
    {
        $res = self::getIdgenId(substr($shopId, -2), "goods");
        if (empty($res)) {
            throw new GoodsException(['cus' => 2]);
        }
        $skuId = GoodsSkuId::generateGoodSkuId($res[0], $skuData["category_1_id"], $skuData["category_2_id"], $spuData["goods_type"]);

        if ($skuData["expiration_time"] < date("Y-m-d H:i:s")) {
            throw new GoodsException(['cus' => 16]);
        }
        if ($skuData["price"] <= 0) {
            throw new GoodsException(['cus' => 33]);
        }

        if ($skuData["price"] > 50000) {
            throw new GoodsException(['cus' => 34]);
        }
        $checkGoodsName = self::isHaveSensitive($skuData["goods_name"], 1);
        if ($checkGoodsName) {
            throw new GoodsException(['cus' => 19]);
        }
        $checkGoodsDesc = self::isHaveSensitive($skuData["desc"], 2);
        if ($checkGoodsDesc) {
            throw new GoodsException(['cus' => 20]);
        }
        if (!empty($skuData["introduce"])) {
            $checkGoodsIntroduce = self::isHaveSensitive($skuData["introduce"], 3);
            if ($checkGoodsIntroduce) {
                throw new GoodsException(['cus' => 21]);
            }
        }

        $checkGoodsRuleDesc = self::isHaveSensitive($skuData["rule_desc"], 2);
        if ($checkGoodsRuleDesc) {
            throw new GoodsException(['cus' => 22]);
        }

        if (!empty($skuData["rule_start_time"]) || !empty($skuData["rule_end_time"])) {
            self::checkoutRuleTime($skuData["rule_start_time"], $skuData["rule_end_time"]);
        }

        $skuParams = [
            "goods_sku_id" => $skuId,
            "goods_spu_id" => $spuData["goods_spu_id"],
            "life_account_id" => $skuData["life_account_id"],
            "shop_id" => $shopId,
            "publish_user_id" => $skuData["publish_user_id"],
            "category_1_id" => $skuData["category_1_id"],
            "category_2_id" => $skuData["category_2_id"],
            "goods_name" => $skuData["goods_name"],
            "desc_pic_url" => $skuData["desc_pic_url"],
            "desc" => $skuData["desc"],
            "introduce" => empty($skuData["introduce"]) ? "" : $skuData["introduce"],
            "introduce_pic_url" => $skuData["introduce_pic_url"],
            "expiration_time" => $skuData["expiration_time"],
            "rule_limit" => $skuData["rule_limit"],
            "rule_desc" => $skuData["rule_desc"],
            "rule_refund" => $skuData["rule_refund"],
            "rule_date_type" => empty($skuData["rule_date_type"]) ? GoodsSku::RULE_DATE_TYPE_1 : $skuData["rule_date_type"],
            "rule_start_time" => empty($skuData["rule_start_time"]) ? "" : $skuData["rule_start_time"],
            "rule_end_time" => empty($skuData["rule_end_time"]) ? "" : $skuData["rule_end_time"],
            "inventory_total" => $skuData["inventory"],
            "inventory_rest" => $skuData["inventory"],
            "original_price" => empty($skuData["original_price"]) ? '' : $skuData["original_price"] * 100,
            "price" => $skuData["price"] * 100,
            "online_start_time" =>  empty($skuData["online_start_time"]) ? "" : $skuData["online_start_time"],
            "online_end_time" =>  empty($skuData["online_end_time"]) ? "" : $skuData["online_end_time"],
            "online_type" => empty($skuData["online_type"]) ? "" : $skuData["online_type"],
        ];
        if (!empty($skuData["setmeal"])) {
            $skuParams["setmeal"] = $skuData["setmeal"];
        }

        $online_type = empty($skuData["online_type"]) ? 0 : $skuData["online_type"];

        switch ($online_type) {
            case 1:
                $skuParams['online_status'] = 0;
                $skuParams['online_start_time'] = date("Y-m-d H:i:s");
                break;
            case 2:
                $skuParams['online_status'] = 0;
                break;
            case 3:
                $skuParams['online_status'] = 0;
                break;
            default:
                $skuParams['online_type'] = 1;
                $skuParams['online_status'] = 0;
                $skuParams['online_start_time'] = date("Y-m-d H:i:s");
                break;
        }

        if (!empty($skuData["online_type"])) {
            //立即上架和定时上架
            if (in_array($skuData["online_type"], [1,2])) {
                if ($skuData["expiration_time"] <= $skuData['online_start_time']) {
                    throw new GoodsException(["cus" => 52]);
                }
            }
        }

        GoodsSku::save($skuParams);
        self::addGoodsSkuPicRecord($skuId, $skuData);
        return $skuId;
    }

    /**
     * 添加商铺
     * @param $lifeAccount
     * @return mixed
     * @throws GoodsException
     */
    public static function addShop($lifeAccount)
    {
        $lifeAccountId = $lifeAccount["life_account_id"];
        $shop = Shop::getRecordMaster(['life_account_id' => $lifeAccountId]);

        if (empty($shop)) {
            $res = self::getIdgenId(substr($lifeAccountId, -2), "goods");
            if (empty($res)) {
                throw new GoodsException(['cus' => 1]);
            }
            $shopId = $res[0];
            Shop::save([
                "shop_id" => $shopId,
                "life_account_id" => $lifeAccountId,
                "merchant_id" => $lifeAccount["merchant_id"],
                "status" => Shop::STATUS_ONLINE,
            ]);

            $shopNum = LifeAccountShopNum::getRecord(["life_account_id" => $lifeAccountId]);
            if (empty($shopNum)) {
                LifeAccountShopNum::save(["life_account_id" => $lifeAccountId, "number" => 1]);
            } else {
                LifeAccountShopNum::save(["number" => $shopNum["number"] + 1], ["life_account_id" => $lifeAccountId]);
            }
        } else {
            $shopId = $shop[0]["shop_id"];
        }
        return $shopId;
    }

    /**
     * 增加商品时候处理门店信息
     * @param $subShopIdStr
     * @param $shopId
     * @param $skuId
     */
    public static function addDealSubShopList($subShopIdStr, $shopId, $skuId)
    {
        if (!empty($subShopIdStr)) {
            $subShopIds = explode(",", $subShopIdStr);
            ShopService::dealShopId($subShopIds, $shopId);

            foreach ($subShopIds as $subShopId) {
                GoodsSkuSubShop::save(["goods_sku_id" => $skuId, "sub_shop_id" => $subShopId]);
            }
        }
    }

    /**
     * 编辑商品时候处理门店信息
     * @param $subShopIdStr
     * @param $shopId
     * @param $skuId
     */
    private static function editDealSubShopList($subShopIdStr, $shopId, $skuId)
    {
        if (!empty($subShopIdStr)) {
            $subShopIds = explode(",", $subShopIdStr);
            ShopService::dealShopId($subShopIds, $shopId);

            $list = GoodsSkuSubShop::select("*", ["goods_sku_id" => $skuId]);
            if (!empty($list)) {
                $goodsSkuSubShopIds = [];
                foreach ($list as $item) {
                    $goodsSkuSubShopIds[] = $item["goods_sku_sub_shop_id"];
                }
                GoodsSkuSubShop::deleteRecord(["goods_sku_sub_shop_id" => $goodsSkuSubShopIds]);
            }

            foreach ($subShopIds as $subShopId) {
                GoodsSkuSubShop::save(["goods_sku_id" => $skuId, "sub_shop_id" => $subShopId]);
            }
        }
    }

    /**
     * 审核
     * @param array $params
     * @return bool
     * @throws GoodsException
     */
    public static function audit($params = [])
    {
        $goodsSpuId = $params["goods_spu_id"];
        $status = $params["audit_status"];
        $operatorId = empty($params["user_id"]) ? 0 : $params["user_id"];
        $operatorName = $params["user_name"];
        //为避免下边逻辑判断复杂
        $params["rejected_reason"] = isset($params["rejected_reason"]) ? $params["rejected_reason"] : '';

        $goodsSpu = GoodsSpu::get("*", ["goods_spu_id" => $goodsSpuId]);
        if (empty($goodsSpu)) {
            throw new GoodsException(["cus" => 15]);
        }
        //权限判断
        if (!empty($params["life_account_id"]) && $goodsSpu["life_account_id"] != $params["life_account_id"]) {
            throw new GoodsException(["cus" => 13]);
        }

        //审核状态是否正确
        if (!in_array($status, [GoodsSku::STATUS_PASS, GoodsSku::STATUS_REJECT])) {
            throw new GoodsException(["cus" => 12]);
        }
        //驳回时候要有原因
        if ($status == GoodsSku::STATUS_REJECT && strlen(trim($params["rejected_reason"])) == 0) {
            throw new GoodsException(["cus" => 9]);
        }

        GoodsSku::beginTransaction();
        $goodsSkuList = GoodsSku::select("*", ["goods_spu_id" => $goodsSpuId]);
        if (!empty($goodsSkuList)) {
            foreach ($goodsSkuList as $sku) {
                if ($sku["audit_status"] == GoodsSku::STATUS_PASS || $sku["audit_status"] == GoodsSku::STATUS_REJECT) {
                    throw new GoodsException(["cus" => 10]);
                }
                if ($status == GoodsSku::STATUS_PASS && $sku["expiration_time"] < date("Y-m-d H:i:s")) {
                    throw new GoodsException(["cus" => 30]);
                }
                if ($status == GoodsSku::STATUS_PASS && $sku["inventory_rest"] <= 0) {
                    throw new GoodsException(["cus" => 24]);
                }
                $goodsSkuId = $sku["goods_sku_id"];

                $rejectedReason = strlen(trim($params["rejected_reason"])) == 0 ? "" : $params["rejected_reason"];
                if ($status == GoodsSku::STATUS_PASS) {
                    $statusData = [
                        "online_status" => GoodsSku::ONLINE_STATUS_ONLINE,
                        "audit_status" => $status,
                        "rejected_reason" => $rejectedReason
                    ];
                } else {
                    $statusData = [
                        "audit_status" => $status,
                        "rejected_reason" => $rejectedReason
                    ];
                }
                
                if ($status == GoodsSku::STATUS_PASS) {
                    $online_type = empty($sku["online_type"]) ? 0 : $sku["online_type"];
                    if ($online_type == 1) {
                        $statusData['online_status'] = GoodsSku::ONLINE_STATUS_ONLINE;
                        $statusData['online_start_time'] = date("Y-m-d H:i:s");
                    }
                    
                    //定点上架
                    if ($online_type == 2) {
                        $onlineStartTime = empty($sku["online_start_time"]) ? 0 : strtotime($sku["online_start_time"]);
                        if ($onlineStartTime > time()) {
                            $statusData['online_status'] = GoodsSku::ONLINE_STATUS_OFFLINE;
                        }
                    }

                    //暂不上架
                    if ($online_type == 3) {
                        $statusData['online_status'] = GoodsSku::ONLINE_STATUS_OFFLINE;
                    }
                }

                GoodsSku::save($statusData, ["goods_sku_id" => $sku["goods_sku_id"]]);

                //商品操作记录
                if ($status == GoodsSku::STATUS_PASS) {
                    $onlineStatus = GoodsSku::ONLINE_STATUS_ONLINE;
                } else {
                    $onlineStatus = GoodsSku::ONLINE_STATUS_NO_ONLINE;
                }
                $record = [
                    "goods_spu_id" => $goodsSpuId,
                    "goods_sku_id" => $goodsSkuId,
                    "operator_id" => $operatorId,
                    "operator_name" => $operatorName,
                    "goods_status" => $status,
                    "online_status" => $onlineStatus,
                    "before_version" => $sku["goods_version"],
                    "after_version" => $sku["goods_version"],
                    "note" => $rejectedReason,
                ];
                GoodsOperationRecord::insertRecord($record);
                //审核通过并且上架后，添加镜像
                if ($status == GoodsSku::STATUS_PASS) {
                    self::addGoodsSnapshot($sku);
                }

                self::updateGoodsInfoToEs($goodsSkuId);
            }
        }
        if (!GoodsSku::commit()) {
            GoodsSku::rollback();
            throw new GoodsException(["cus" => 11]);
        }
        return true;
    }

    /**
     * 上下架
     * @param $params
     * @return bool
     * @throws GoodsException
     */
    public static function onlineOrOffline($params)
    {
        $goodsSpuId = $params["goods_spu_id"];
        $onlineStatus = $params["online_status"];
        $operatorId = empty($params["user_id"]) ? 0 : $params["user_id"];
        $operatorName = $params["user_name"];

        $goodsSpu = GoodsSpu::get("*", ["goods_spu_id" => $goodsSpuId]);
        //权限判断
        if (!empty($params["life_account_id"]) && $goodsSpu["life_account_id"] != $params["life_account_id"]) {
            throw new GoodsException(["cus" => 13]);
        }

        //审核状态是否正确
        if (!in_array($onlineStatus, [GoodsSku::ONLINE_STATUS_ONLINE, GoodsSku::ONLINE_STATUS_OFFLINE])) {
            throw new GoodsException(["cus" => 12]);
        }

        GoodsSku::beginTransaction();
        $goodsSkuList = GoodsSku::select("*", ["goods_spu_id" => $goodsSpuId]);
        if (!empty($goodsSkuList)) {
            foreach ($goodsSkuList as $sku) {
                if ($sku["audit_status"] != GoodsSku::STATUS_PASS) {
                    throw new GoodsException(["cus" => 14]);
                }
                if ($onlineStatus == GoodsSku::ONLINE_STATUS_ONLINE && $sku["expiration_time"] < date("Y-m-d H:i:s")) {
                    throw new GoodsException(["cus" => 30]);
                }
                if ($onlineStatus == GoodsSku::ONLINE_STATUS_ONLINE && $sku["inventory_rest"] <= 0) {
                    throw new GoodsException(["cus" => 24]);
                }

                $goodsSkuData = ["online_status" => $onlineStatus];

                if ($onlineStatus == GoodsSku::ONLINE_STATUS_OFFLINE){
                    $goodsSkuData['online_type'] = 3;
                    $goodsSkuData['online_start_time'] = null;
                    $goodsSkuData['online_end_time'] = null;
                }

                if ($onlineStatus == GoodsSku::ONLINE_STATUS_ONLINE){
                    $goodsSkuData['online_type'] = 1;
                    $goodsSkuData['online_start_time'] = date("Y-m-d H:i:s");
                }

                $goodsSkuId = $sku["goods_sku_id"];
                GoodsSku::save($goodsSkuData, ["goods_sku_id" => $goodsSkuId]);

                //商品操作记录
                $record = [
                    "goods_spu_id" => $goodsSpuId,
                    "goods_sku_id" => $goodsSkuId,
                    "operator_id" => $operatorId,
                    "operator_name" => $operatorName,
                    "goods_status" => $sku["audit_status"],
                    "online_status" => $onlineStatus,
                    "before_version" => $sku["goods_version"],
                    "after_version" => $sku["goods_version"],
                    "note" => empty($params["rejected_reason"]) ? "" : $params["rejected_reason"],
                ];
                GoodsOperationRecord::insertRecord($record);

                //上架的话，生成快照
                if (GoodsSku::ONLINE_STATUS_ONLINE == $onlineStatus) {
                    self::addGoodsSnapshot($sku);
                }

                self::updateGoodsInfoToEs($goodsSkuId);
            }
        }
        if (!GoodsSku::commit()) {
            GoodsSku::rollback();
            throw new GoodsException(["cus" => 11]);
        }
        return true;
    }

    /**
     * 设置商品上架
     * @date      2021-08-25
     * @copyright [copyright]
     * @license   [license]
     * @version   [version]
     * @param     $params [description]
     * @return    array  [description]
     */
    public static function onlineSite($params)
    {
        $goodsSpuId = $params["goods_spu_id"];
        $onlineType = !empty($params["online_type"]) ? $params["online_type"] : 0;
        $onlineStartTime = !empty($params["online_start_time"]) ? $params["online_start_time"] : null;
        $onlineEndTime = !empty($params["online_end_time"]) ? $params["online_end_time"] : null;
        GoodsSku::beginTransaction();
        $goodsSkuList = GoodsSku::select("*", ["goods_spu_id" => $goodsSpuId]);
        if (!empty($goodsSkuList)) {
            foreach ($goodsSkuList as $sku) {

                if ($sku["expiration_time"] < date("Y-m-d H:i:s")) {
                    throw new GoodsException(["cus" => 30]);
                }

                $goodsSkuId = $sku["goods_sku_id"];
                $goodsSkuData = [
                    "online_type" => $onlineType,
                    "online_start_time" => $onlineStartTime,
                    "online_end_time" => $onlineEndTime
                ];
                if ($onlineType == 1) {
                    if ($sku['audit_status'] == 1) {
                        $goodsSkuData['online_status'] = GoodsSku::ONLINE_STATUS_ONLINE;
                    }
                    $goodsSkuData['online_start_time'] = date("Y-m-d H:i:s");
                }
                
                //暂不上架
                if ($onlineType == 3) {
                    //$goodsSkuData['audit_status'] = 0;
                    if ($sku['audit_status'] == 1) {
                        $goodsSkuData['online_status'] = GoodsSku::ONLINE_STATUS_OFFLINE;
                    }else{
                        $goodsSkuData['online_status'] = 0;
                    }
                    
                }

                if ($onlineType == 2) {
                    $onlineStartTime = strtotime($goodsSkuData['online_start_time']);
                    if ($onlineStartTime > time()) {
                        if ($sku['audit_status'] == 1) {
                            $goodsSkuData['online_status'] = GoodsSku::ONLINE_STATUS_OFFLINE;
                        }else{
                            $goodsSkuData['online_status'] = 0;
                        }
                    }
                }

                //立即上架和定时上架
                if (in_array($onlineType, [1,2])) {

                    if ($sku["expiration_time"] <= $goodsSkuData['online_start_time']) {
                        throw new GoodsException(["cus" => 52]);
                    }
                }

                $operatorId = empty($params["user_id"]) ? 0 : $params["user_id"];
                $operatorName = !empty($params["user_name"]) ? $params["user_name"] : '';
                 //商品操作记录
                $record = [
                    "goods_spu_id" => $goodsSpuId,
                    "goods_sku_id" => $goodsSkuId,
                    "operator_id" => $operatorId,
                    "operator_name" => $operatorName,
                    "goods_status" => $sku["audit_status"],
                    "online_status" => !empty($goodsSkuData['online_status']) ? $goodsSkuData['online_status'] : $sku["online_status"],
                    "before_version" => $sku["goods_version"],
                    "after_version" => $sku["goods_version"],
                    "note" => empty($params["rejected_reason"]) ? "" : $params["rejected_reason"],
                ];
                GoodsOperationRecord::insertRecord($record);

                GoodsSku::save($goodsSkuData, ["goods_sku_id" => $goodsSkuId]);
                //上架的话，生成快照
                self::addGoodsSnapshot($sku);
                self::updateGoodsInfoToEs($goodsSkuId);
            }
        }
        if (!GoodsSku::commit()) {
            GoodsSku::rollback();
            throw new GoodsException(["cus" => 11]);
        }
        return true;
    }


    /**
     * 生成快照数据
     * @param $skuInfo
     */
    private static function addGoodsSnapshot($skuInfo)
    {
        $subShopList = ShopService::getRelationShop($skuInfo["goods_sku_id"]);
        $skuInfo["sub_shop"] = json_encode($subShopList);
        if (empty($skuInfo["setmeal"])) {
            $skuInfo["setmeal"] = json_encode([]);
        }
        unset($skuInfo["is_import"], $skuInfo["update_time"], $skuInfo["create_time"]);
        GoodsSnapshot::insertRecord($skuInfo);
    }

    /**
     * 商品名是否可用
     * @param $goodsName
     * @param $lifeAccountId
     * @param int $goodsSpuId
     * @return bool[]
     */
    public static function checkGoodsName($goodsName, $lifeAccountId, $goodsSpuId = 0)
    {
        if ($goodsSpuId) {
            $sku = GoodsSpu::get("*", ["goods_name" => $goodsName, "life_account_id" => $lifeAccountId, "goods_spu_id[!]" => $goodsSpuId]);
        } else {
            $sku = GoodsSpu::get("*", ["goods_name" => $goodsName, "life_account_id" => $lifeAccountId]);
        }
        $nameCanUse = false;
        if (empty($sku)) {
            $nameCanUse = true;
        }
        return ["can_use" => $nameCanUse];
    }

    /**
     * 编辑商品
     * @param array $params
     * @return bool
     * @throws GoodsException
     */
    public static function editGoods($params = [])
    {
        $marketingType = !empty($params['marketing_type']) ? $params['marketing_type'] : 0;
        if ($marketingType == Marketing::MARKETING_TYPE_PINDAN) {
            return MarketingPindanGoodsService::pindanMarketingEditGoods($params);
        } else {
            return self::generalEditGoods($params);
        }
    }

    /**
     * 普通商品编辑
     * @param $params
     * @return bool
     * @throws GoodsException
     * @throws InterfaceException
     */
    public static function generalEditGoods($params)
    {
        $goodsSpuId = $params["goods_spu_id"];
        $goodsSpu = GoodsSpu::get("*", ["goods_spu_id" => $goodsSpuId]);
        if (empty($goodsSpu)) {
            throw new GoodsException(["cus" => 15]);
        }

        GoodsSpu::beginTransaction();

        self::editGoodsSpu($goodsSpu, $params);
        $goodsSkuList = GoodsSku::select("*", ["goods_spu_id" => $goodsSpuId]);
        if (!empty($goodsSkuList)) {
            foreach ($goodsSkuList as $sku) {
                self::editGoodsSku($sku["goods_sku_id"], $sku, $params);
            }
        }

        if (!GoodsSpu::commit()) {
            GoodsSpu::rollback();
            throw new GoodsException(["cus" => 0]);
        }

        foreach ($goodsSkuList as $sku) {
            self::updateGoodsInfoToEs($sku["goods_sku_id"]);
        }

        return true;
    }

    /**
     * @param $goodsSpu
     * @param array $params
     * @return \Api\PhpUtils\Mysql\MysqlBase
     * @throws GoodsException
     */
    private static function editGoodsSpu($goodsSpu, $params = [])
    {
        return GoodsSpu::save([
            "goods_name" => $params["goods_name"],
            "desc_pic_url" => $params["desc_pic_url"],
            "desc" => $params["desc"],
            "goods_type" => GoodsSpu::TYPE_VIRTUAL,
            "goods_sub_type" => GoodsSpu::SUB_TYPE_TO_SHOP,
            "goods_sale_type" => empty($params["setmeal"]) ? GoodsSpu::SALE_TYPE_NO_COMBINATION : GoodsSpu::SALE_TYPE_COMBINATION,
            "rule_limit" => $params["rule_limit"],
            "rule_desc" => $params["rule_desc"],
            "rule_refund" => $params["rule_refund"],
        ], ["goods_spu_id" => $goodsSpu["goods_spu_id"]]);
    }

    /**
     * @param $goodsSkuId
     * @param $skuData
     * @param array $params
     * @return \Api\PhpUtils\Mysql\MysqlBase
     * @throws GoodsException
     */
    private static function editGoodsSku($goodsSkuId, $skuData, $params = [])
    {
        if ($params["expiration_time"] < date("Y-m-d H:i:s")) {
            throw new GoodsException(['cus' => 16]);
        }
        $inventoryCount = $skuData["inventory_rest"] + $params["inventory_add"];
        //$inventoryCount = $params["inventory"];
        if ($inventoryCount < 0) {
            throw new GoodsException(['cus' => 18]);
        }
        $checkGoodsName = self::isHaveSensitive($params["goods_name"], 1);
        if ($checkGoodsName) {
            throw new GoodsException(['cus' => 19]);
        }
        $checkGoodsDesc = self::isHaveSensitive($params["desc"], 2);
        if ($checkGoodsDesc) {
            throw new GoodsException(['cus' => 20]);
        }
        if (!empty($params["introduce"])) {
            $checkGoodsIntroduce = self::isHaveSensitive($params["introduce"], 3);
            if ($checkGoodsIntroduce) {
                throw new GoodsException(['cus' => 21]);
            }
        }
        $checkGoodsRuleDesc = self::isHaveSensitive($params["rule_desc"], 2);
        if ($checkGoodsRuleDesc) {
            throw new GoodsException(['cus' => 22]);
        }
        if (!empty($params["rule_start_time"]) || !empty($params["rule_end_time"])) {
            self::checkoutRuleTime($params["rule_start_time"], $params["rule_end_time"]);
        }

        if ($params["price"] <= 0) {
            throw new GoodsException(['cus' => 33]);
        }

        if ($params["price"] > 50000) {
            throw new GoodsException(['cus' => 34]);
        }

        //门店
        $subShopIdStr = $params["sub_shop_ids"];//逗号分割
        self::editDealSubShopList($subShopIdStr, $skuData["shop_id"], $goodsSkuId);

        $skuParams = [
            "category_1_id" => $params["category_1_id"],
            "category_2_id" => $params["category_2_id"],
            "goods_name" => $params["goods_name"],
            "desc_pic_url" => $params["desc_pic_url"],
            "desc" => $params["desc"],
            "introduce" => empty($params["introduce"]) ? "" : $params["introduce"],
            "introduce_pic_url" => $params["introduce_pic_url"],
            "expiration_time" => $params["expiration_time"],
            "rule_limit" => $params["rule_limit"],
            "rule_desc" => $params["rule_desc"],
            "rule_refund" => $params["rule_refund"],
            "rule_date_type" => empty($params["rule_date_type"]) ? GoodsSku::RULE_DATE_TYPE_1 : $params["rule_date_type"],
            "rule_start_time" => empty($params["rule_start_time"]) ? "" : $params["rule_start_time"],
            "rule_end_time" => empty($params["rule_end_time"]) ? "" : $params["rule_end_time"],
            "inventory_total" => $skuData["inventory_total"] + $params["inventory_add"],
            //"inventory_total" => $params["inventory"],
            "inventory_rest" => $inventoryCount,
            "original_price" => empty($params["original_price"]) ? 0 : $params["original_price"] * 100,
            "price" => $params["price"] * 100,
            "clear_price" => empty($params["clear_price"]) ? 0 : $params["clear_price"] * 100,
            "goods_version" => (int)$skuData["goods_version"] + 1,
        ];

        //验证结算价格/分销金额
        self::checkClearPrice($goodsSkuId, $skuParams);

        if (self::isInitGoodsStatus($params, $skuData)) {
            $skuParams["audit_status"] = GoodsSku::STATUS_AUDIT;
            $skuParams["online_status"] = GoodsSku::ONLINE_STATUS_NO_ONLINE;
        }
        if (!empty($params["setmeal"])) {
            $skuParams["setmeal"] = $params["setmeal"];
        }

        if (!empty($params["online_start_time"])) {
            $skuParams['online_start_time'] = empty($params["online_start_time"]) ? "" : $params["online_start_time"];
        }

        if (!empty($params["online_end_time"])) {
            $skuParams['online_end_time'] = empty($params["online_end_time"]) ? "" : $params["online_end_time"];
        }

        if (!empty($params["online_type"])) {
            $skuParams['online_type'] = empty($params["online_type"]) ? 0 : $params["online_type"];
        }


        if (!empty($params["online_type"])) {
            //立即上架和定时上架
            if (in_array($params["online_type"], [1,2])) {
                if ($skuData["expiration_time"] <= $skuParams['online_start_time']) {
                    throw new GoodsException(["cus" => 52]);
                }
            }
        }

        //商品操作记录
        $record = [
            "goods_spu_id" => $skuData["goods_spu_id"],
            "goods_sku_id" => $goodsSkuId,
            "operator_id" => empty($params["publish_user_id"]) ? 0 : $params["publish_user_id"],//op后台操作没有记录user_id
            "operator_name" => $params["user_name"],
            "goods_status" => GoodsSku::STATUS_AUDIT,
            "online_status" => GoodsSku::ONLINE_STATUS_NO_ONLINE,
            "before_version" => $skuData["goods_version"],
            "after_version" => $skuParams["goods_version"],
            "note" => empty($params["rejected_reason"]) ? "" : $params["rejected_reason"],
        ];
        GoodsOperationRecord::insertRecord($record);

        self::addGoodsSkuPicRecord($goodsSkuId, $skuParams);

        return GoodsSku::save($skuParams, ["goods_sku_id" => $goodsSkuId]);
    }

    /**
     * 检查结算价格
     * @param $goodsSkuId
     * @param $skuParams
     * @throws GoodsException
     */
    private static function checkClearPrice($goodsSkuId, $skuParams)
    {
        $clearPrice = $skuParams["clear_price"];
        $price = $skuParams["price"];
        $chargeFee = !empty($price) ? (float)bcmul($price , self::CHARGEFEE,2) : 0; //手续费 (分)
        if ($chargeFee<1) {
            $chargeFee = 0;
        }
        if ($clearPrice > 0 && $clearPrice > $price) {
            throw new GoodsException(['cus' => 39]);
        }

        $marketingIds = MarketingGoods::select(["marketing_id"], ["goods_sku_id" => $goodsSkuId]);
        if (!empty($marketingIds)) {
            $marketingIds = array_column($marketingIds, "marketing_id");
            $marketings = Marketing::select("*", [
                "marketing_id" => $marketingIds,
                "marketing_type"=> Marketing::MARKETING_TYPE_FENXIAO,
                "online_status" => Marketing::ONLINE_STATUS_QIDONG]
            );

            if (!empty($marketings)) {
                foreach ($marketings as $marketing) {
                    if ($clearPrice > 0) {
                        if ($marketing["commission_mode"] == Marketing::COMMISSION_MODE_RATE) {
                            $commissionTotal = ($marketing["first_commission_value"] + $marketing["second_commission_value"]) / 10000 * $price;
                            if (($price - $commissionTotal - $chargeFee) < $clearPrice) {
                                throw new GoodsException(['cus' => 40]);
                            }
                        }

                        if ($marketing["commission_mode"] == Marketing::COMMISSION_MODE_FIXED) {
                            $commissionTotal = ($marketing["first_commission_value"] + $marketing["second_commission_value"]);
                            if (($price - $commissionTotal - $chargeFee) < $clearPrice) {
                                throw new GoodsException(['cus' => 40]);
                            }
                        }
                    }else{

                        //比例计算
                        if ($marketing["commission_mode"] == Marketing::COMMISSION_MODE_RATE) {
                            $commissionTotal = ($marketing["first_commission_value"] + $marketing["second_commission_value"]) / 10000 * $price;
                            if ($price < ($commissionTotal+$chargeFee)) {
                                throw new MarketingException(['cus'=>33]);
                            }
                        }

                        //固定金额
                        if ($marketing["commission_mode"] == Marketing::COMMISSION_MODE_FIXED) {
                            $commissionTotal = ($marketing["first_commission_value"] + $marketing["second_commission_value"]);
                            if ($price < ($commissionTotal+$chargeFee)) {
                                throw new MarketingException(['cus'=>33]);
                            }
                        }
                    }
                }
            }else{
                if ($clearPrice > 0 && (($price - $chargeFee) < $clearPrice)) {
                    throw new GoodsException(['cus' => 40]);
                }
            }
        }
    }

    /**
     * 是否要初始化状态
     * @param $params
     * @param $sku
     * @return bool
     */
    private static function isInitGoodsStatus($params, $sku)
    {
        $introduce = empty($params["introduce"]) ? "" : $params["introduce"];
        return $params["category_1_id"] != $sku["category_1_id"]
            || $params["category_2_id"] != $sku["category_2_id"]
            || $params["goods_name"] != $sku["goods_name"]
            || $params["desc_pic_url"] != $sku["desc_pic_url"]
            || $params["desc"] != $sku["desc"]
            || $introduce != $sku["introduce"]
            || $params["introduce_pic_url"] != $sku["introduce_pic_url"]
            || $params["expiration_time"] != $sku["expiration_time"]
            || $params["rule_desc"] != $sku["rule_desc"]
            || $params["rule_refund"] != $sku["rule_refund"]
            || $params["original_price"] != $sku["original_price"]
            || $params["price"] != $sku["price"]
            || $params["clear_price"] != $sku["clear_price"];
    }

    /**
     * @param $ruleStartTime
     * @param $ruleEndTime
     * @throws GoodsException
     */
    private static function checkoutRuleTime($ruleStartTime, $ruleEndTime)
    {
        $startArr = explode(":", $ruleStartTime);
        if (!(isset($startArr[0]) && (int)$startArr[0] >= 0 && (int)$startArr[0] <= 23)
            || !(isset($startArr[1]) && (int)$startArr[1] >= 0 && (int)$startArr[1] <= 59)) {
            throw new GoodsException(['cus' => 25]);
        }
        $endArr = explode(":", $ruleEndTime);
        if (!(isset($endArr[0]) && (int)$endArr[0] >= 0 && (int)$endArr[0] <= 23)
            || !(isset($endArr[1]) && (int)$endArr[1] >= 0 && (int)$endArr[1] <= 59)) {
            throw new GoodsException(['cus' => 26]);
        }
    }

    /**
     * 后台用商品详情
     * @param array $params
     * @return array
     * @throws GoodsException
     */
    public static function getGoodsSpuInfo($params = [])
    {
        $data = [];
        $goodsSpuId = $params["goods_spu_id"];
        $goodsSpu = GoodsSpu::get("*", ["goods_spu_id" => $goodsSpuId]);
        if (empty($goodsSpu)) {
            throw new GoodsException(["cus" => 15]);
        }

        $goodsSkuList = GoodsSku::select("*", ["goods_spu_id" => $goodsSpuId]);
        //当前这里一个spu对应一个sku
        if (!empty($goodsSkuList)) {
            foreach ($goodsSkuList as $key => $sku) {
                $data["goods_info"] = $sku;

                if (!empty($sku["desc_pic_url"])) {
                    $ksyun = self::getUrlList($sku["desc_pic_url"]);
                    $data["goods_info"]["desc_pic_url_list"] = $ksyun;
                }
                $data["goods_info"]["introduce_pic_url_list"] = [];
                if (!empty($sku["introduce_pic_url"])) {
                    $ksyun = self::getUrlList($sku["introduce_pic_url"]);
                    $data["goods_info"]["introduce_pic_url_list"] = $ksyun;
                }

                $data["goods_info"]["original_price"] = empty($sku["original_price"]) ? '' : (string)($sku["original_price"] / 100);
                $data["goods_info"]["clear_price"] = empty($sku["clear_price"]) ? "" : $sku["clear_price"] / 100;
                $data["goods_info"]["price"] = $sku["price"] / 100;
                $data["goods_info"]["inventory"] = $sku["inventory_rest"];
                $data["goods_info"]["online_type"] = $sku["online_type"];
                $data["goods_info"]["online_start_time"] = $sku["online_start_time"];
                $data["goods_info"]["online_end_time"] = $sku["online_end_time"];
                
                $categoryNameList = Category::select("name", ["category_id" => [$sku["category_1_id"], $sku["category_2_id"]]]);
                $data["goods_info"]["category_1_name"] = $categoryNameList[0];
                $data["goods_info"]["category_2_name"] = $categoryNameList[1];

                //门店
                $goodsSkuSubShopList = GoodsSkuSubShop::select("*", ["goods_sku_id" => $sku["goods_sku_id"]]);
                if (!empty($goodsSkuSubShopList)) {
                    $subShopIds = [];
                    foreach ($goodsSkuSubShopList as $item) {
                        $subShopIds[] = $item["sub_shop_id"];
                    }

                    $subShopList = SubShop::select("*", ["sub_shop_id" => $subShopIds]);
                    $data["goods_info"]["sub_shop"] = $subShopList;
                }

                //是否是分销活动
                $runningMarketing = MarketingGoodsService::getRunningMarketing([$sku["goods_sku_id"]]);
                $data["goods_info"]["is_fenxiao"] = false;
                if (!empty($runningMarketing[$sku["goods_sku_id"]])) {
                    $data["goods_info"]["is_fenxiao"] = true;
                }

                //当前人是否是团长
                $data["goods_info"]["is_tuanzhang"] = false;
                if (!empty($params["user_id"])) {
                    $distributorList = DistributorService::getDistributorInfo($params["user_id"]);
                    if (!empty($distributorList)) {
                        $data["goods_info"]["is_tuanzhang"] = true;
                        if (!empty($runningMarketing)) {
                            //分销返现多少钱
                            $data["goods_info"]["cash_back"] = substr(sprintf("%.4f",$runningMarketing[$sku["goods_sku_id"]] * $data["goods_info"]["price"]),0,-2);
                        }
                    }
                }
            }
        }

        
        $recordList = GoodsOperationRecord::select("*", ["goods_spu_id" => $goodsSpuId, "ORDER" => ["create_time" => "DESC"]]);
        if (!empty($recordList)) {
            foreach ($recordList as $key => $record) {
                $data["record_list"][$key]["status"] = $record["goods_status"];
                $data["record_list"][$key]["status_desc"] = GoodsOperationRecord::$statusDesc[$record["goods_status"]];
                $data["record_list"][$key]["online_status"] = $record["online_status"];
                $data["record_list"][$key]["online_status_desc"] = GoodsOperationRecord::$onlineStatusDesc[$record["online_status"]];
                $data["record_list"][$key]["create_time"] = $record["create_time"];
                $data["record_list"][$key]["operator_name"] = $record["operator_name"];
                $data["record_list"][$key]["note"] = $record["note"];
            }
        }
        return $data;
    }

    /**
     * 商品sku详情
     * @param array $params
     * @return array
     * @throws GoodsException
     */
    public static function getGoodsSkuInfo($params = [])
    {
        $goodsSukParams = GoodsSkuId::getGoodsSkuIdParams($params["goods_sku_id"]);
        if (!empty($goodsSukParams)) {
            if (isset($goodsSukParams["table_tag"]) && ($goodsSukParams["table_tag"] == GoodsSkuId::TABLE_TAG_PINDAN
            || $goodsSukParams["category_1_id"] == "00")) {
                return MarketingPindanGoodsService::pindanGoodsInfo($params);
            } else {
                return self::generalGoodsInfo($params);
            }
        } else {
            throw new GoodsException(["cus" => 41]);
        }

    }

    /**
     * 普通商品详情，通过sku_id查询
     * @param $params
     * @return array
     * @throws GoodsException
     */
    private static function generalGoodsInfo($params)
    {
        $data = [];
        $sku = GoodsSku::get(["life_account_id", "goods_sku_id", "category_1_id", "category_2_id", "goods_name",
                "desc_pic_url", "desc", "introduce", "introduce_pic_url", "expiration_time", "rule_limit",
                "rule_desc", "rule_refund", "rule_date_type", "rule_start_time", "rule_end_time", "inventory_rest",
                "total_amount_sold", "original_price", "price"]
            , ["goods_sku_id" => $params["goods_sku_id"]]);
        if (empty($sku)) {
            throw new GoodsException(["cus" => 15]);
        }

        $data["goods_info"] = $sku;
        $data["goods_info"]["original_price"] = empty($sku["original_price"]) ? '' : (string)($sku["original_price"] / 100);
        $data["goods_info"]["price"] = $sku["price"] / 100;
        $data["goods_info"]["clear_price"] = empty($sku["clear_price"]) ? 0 : $sku["clear_price"] / 100;
        $data["goods_info"]["desc_pic_url_list"] = [];
        if (!empty($sku["desc_pic_url"])) {
            $ksyun = self::getUrlList($sku["desc_pic_url"]);
            $data["goods_info"]["desc_pic_url_list"] = $ksyun;
        }
        $data["goods_info"]["introduce_pic_url_list"] = [];
        if (!empty($sku["introduce_pic_url"])) {
            $ksyun = self::getUrlList($sku["introduce_pic_url"]);
            $data["goods_info"]["introduce_pic_url_list"] = $ksyun;
        }
        $categoryNameList = Category::select("name", ["category_id" => [$sku["category_1_id"], $sku["category_2_id"]]]);
        $data["goods_info"]["category_1_name"] = $categoryNameList[0];
        $data["goods_info"]["category_2_name"] = $categoryNameList[1];

        $ruleRefundDesc = GoodsSku::$ruleRefundList[$sku["rule_refund"]];
        $ruleDateTypeDesc = GoodsSku::$ruleDataTypeList[$sku["rule_date_type"]];
        $data["goods_info"]["rule"]["rule_limit"] = $sku["rule_limit"];
        $data["goods_info"]["rule"]["rule_refund"] = $ruleRefundDesc;
        $data["goods_info"]["rule"]["rule_date_type"] = $ruleDateTypeDesc;
        $data["goods_info"]["rule"]["rule_time"] = date('H:i', strtotime($sku["rule_start_time"])) . " ~ " . date('H:i', strtotime($sku["rule_end_time"]));
        $data["goods_info"]["rule"]["rule_desc"] = $sku["rule_desc"];
        $data["goods_info"]["rule"]["expiration_time"] = $sku["expiration_time"];

        //门店
        $goodsSkuSubShopList = GoodsSkuSubShop::select("*", ["goods_sku_id" => $sku["goods_sku_id"]]);
        if (!empty($goodsSkuSubShopList)) {
            $subShopIds = [];
            foreach ($goodsSkuSubShopList as $item) {
                $subShopIds[] = $item["sub_shop_id"];
            }

            $subShopList = SubShop::select("*", ["sub_shop_id" => $subShopIds]);
            foreach ($subShopList as $key => $sub) {
                $data["goods_info"]["sub_shop"][$key]["sub_shop_id"] = $sub["sub_shop_id"];
                $data["goods_info"]["sub_shop"][$key]["shop_name"] = $sub["shop_name"];
                $data["goods_info"]["sub_shop"][$key]["longitude"] = $sub["longitude"];
                $data["goods_info"]["sub_shop"][$key]["latitude"] = $sub["latitude"];
                $data["goods_info"]["sub_shop"][$key]["address"] = $sub["address"];
                $data["goods_info"]["sub_shop"][$key]["phone"] = $sub["phone"];
            }
        }

        //是否是分销活动
        $runningMarketing = MarketingGoodsService::getRunningMarketing([$params["goods_sku_id"]]);

        $data["goods_info"]["is_fenxiao"] = false;
        if (!empty($runningMarketing[$params["goods_sku_id"]])) {
            $data["goods_info"]["is_fenxiao"] = true;
        }

        $marketingInfoList = MarketingGoods::select(["marketing_id", "goods_sku_id"], ["goods_sku_id" => $params["goods_sku_id"]]);

        if (!empty($marketingInfoList)) {
            foreach ($marketingInfoList as $marketingInfo) {
                $marketingInfoIds[$marketingInfo["goods_sku_id"]] = $marketingInfo["marketing_id"];
            }
            $marketingIds = array_values($marketingInfoIds);

            $now = date("Y-m-d H:i:s");
            $resMarketingList = Marketing::select("*", ["start_time[<]" => $now, "end_time[>]" => $now, "marketing_id" => $marketingIds, "marketing_type" => Marketing::MARKETING_TYPE_FENXIAO]);
            if (!empty($resMarketingList)) {
                foreach ($resMarketingList as $res) {
                    $marketingList[$res["marketing_id"]] = $res;
                }
            }
        }

        $marketing = !empty($marketingList) ? current($marketingList) : [];
        $data["goods_info"]['goods_share_code'] = CommonService::getGoodsShareId($params);
        //当前人是否是团长
        $data["goods_info"]["is_tuanzhang"] = false;
        if (!empty($params["user_id"])) {
            $distributorList = DistributorService::getDistributorInfo($params["user_id"]);
            if (!empty($distributorList)) {
                $data["goods_info"]["is_tuanzhang"] = true;
                if (!empty($runningMarketing)) {
                    //分销返现多少钱
                    if (!empty($marketing) && $marketing['commission_mode'] == 2) {
                        $data["goods_info"]["cash_back"] = (float)sprintf("%.2f",$runningMarketing[$params["goods_sku_id"]]);
                    }else{
                        $data["goods_info"]["cash_back"] = (float)sprintf("%.2f",$runningMarketing[$params["goods_sku_id"]] * $data["goods_info"]["price"]);
                    }
                }
            }
        }
        return $data;
    }

    /**
     * op后台商品列表
     * @param array $params
     * @return array
     */
    public static function getOpGoodsSpuList($params = [])
    {
        $params['page'] = !empty($params['page']) ? $params['page'] : 1;
        $limit = !empty($params['page_size']) ? $params['page_size'] : 20;
        $page = ($params['page'] - 1) * $limit;

        $where = $data = [];
        if (!empty($params["goods_spu_id"])) {
            $where["goods_spu_id"] = $params["goods_spu_id"];
        }
        if (!empty($params["goods_name"])) {
            $where["goods_name"] = $params["goods_name"];
        }
        if (!empty($params["category_1_id"])) {
            $category1Ids = explode(",", $params["category_1_id"]);
            $where["category_1_id"] = $category1Ids;
        }
        if (!empty($params["category_2_id"])) {
            $category2Ids = explode(",", $params["category_2_id"]);
            $where["category_2_id"] = $category2Ids;
        }
        if (!empty($params["life_account_id"])) {
            $where["life_account_id"] = $params["life_account_id"];
        }
        if (!empty($params["audit_status"]) || (isset($params["audit_status"]) && $params["audit_status"] === '0')) {
            $status = explode(",", $params["audit_status"]);
            $where["audit_status"] = $status;
        }
        if (!empty($params["online_status"]) || (isset($params["online_status"]) && $params["online_status"] === '0')) {
            $onlineStatus = explode(",", $params["online_status"]);
            $where["online_status"] = $onlineStatus;
        }

        $count = GoodsSku::getCount($where);

        $where['LIMIT'] = [$page, $limit];
        $where['ORDER'] = ["create_time" => "DESC"];

        $list = GoodsSku::select(["goods_spu_id", "goods_sku_id", "goods_name", "category_1_id", "category_2_id", "life_account_id",
            "publish_user_id", "update_time", "create_time", "audit_status", "online_status","online_start_time","online_end_time","online_type"],
            $where);
        if (!empty($list)) {
            foreach ($list as $key => $item) {
                $nameList = Category::select("name", ["category_id" => [$item["category_1_id"], $item["category_2_id"]]]);
                $list[$key]["category_1_name"] = $nameList[0];
                $list[$key]["category_2_name"] = $nameList[1];

                if ($item['online_type'] == 3) {
                    $list[$key]["online_start_time"] = "";
                    $list[$key]["online_end_time"] = "";
                }

                if ($item['online_type'] == 1) {
                    $list[$key]["online_end_time"] = "";
                }
                
            }
        }
        return ["list" => $list, "count" => $count];
    }

    public static function getBGoodsSpuList($params = [])
    {

    }

    /**
     * 商家 c端商品列表
     * @param $params
     * @return array
     */
    public static function getCGoodsSkuList($params)
    {
        $lifeAccountId = $params["life_account_id"];
        $type = empty($params["type"]) ? "online" : $params["type"];
        $lastId = empty($params["last_id"]) ? "" : $params["last_id"];
        $limit = empty($params["num"]) ? 10 : $params["num"];

        $statusList = [
            ["type" => "online", "name" => "上架中"],
            ["type" => "auditing", "name" => "审核中"],
            ["type" => "rejected", "name" => "被驳回"],
            ["type" => "offline", "name" => "已下架"],
        ];

        $where = [];
        if ($type == "online") {
            $where["audit_status"] = GoodsSku::STATUS_PASS;
            $where["online_status"] = GoodsSku::ONLINE_STATUS_ONLINE;
        } else if ($type == "auditing") {
            $where["audit_status"] = GoodsSku::STATUS_AUDIT;
        } else if ($type == "rejected") {
            $where["audit_status"] = GoodsSku::STATUS_REJECT;
        } else if ($type == "offline") {
            $where["online_status"] = GoodsSku::ONLINE_STATUS_OFFLINE;
        }

        if (!empty($lastId)) {
            $where["goods_spu_id[<]"] = $lastId;
        }
        $where["life_account_id"] = $lifeAccountId;
        $where["LIMIT"] = $limit;
        $where["ORDER"] = ["goods_spu_id" => "DESC"];
        $list = GoodsSku::select(["goods_spu_id", "goods_sku_id", "goods_name", "desc", "desc_pic_url", "total_amount_sold", "inventory_rest", "original_price",
            "price", "audit_status", "online_status"], $where);

        $data = [];
        if (!empty($list)) {
            $count = count($list);
            foreach ($list as $key => $sku) {
                $sku["original_price"] = empty($sku["original_price"]) ? '' : (string)($sku["original_price"] / 100);
                $sku["price"] = $sku["price"] / 100;

                $data[] = $sku;
                if (!empty($sku["desc_pic_url"])) {
                    $ksyun = self::getUrlList($sku["desc_pic_url"], 200, 200);
                    $data[$key]["desc_pic_url_list"] = $ksyun;
                }
                $lastId = $sku["goods_spu_id"];
            }
            if ($count < $limit) {
                $lastId = "-1";
            }
        } else {
            $lastId = "-1";
        }

        return ["status_list" => $statusList, "goods_list" => $data, "last_id" => $lastId];
    }

    /**
     * 更新到es
     * @param $goodsSkuId
     * @return array|callable
     * @throws InterfaceException
     */
    public static function updateGoodsInfoToEs($goodsSkuId)
    {
        $goodsSkuInfoList = GoodsSku::getRecordMaster(["goods_sku_id" => $goodsSkuId]);
        if (!empty($goodsSkuInfoList)) {
            $goodsSkuInfo = $goodsSkuInfoList[0];
            $nameList = Category::select("name", ["category_id" => [$goodsSkuInfo["category_1_id"], $goodsSkuInfo["category_2_id"]]]);
            //生活号信息
            $url = config('interface', 'merchant.lifeaccount.get_life_account_by_id');
            if (empty($url)) {
                throw new InterfaceException(['cus' => 0]);
            }
            $lifeAccountRes = (new Request())->get($url, ["life_account_id" => $goodsSkuInfo["life_account_id"]]);
            //门店信息
            $subShopList = ShopService::getRelationShop($goodsSkuId);

            if (!empty($subShopList)) {
                foreach ($subShopList as $subShop) {
                    if (!empty($subShop["latitude"]) && !empty($subShop["longitude"])) {
                        $esId = $goodsSkuInfo["goods_sku_id"] . "_" . $subShop["sub_shop_id"];
                        $data = [
                            "doc" => [
                                "goods_sku_id" => $goodsSkuInfo["goods_sku_id"],
                                "goods_desc_pic_url" => $goodsSkuInfo["desc_pic_url"],
                                "goods_name" => $goodsSkuInfo["goods_name"],
                                "inventory_rest" => $goodsSkuInfo["inventory_rest"],
                                "total_amount_sold" => $goodsSkuInfo["total_amount_sold"],
                                "original_price" => empty($goodsSkuInfo["original_price"]) ? '' : (string)($goodsSkuInfo["original_price"] / 100),
                                "price" => $goodsSkuInfo["price"] / 100,
                                "price_sort" => (int)$goodsSkuInfo["price"],
                                "audit_status" => $goodsSkuInfo["audit_status"],
                                "online_status" => $goodsSkuInfo["online_status"],
                                "desc" => $goodsSkuInfo["desc"],
                                "category_1_id" => $goodsSkuInfo["category_1_id"],
                                "category_2_id" => $goodsSkuInfo["category_2_id"],
                                "category_1_name" => $nameList[0],
                                "category_2_name" => $nameList[1],
                                "life_account_id" => $goodsSkuInfo["life_account_id"],
                                "life_account_name" => empty($lifeAccountRes["response"]["result"]["life_account_name"]) ? "" : $lifeAccountRes["response"]["result"]["life_account_name"],
                                "life_account_icon" => empty($lifeAccountRes["response"]["result"]["life_account_icon"]) ? "" : $lifeAccountRes["response"]["result"]["life_account_icon"],
                                "shop_name" => $subShop["shop_name"],
                                "shop_address" => $subShop["address"],
                                "shop_location" => $subShop["latitude"] . "," . $subShop["longitude"],
                                "update_time" => strtotime($goodsSkuInfo["update_time"]),
                            ],
                        ];
                        $isHaveId = ElasticGoodService::isHaveById($goodsSkuId);
                        if ($isHaveId) {
                            ElasticGoodService::updateDoc($esId, $data);
                        } else {
                            $data = $data["doc"];
                            ElasticGoodService::indexDoc($esId, $data);
                        }
                    }
                }
            }
        }
    }

    /**
     * es 创建一条数据
     * @param $skuParams
     * @return bool
     */
    private static function addGoodsInfoToEs($skuParams)
    {
        $nameList = Category::select("name", ["category_id" => [$skuParams["category_1_id"], $skuParams["category_2_id"]]]);
        //生活号信息
        $url = config('interface', 'merchant.lifeaccount.get_life_account_by_id');
        if (empty($url)) {
            throw new InterfaceException(['cus' => 0]);
        }
        $lifeAccountRes = (new Request())->get($url, ["life_account_id" => $skuParams["life_account_id"]]);

        $data = [
            "goods_sku_id" => $skuParams["goods_sku_id"],
            "goods_desc_pic_url" => $skuParams["desc_pic_url"],
            "goods_name" => $skuParams["goods_name"],
            "inventory_rest" => $skuParams["inventory_rest"],
            "total_amount_sold" => 0,
            "original_price" => $skuParams["original_price"] / 100,
            "price" => $skuParams["price"] / 100,
            "price_sort" => (int)$skuParams["price"],
            "audit_status" => GoodsSku::STATUS_AUDIT,
            "online_status" => GoodsSku::ONLINE_STATUS_NO_ONLINE,
            "desc" => $skuParams["desc"],
            "category_1_id" => $skuParams["category_1_id"],
            "category_2_id" => $skuParams["category_2_id"],
            "category_1_name" => $nameList[0],
            "category_2_name" => $nameList[1],
            "life_account_name" => empty($lifeAccountRes["response"]["result"]["life_account_name"]) ? "" : $lifeAccountRes["response"]["result"]["life_account_name"],
            "life_account_icon" => empty($lifeAccountRes["response"]["result"]["life_account_icon"]) ? "" : $lifeAccountRes["response"]["result"]["life_account_icon"],
            "update_time" => time(),
        ];
        $esRes = ElasticGoodService::indexDoc($skuParams["goods_sku_id"], $data);
        if ($esRes["result"] == "created" && $esRes["_shards"]["successful"] == 1) {
            return true;
        }
        return false;
    }

    /**
     * 是否存在敏感词
     * $text 送查内容
     * $scene 场景ID 1.标题 2.简介 3.正文 4.评论 6.昵称 7.搜索
     * $businessId 1.一点 2.身边 9.VPN
     * @param $text
     * @param $scene
     * @param int $businessId
     * @return bool|mixed
     * @throws \App\Exception\custom\CodeSpecialException
     */
    public static function isHaveSensitive($text, $scene, $businessId = 1)
    {
        $params = [
            'businessId' => $businessId,
            'text' => $text,
            'scene' => $scene,

        ];

        $res = (new Sensitive())->detect($params);
        if (empty($res["data"])) {
            return false;
        }
        return true;
    }

    /**
     * 通过sku_id 和 goods_version 获取实时商品信息
     * @param $params
     * @return array
     * @throws GoodsException
     */
    public static function getGoodsRealTimeInfo($params)
    {
        $data = [];
        $goodsSku = GoodsSku::get("*", ["goods_sku_id" => $params["goods_sku_id"], "goods_version" => $params["goods_version"]]);
        if (empty($goodsSku)) {
            throw new GoodsException(["cus" => 15]);
        }

        $data["online_status"] = $goodsSku["online_status"];
        $data["rule_limit"] = $goodsSku["rule_limit"];
        $data["rule_refund"] = $goodsSku["rule_refund"];
        return $data;
    }

    /**
     * 商品快照数据
     * @param $params
     * @return array
     * @throws GoodsException
     */
    public static function getGoodsSnapshotInfo($params)
    {
        $marketingType = !empty($params['marketing_type']) ? $params['marketing_type'] : 0;
        if ($marketingType == Marketing::MARKETING_TYPE_PINDAN) {
            return MarketingPindanGoodsService::pindanGoodsSnapshotInfo($params);
        } else {
            return self::generalGoodsSnapshotInfo($params);
        }
    }

    /**
     * 普通商品商品快照
     * @param $params
     * @return array
     * @throws GoodsException
     */
    private static function generalGoodsSnapshotInfo($params)
    {
        $data = [];
        $goodsSnapshot = GoodsSnapshot::getRecord(["goods_sku_id" => $params["goods_sku_id"], "goods_version" => $params["version"]]);
        if (empty($goodsSnapshot)) {
            throw new GoodsException(["cus" => 23]);
        }

        $data["goods_name"] = $goodsSnapshot["goods_name"];
        $nameList = Category::select("name", ["category_id" => [$goodsSnapshot["category_1_id"], $goodsSnapshot["category_2_id"]]]);
        $data["category_1_name"] = $nameList[0];
        $data["category_2_name"] = $nameList[1];
        $data["desc_pic_url_list"] = [];
        if (!empty($goodsSnapshot["desc_pic_url"])) {
            $ksyun = GoodsService::getUrlList($goodsSnapshot["desc_pic_url"]);
            $data["desc_pic_url_list"] = $ksyun;
        }
        $data["introduce_pic_url_list"] = [];
        if (!empty($goodsSnapshot["introduce_pic_url"])) {
            $ksyun = GoodsService::getUrlList($goodsSnapshot["introduce_pic_url"]);
            $data["introduce_pic_url_list"] = $ksyun;
        }

        $data["desc"] = $goodsSnapshot["desc"];
        $data["introduce"] = $goodsSnapshot["introduce"];
        $data["expiration_time"] = $goodsSnapshot["expiration_time"];
        $data["rule_limit"] = $goodsSnapshot["rule_limit"];
        $data["rule_desc"] = $goodsSnapshot["rule_desc"];
        $data["rule_refund"] = $goodsSnapshot["rule_refund"];
        $data["original_price"] = $goodsSnapshot["original_price"] / 100;
        $data["price"] = $goodsSnapshot["price"] / 100;
        $data["sub_shop"] = json_decode($goodsSnapshot["sub_shop"], true);
        $data["setmeal"] = empty($goodsSnapshot["setmeal"]) ? [] : json_decode($goodsSnapshot["sub_shop"], true);
        return $data;
    }

    /**
     * 检查商品是否有营销活动
     * @param $params
     * @return array
     * @throws GoodsException
     */
    public static function checkGoodsMarketing($params)
    {
        $data = [];
        $goodsSku = GoodsSku::get("*", ["goods_sku_id" => $params["goods_sku_id"], "goods_version" => $params["goods_version"]]);
        if (empty($goodsSku)) {
            throw new GoodsException(["cus" => 15]);
        }
        //todo

        return $data;
    }

    /**
     * 获取 GoodsSku 数据
     * @param $params
     * @return array
     * @throws GoodsException
     */
    public static function getGoodsBySkuId($params)
    {
        $where = [];
        if (empty($params)) {
            return [];
        }
        if (!empty($params['goods_sku_id'])) {
            $where['goods_sku_id'] = $params['goods_sku_id'];
        }
        $info = GoodsSku::getRecord($where);

        $info['original_price'] = empty($info['original_price']) ? 0 : $info['original_price'] / 100;
        $info['price'] = !empty($info['price']) ? $info['price'] / 100 : 0;
        $info['desc_pic_url'] = !empty($info['desc_pic_url']) ? self::getUrlList($info['desc_pic_url']) : '';
        $info['introduce_pic_url'] = !empty($info['introduce_pic_url']) ? self::getUrlList($info['introduce_pic_url']) : [];
        return $info;
    }

    /**
     * 获取 GoodsSku 列表
     * @param $params
     * @return \Api\PhpUtils\Mysql\MysqlBase|array
     */
    public static function getGoodsSkuList($params)
    {
        if (empty($params)) {
            return [];
        }

        $marketingType = !empty($params['marketing_type']) ? $params['marketing_type'] : 0;
        if ($marketingType == Marketing::MARKETING_TYPE_PINDAN) {
            return self::generalGetPindanGoodsSkuList($params);
        } else {
            return self::generalGetGoodsSkuList($params);
        }
    }

    private static function generalGetGoodsSkuList($params)
    {
        $where = [];
        if (!empty($params['goods_sku_id'])) {
            $where['goods_sku_id'] = $params['goods_sku_id'];
        }

        if (!empty($params['goods_spu_id'])) {
            $where['goods_spu_id'] = $params['goods_spu_id'];
        }

        if (!empty($params['life_account_id'])) {
            $where['life_account_id'] = $params['life_account_id'];
        }

        if (!empty($params['shop_id'])) {
            $where['shop_id'] = $params['shop_id'];
        }

        if (!empty($params['goods_name'])) {
            $where['goods_name'] = $params['goods_name'];
        }

        $list = GoodsSku::getRecords($where);
        return $list;
    }

    private static function generalGetPindanGoodsSkuList($params)
    {
        $where = [];
        if (!empty($params['goods_sku_id'])) {
            $where['goods_sku_id'] = $params['goods_sku_id'];
        }

        return PindanGoodsSku::getRecords($where);
    }


    /**
     * 获取 GoodsSpu 列表
     * @param $params
     * @return array
     * @throws GoodsException
     */
    public static function getGoodsSpuList($params)
    {
        $where = [];
        if (empty($params)) {
            return [];
        }

        if (!empty($params['goods_spu_id'])) {
            $where['goods_spu_id'] = $params['goods_spu_id'];
        }

        if (!empty($params['life_account_id'])) {
            $where['life_account_id'] = $params['life_account_id'];
        }

        if (!empty($params['shop_id'])) {
            $where['shop_id'] = $params['shop_id'];
        }

        if (!empty($params['goods_name'])) {
            $where['goods_name'] = $params['goods_name'];
        }

        $list = GoodsSpu::getRecords($where);
        return $list;
    }


    /**
     * 获取 GoodsSku 列表
     * @param $params
     * @return array
     * @throws GoodsException
     */
    public static function getGoodsSkuSubShopList($params)
    {
        $where = [];
        if (empty($params)) {
            return [];
        }

        if (!empty($params['goods_sku_id'])) {
            $where['goods_sku_id'] = $params['goods_sku_id'];
        }
 
        if (!empty($params['sub_shop_id'])) {
            $where['sub_shop_id'] = $params['sub_shop_id'];
        }
 
        $list = GoodsSkuSubShop::getRecords($where);
        return $list;
    }

    /**
     * 获取图片地址，这里因为bucket可能不同，不保证图片顺序
     * @param $picUrlStr
     * @param $widthSize
     * @param $highSize
     * @return array
     */
    public static function getUrlList($picUrlStr, $widthSize = 0, $highSize = 0)
    {
        $data = $ksyunParams = [];
        $strList = explode(",", $picUrlStr);
        foreach ($strList as $key => $str) {
            $arr = explode("/", $str);
            if (preg_match("/^http[s]{0,1}:\/\/([\w.]+\/?)\S*/", $str)) {
                $data[] = $str;
            } else if (count($arr) == 1) {
                if (!empty($widthSize) && !empty($highSize)) {
                    $urlRes = Ks3Api::picEncryptUrl($str, $widthSize, $highSize);
                } else {
                    $urlRes = Ks3Api::picEncryptUrl($str);
                }
                if (!empty($urlRes["response"]["data"]["url"]) && $urlRes["response"]["data"]["url"]) {
                    $data[] = $urlRes["response"]["data"]["url"];
                } else {
                    continue;
                }
            } else {
                $bucket = $arr[0];
                $objectId = $arr[1];

                $url = Ksyun::getPicUrl("merchant-b", 'goods_temp', $bucket . '/' . $objectId, 200, 200, 'jpeg');
                $data[] = $url;
            }
        }

        return $data;
    }

    /**
     * 支付成功后回调
     * @param array $params
     * @return bool
     * @throws GoodsException
     * @throws InterfaceException
     */
    public static function paySuccessGoodsCallback($params = [])
    {
        $orderId = $params["order_id"];
        $goodsPayInfos = json_decode($params["goods"], true);
        $marketingInfos = json_decode($params["marketing"], true);

        GoodsSku::beginTransaction();
        foreach ($goodsPayInfos as $goodsSkuId => $num) {
            $marketingId = empty($marketingInfos[$goodsSkuId]) ? 0 : $marketingInfos[$goodsSkuId];
            $record = PaySuccessGoodsCallbackRecord::getRecord([
                    "order_id" => $orderId,
                    "goods_sku_id" => $goodsSkuId,
                    "operator_result" => PaySuccessGoodsCallbackRecord::OPERATOR_RESULT_SUCCESS,
                    "marketing_id" => $marketingId]
            );
            if (empty($record)) {
                if (!empty($marketingId)) {
                    $marketing = Marketing::getRecord(["marketing_id" => $marketingId]);
                    if (!empty($marketing) && $marketing["marketing_type"] == Marketing::MARKETING_TYPE_PINDAN) {
                        $goodsSku = PindanGoodsSku::getRecord(["goods_sku_id" => $goodsSkuId]);
                    }
                } else {
                    $goodsSku = GoodsSku::getRecord(["goods_sku_id" => $goodsSkuId]);
                }
                if (empty($goodsSku)) {
                    return false;
                }

                if (!empty($marketingId)) {
                    $marketing = Marketing::getRecord(["marketing_id" => $marketingId]);
                    if (!empty($marketing) && $marketing["marketing_type"] == Marketing::MARKETING_TYPE_PINDAN) {
                        $marketingPindan = MarketingPindan::getRecord(["marketing_id" => $marketingId]);
                        if (!empty($marketingPindan)) {
                            $rowCount = MarketingPindan::save(["participate_number[+]" => $num]
                                , ["marketing_pindan_id" => $marketingPindan["marketing_pindan_id"]]);
                            if ($rowCount <= 0) {
                                GoodsSku::rollback();
                                return false;
                            }
                        }
                    }
                    PindanGoodsSku::save(["total_amount_sold[+]" => $num], ["goods_sku_id" => $goodsSkuId]);
                } else {
                    GoodsSku::save(["total_amount_sold[+]" => $num], ["goods_sku_id" => $goodsSkuId]);
                }

                PaySuccessGoodsCallbackRecord::insertRecord([
                        "order_id" => $orderId,
                        "goods_sku_id" => $goodsSkuId,
                        "num" => $num,
                        "operator_result" => PaySuccessGoodsCallbackRecord::OPERATOR_RESULT_SUCCESS,
                        "marketing_id" => $marketingId]
                );
            }
        }
        if (!GoodsSku::commit()) {
            GoodsSku::rollback();
            foreach ($goodsPayInfos as $goodsSkuId => $num) {
                PaySuccessGoodsCallbackRecord::insertRecord([
                        "order_id" => $orderId,
                        "goods_sku_id" => $goodsSkuId,
                        "num" => $num,
                        "operator_result" => PaySuccessGoodsCallbackRecord::OPERATOR_RESULT_FAIL]
                );
            }

            throw new GoodsException(["cus" => 44]);
        } else {
            //同步到es
            if (empty($marketingId)) {
                foreach ($goodsPayInfos as $goodsSkuId => $num) {
                    self::updateGoodsInfoToEs($goodsSkuId);
                }
            }
        }

        return true;
    }

    /**
     * 商品中使用的图片记录
     * @param $goodsSkuId
     * @param $skuData
     */
    public static function addGoodsSkuPicRecord($goodsSkuId, $skuData)
    {
        $descPicUrl = $introducePicUrl = [];
        if (!empty($skuData["desc_pic_url"])) {
            $descPicUrl = explode(",", $skuData["desc_pic_url"]);
        }
        if (!empty($skuData["introduce_pic_url"])) {
            $introducePicUrl = explode(",", $skuData["introduce_pic_url"]);
        }

        $ids = GoodsSkuPicRecord::select("id", ["goods_sku_id" => $goodsSkuId]);
        if (!empty($ids)) {
            GoodsSkuPicRecord::delete(["id" => $ids]);
        }

        $urlList = array_unique(array_merge($descPicUrl, $introducePicUrl));
        $data = [];
        if (!empty($urlList)) {
            foreach ($urlList as $url) {
                $data[] = ["goods_sku_id" => $goodsSkuId, "url" => $url];
            }
            GoodsSkuPicRecord::save($data);
        }
    }

    /**
     * 当前没有初始化shop的地方，单拎出来一个接口
     * @param array $params
     * @return mixed
     * @throws GoodsException
     */
    public static function initShop($params = [])
    {
        //生活号信息
        $url = config('interface', 'merchant.lifeaccount.get_life_account_by_id');
        if (empty($url)) {
            throw new InterfaceException(['cus' => 0]);
        }
        $lifeAccountRes = (new Request())->get($url, ["life_account_id" => $params["life_account_id"]]);
        if (empty($lifeAccountRes["response"]["result"])) {
            throw new GoodsException(['cus' => 29]);
        }

        $lifeAccount = [
            "life_account_id" => $params["life_account_id"],
            "merchant_id" => $lifeAccountRes["response"]["result"]["merchant_id"],
        ];

        return self::addShop($lifeAccount);
    }

    /**
     * 退款拼单商品，库存调整
     * @param $params
     * @return bool
     * @throws GoodsException
     */
    public static function refundGoods($dataJson)
    {
        if (empty($dataJson)){
            throw new GoodsException(["cus" => GoodsException::PARAMS_NULL_ERROR]);
        }
        foreach ($dataJson as $params){
            $goodsSukParams = GoodsSkuId::getGoodsSkuIdParams($params["goods_sku_id"]);
            if (!empty($goodsSukParams)) {
                if (isset($goodsSukParams["table_tag"]) && ($goodsSukParams["table_tag"] == GoodsSkuId::TABLE_TAG_PINDAN
                        || $goodsSukParams["category_1_id"] == "00")) {
                    $refundGoodsData[] = $params;
                }
            } else {
                throw new GoodsException(["cus" => 41]);
            }
        }
        if (empty($refundGoodsData)){
            return true;
        }
        return MarketingPindanGoodsService::refundGoods($refundGoodsData);
    }

    /**
     * 通过goods_sku_id 获取 拼单商品的ota信息
     * @param array $params
     * @return array
     */
    public static function getOtaInfoByGoodsSkuIds($params = [])
    {
        $data = [];
        $goodsSkuIds = empty($params["goods_sku_ids"]) ? [] : $params["goods_sku_ids"];
        if (!empty($goodsSkuIds)) {
            $pindanGoodsSkus = PindanGoodsSku::select(["goods_sku_id", "ota_id"], ["goods_sku_id" => $goodsSkuIds]);
            $otaIds = array_column($pindanGoodsSkus, "ota_id");
            $otaInfos = Ota::select("*", ["ota_id" => $otaIds]);
            $otaIds = array_column($otaInfos, "ota_id");
            $otaInfos = array_column($otaInfos, null, "ota_id");

            foreach ($pindanGoodsSkus as $sku) {
                if (in_array($sku["ota_id"], $otaIds)) {
                    $data[$sku["goods_sku_id"]] = $otaInfos[$sku["ota_id"]];
                }
            }
        }
        return $data;
    }

    /**
     * 下单时获取商品数据
     * @param array $params
     * @return array
     */
    public static function getPlaceOrderGoodsList($params)
    {
        if (!$goodsSkuList = self::getPlaceOrderGoodsSkuList($params)) {
            return [];
        }
        $goodsSpuList = self::getGoodsSpuList(['goods_spu_id' => array_column($goodsSkuList, 'goods_spu_id')]);
        $goodsSpuList = array_column($goodsSpuList, null, 'goods_spu_id');
        $goodsSkuData = [];
        foreach ($goodsSkuList as $goodsInfo) {
            if (!empty($goodsSpuList[$goodsInfo['goods_spu_id']])) {
                $goodsSpuInfo = $goodsSpuList[$goodsInfo['goods_spu_id']];
                $goodsSkuData[] = [
                    'goods_sku_id'    => $goodsInfo['goods_sku_id'],
                    'goods_spu_id'    => $goodsInfo['goods_spu_id'],
                    'goods_version'   => $goodsInfo['goods_version'],
                    'price'           => $goodsInfo['price'],
                    'clear_price'     => $goodsInfo['clear_price'],
                    'rule_limit'      => $goodsInfo['rule_limit'],
                    'online_status'   => $goodsInfo['online_status'],
                    'inventory_rest'  => $goodsInfo['inventory_rest'],
                    'rule_refund'     => $goodsSpuInfo['rule_refund'],
                    'goods_sale_type' => $goodsSpuInfo['goods_sale_type'],
                    'goods_type'      => $goodsSpuInfo['goods_type'],
                    'shop_id'         => $goodsSpuInfo['shop_id'],
                    'life_account_id' => $goodsSpuInfo['life_account_id']
                ];
            }
        }
        return $goodsSkuData;
    }

    /**
     * 下单时获取商品sku数据
     * @param array $params
     * @return array
     */
    public static function getPlaceOrderGoodsSkuList($params)
    {
        if (empty($params['goods_sku_id'])) {
            return [];
        }
        $goodsSkuIdList = [];
        foreach ($params['goods_sku_id'] as $goodsSkuId) {
            $goodsParams = GoodsSkuId::getGoodsSkuIdParams($goodsSkuId);
            $goodsSkuIdList[$goodsParams['goods_type']][] = $goodsSkuId;
        }
        $goodsSkuList = [];
        foreach ($goodsSkuIdList as $goodsType => $goodsSkuIds) {
            // 现在只有两种类型 实体，虚拟
            if ($goodsType == GoodsSpu::TYPE_VIRTUAL) {
                $goodsData = self::generalGetGoodsSkuList(['goods_sku_id' => $goodsSkuIds]);
            } else {
                $goodsData = self::generalGetPindanGoodsSkuList(['goods_sku_id' => $goodsSkuIds]);
            }
            $goodsSkuList = array_merge($goodsSkuList, $goodsData);
        }
        return $goodsSkuList;
    }

}