<?php


namespace App\Services\goods;


use Api\PhpServices\Idgen\Idgen;
use Api\PhpServices\Ksy\Ksyun;
use Api\PhpServices\Sensitive\Sensitive;
use Api\PhpUtils\Common\BaseConvert;
use Api\PhpUtils\Common\GoodsSkuId;
use App\Exception\custom\GoodsException;
use App\Models\goods\mysql\Category;
use App\Models\goods\mysql\GoodsOperationRecord;
use App\Models\goods\mysql\GoodsSku;
use App\Models\goods\mysql\GoodsSkuSubShop;
use App\Models\goods\mysql\GoodsSnapshot;
use App\Models\goods\mysql\GoodsSpu;
use App\Models\goods\mysql\Shop;
use App\Models\shop\mysql\SubShop;
use App\Services\shop\ShopService;

class GoodsService
{
    /**
     * 通过发号器拿 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 = [])
    {
        GoodsSpu::beginTransaction();

        $lifeAccount = [
            "life_account_id" => $params["life_account_id"],
            "merchant_id" => $params["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);

        //商品操作记录
        $res = self::getSnowIdgenId("goods");
        if (empty($res)) {
            throw new GoodsException(['cus' => 2]);
        }
        $record = [
            "goods_operation_record_id" => $res[0],
            "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
     */
    private static function addGoodsSpu($shopId, $spuData = [])
    {
        $res = self::getIdgenId(substr($shopId, -2), "goods");
        if (empty($res)) {
            throw new GoodsException(['cus' => 2]);
        }
        $spuId = $res[0];
        $checkName = self::checkGoodsName($spuData["goods_name"], $spuData["life_account_id"]);
        if (!$checkName["can_use"]) {
            throw new GoodsException(['cus' => 17]);
        }

        $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]);
        }
        $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]);
        }
        $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]);
        }

        $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" => $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"],
            "inventory_total" => $skuData["inventory"],
            "inventory_rest" => $skuData["inventory"],
            "original_price" => $skuData["original_price"] * 100,
            "price" => $skuData["price"] * 100,
        ];
        if (!empty($skuData["setmeal"])) {
            $skuParams["setmeal"] = $skuData["setmeal"];
        }
        self::addGoodsInfoToEs($skuParams);

        GoodsSku::save($skuParams);
        return $skuId;
    }

    /**
     * 添加商铺
     * @param $lifeAccount
     * @return mixed
     * @throws GoodsException
     */
    private 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,
            ]);
        } else {
            $shopId = $shop[0]["shop_id"];
        }
        return $shopId;
    }

    /**
     * 增加商品时候处理门店信息
     * @param $subShopIdStr
     * @param $shopId
     * @param $skuId
     */
    private 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, "sub_shop_id" => $subShopIds]);
            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"];

        $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 && empty($params["rejected_reason"])) {
            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]);
                }
                $goodsSkuId = $sku["goods_sku_id"];
                GoodsSku::save([
                    "audit_status" => $status,
                    "rejected_reason" => $params["rejected_reason"]
                ], ["goods_sku_id" => $sku["goods_sku_id"]]);

                //todo:: info to es
                //商品操作记录
                $res = self::getSnowIdgenId("goods");
                if (empty($res)) {
                    throw new GoodsException(['cus' => 2]);
                }
                $record = [
                    "goods_operation_record_id" => $res[0],
                    "goods_spu_id" => $goodsSpuId,
                    "goods_sku_id" => $goodsSkuId,
                    "operator_id" => $operatorId,
                    "operator_name" => $operatorName,
                    "goods_status" => $status,
                    "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);
            }
        }
        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]);
                }
                $goodsSkuId = $sku["goods_sku_id"];
                GoodsSku::save(["online_status" => $onlineStatus], ["goods_sku_id" => $goodsSkuId]);

                //商品操作记录
                $res = self::getSnowIdgenId("goods");
                if (empty($res)) {
                    throw new GoodsException(['cus' => 2]);
                }
                $record = [
                    "goods_operation_record_id" => $res[0],
                    "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);
                }
            }
        }
        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);
        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 = [])
    {
        $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]);
        }
        return true;
    }

    /**
     * @param $goodsSpu
     * @param array $params
     * @return \Api\PhpUtils\Mysql\MysqlBase
     * @throws GoodsException
     */
    private static function editGoodsSpu($goodsSpu, $params = [])
    {
        $checkName = self::checkGoodsName($params["goods_name"], $goodsSpu["life_account_id"], $goodsSpu["goods_spu_id"]);
        if (!$checkName["can_use"]) {
            throw new GoodsException(['cus' => 17]);
        }

        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"];
        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]);
        }
        $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]);
        }

        //门店
        $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" => $skuData["introduce"],
            "introduce_pic_url" => $skuData["introduce_pic_url"],
            "expiration_time" => $params["expiration_time"],
            "rule_limit" => $params["rule_limit"],
            "rule_desc" => $params["rule_desc"],
            "rule_refund" => $params["rule_refund"],
            "inventory_total" => $skuData["inventory_total"] + $params["inventory_add"],
            "inventory_rest" => $inventoryCount,
            "original_price" => $params["original_price"] * 100,
            "price" => $params["price"] * 100,
            "goods_version" => (int)$skuData["goods_version"] + 1,
        ];
        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"];
        }
        //同步到es
        self::updateGoodsInfoToEs($skuData, $skuParams);

        //商品操作记录
        $res = self::getSnowIdgenId("goods");
        if (empty($res)) {
            throw new GoodsException(['cus' => 2]);
        }
        $record = [
            "goods_operation_record_id" => $res[0],
            "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);

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

    /**
     * 是否要初始化状态
     * @param $params
     * @param $sku
     * @return bool
     */
    private static function isInitGoodsStatus($params, $sku)
    {
        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"]
            || $params["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"];
    }

    /**
     * 后台用商品详情
     * @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;
                $data["goods_info"]["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;
                }

                //门店
                $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;
                }
            }
        }
        $recordList = GoodsOperationRecord::select("*", ["goods_spu_id" => $goodsSpuId]);
        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 = [])
    {
        $data = [];
        $sku = GoodsSku::get(["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", "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"] = $sku["original_price"] / 100;
        $data["goods_info"]["price"] = $sku["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;
        }

        //门店
        $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]["name"] = $sub["name"];
                $data["goods_info"]["sub_shop"][$key]["address_lng"] = $sub["address_lng"];
                $data["goods_info"]["sub_shop"][$key]["address_lat"] = $sub["address_lat"];
                $data["goods_info"]["sub_shop"][$key]["address"] = $sub["address"];
                $data["goods_info"]["sub_shop"][$key]["phone"] = $sub["phone"];
            }
        }
        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"])) {
            $status = explode(",", $params["audit_status"]);
            $where["audit_status"] = $status;
        }
        if (!empty($params["online_status"])) {
            $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"],
            $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];
            }
        }
        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" => "ASC"];
        $list = GoodsSku::select(["goods_spu_id", "goods_sku_id", "goods_name", "desc_pic_url", "total_amount_sold", "inventory_rest", "original_price",
            "price", "audit_status", "online_status"], $where);

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

                $data[] = $sku;
                $lastId = $sku["goods_spu_id"];
            }
        }

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

    /**
     * 更新到es
     * @param $skuData
     * @param $skuParams
     * @return array|callable
     */
    private static function updateGoodsInfoToEs($skuData, $skuParams)
    {
        $nameList = Category::select("name", ["category_id" => [$skuParams["category_1_id"], $skuParams["category_2_id"]]]);
        $data = [
            "doc" => [
                "id" => $skuData["goods_sku_id"],
                "goods_desc_pic_url" => $skuParams["desc_pic_url"],
                "goods_name" => $skuParams["goods_name"],
                "inventory_rest" => $skuParams["inventory_rest"],
                "total_amount_sold" => $skuData["total_amount_sold"],
                "original_price" => $skuParams["original_price"] / 100,
                "price" => $skuParams["price"] / 100,
                "price_sort" => (int)$skuParams["price"],
                "audit_status" => $skuData["audit_status"],
                "online_status" => $skuData["online_status"],
                "desc" => $skuData["desc"],
                "category_1_name" => $nameList[0],
                "category_2_name" => $nameList[1],
            ],
        ];
        return ElasticGoodService::updateDoc($skuData["goods_sku_id"], $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"]]]);
        $data = [
            "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_name" => $nameList[0],
            "category_2_name" => $nameList[1],
        ];
        $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
     */
    private 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)
    {
        $data = [];
        $goodsSnapshot = GoodsSnapshot::getRecord(["goods_sku_id" => $params["goods_sku_id"], "goods_version" => $params["goods_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"])) {
            $image = explode(",", $goodsSnapshot["desc_pic_url"]);
            $ksyun = Ksyun::getDownUrl($image, 'merchant-b', 'bp-yidian', 60);
            $data["desc_pic_url_list"] = array_values($ksyun);
        }
        $data["introduce_pic_url_list"] = [];
        if (!empty($goodsSnapshot["introduce_pic_url"])) {
            $image = explode(",", $goodsSnapshot["introduce_pic_url"]);
            $ksyun = Ksyun::getDownUrl($image, 'merchant-b', 'bp-yidian', 60);
            $data["introduce_pic_url_list"] = array_values($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 getGoodsSkuList($params)
    {
        $where = [];
        if (empty($params)) {
            return [];
        }

        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::getRecordMaster($where);
        return $list;
    }

    /**
     * 获取图片地址，这里因为bucket可能不同，不保证图片顺序
     * @param $picUrlStr
     * @return array
     */
    private static function getUrlList($picUrlStr)
    {
        $data = $ksyunParams = [];
        $strList = explode(",", $picUrlStr);
        foreach ($strList as $str) {
            $arr = explode("/", $str);

            $bucket = $arr[0];
            $objectId = $arr[1];
            $ksyunParams[$bucket][] = $objectId;
        }
        foreach ($ksyunParams as $bucket => $objectIds) {
            $ksyun = Ksyun::getDownUrl($objectIds, 'merchant-b', $bucket, 60);
            $data = array_merge($data, array_values($ksyun));
        }
        return $data;
    }
}