<?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 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\GoodsSnapshot;
use App\Models\goods\mysql\GoodsSpu;
use App\Models\goods\mysql\Shop;
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);
        $spuId = self::addGoodsSpu($shopId, $params);
        $skuId = self::addGoodsSku($spuId, $shopId, $params);

        //商品操作记录
        $res = self::getSnowIdgenId("goods");
        if (empty($res)) {
            throw new GoodsException(['cus' => 2]);
        }
        $record = [
            "goods_operation_record_id" => $res[0],
            "goods_spu_id" => $spuId,
            "goods_sku_id" => $skuId,
            "operator_id" => $params["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["name"], $spuData["life_account_id"]);
        if (!$checkName["can_use"]) {
            throw new GoodsException(['cus' => 17]);
        }
        GoodsSpu::save([
            "goods_spu_id" => $spuId,
            "shop_id" => $shopId,
            "life_account_id" => $spuData["life_account_id"],
            "user_id" => $spuData["user_id"],
            "name" => $spuData["name"],
            "url" => $spuData["url"],
            "desc" => $spuData["desc"],
            "type" => GoodsSpu::TYPE_VIRTUAL,
            "sub_type" => GoodsSpu::SUB_TYPE_TO_SHOP,
            "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"],
        ]);
        return $spuId;
    }

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

        if ($skuData["expiration_time"] < date("Y-m-d H:i:s")) {
            throw new GoodsException(['cus' => 16]);
        }
        $checkGoodsName = self::isHaveSensitive($skuData["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" => $spuId,
            "life_account_id" => $skuData["life_account_id"],
            "shop_id" => $shopId,
            "user_id" => $skuData["user_id"],
            "category_1_id" => $skuData["category_1_id"],
            "category_2_id" => $skuData["category_2_id"],
            "name" => $skuData["name"],
            "url" => $skuData["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_add"],
            "inventory_rest" => $skuData["inventory_add"],
            "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 array $params
     * @return bool
     * @throws GoodsException
     */
    public static function audit($params = [])
    {
        $goodsSpuId = $params["goods_spu_id"];
        $status = $params["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]);
        }
        //todo::权限判断 商品所属 life_account_id 或者 后台管理员
        //权限判断
        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["status"] == GoodsSku::STATUS_PASS || $sku["status"] == GoodsSku::STATUS_REJECT) {
                    throw new GoodsException(["cus" => 10]);
                }
                $goodsSkuId = $sku["goods_sku_id"];
                GoodsSku::save([
                    "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["version"],
                    "after_version" => $sku["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]);
        //todo::权限判断 后台管理员
        //权限判断
        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["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["status"],
                    "online_status" => $onlineStatus,
                    "before_version" => $sku["version"],
                    "after_version" => $sku["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::getSubShopList($skuInfo["shop_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("*", ["name" => $goodsName, "life_account_id" => $lifeAccountId, "goods_spu_id[!]" => $goodsSpuId]);
        } else {
            $sku = GoodsSpu::get("*", ["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["name"], $goodsSpu["life_account_id"], $goodsSpu["goods_spu_id"]);
        if (!$checkName["can_use"]) {
            throw new GoodsException(['cus' => 17]);
        }

        return GoodsSpu::save([
            "name" => $params["name"],
            "url" => $params["url"],
            "desc" => $params["desc"],
            "type" => GoodsSpu::TYPE_VIRTUAL,
            "sub_type" => GoodsSpu::SUB_TYPE_TO_SHOP,
            "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["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]);
        }

        $skuParams = [
            "category_1_id" => $params["category_1_id"],
            "category_2_id" => $params["category_2_id"],
            "name" => $params["name"],
            "url" => $params["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,
            "version" => (int)$skuData["version"] + 1,
        ];
        if (self::isInitGoodsStatus($params, $skuData)) {
            $skuParams["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["user_id"]) ? 0 : $params["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["version"],
            "after_version" => $skuParams["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["name"] != $sku["name"]
            || $params["url"] != $sku["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["url"])) {
                    $image = explode(",", $sku["url"]);
                    $ksyun = Ksyun::getDownUrl($image, 'merchant-b', 'bp-yidian', 60);
                    $data["goods_info"]["url_list"] = array_values($ksyun);
                }
                $data["goods_info"]["introduce_pic_url_list"] = [];
                if (!empty($sku["introduce_pic_url"])) {
                    $image = explode(",", $sku["introduce_pic_url"]);
                    $ksyun = Ksyun::getDownUrl($image, 'merchant-b', 'bp-yidian', 60);
                    $data["goods_info"]["introduce_pic_url_list"] = array_values($ksyun);
                }

                //门店
                $subShopList = ShopService::getSubShopList($sku["shop_id"]);
                if (!empty($subShopList)) {
                    foreach ($subShopList as $key => $subShop) {
                        $data["goods_info"]["sub_shop"][$key] = $subShop;
                    }
                }
            }
        }
        $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 = [];
        $goodsSkuId = BaseConvert::otherToDec($params["goods_sku_id"]);
        $goodsSku = GoodsSku::get("*", ["goods_sku_id" => $goodsSkuId]);
        if (empty($goodsSku)) {
            throw new GoodsException(["cus" => 15]);
        }

        $data["goods_info"] = $goodsSku;
        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["name"])) {
            $where["name"] = $params["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["status"])) {
            $status = explode(",", $params["status"]);
            $where["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", "name", "category_1_id", "category_2_id", "life_account_id",
            "user_id", "update_time", "create_time", "status", "online_status"],
            $where);
        return ["list" => $list, "count" => $count];
    }

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

    }

    /**
     * 商家 c端商品列表
     * @param $lifeAccountId
     * @param $type
     * @return array
     */
    public static function getCGoodsSkuList($lifeAccountId, $type = "")
    {
        $statusList = [
            ["type" => "online", "name" => "上架中"],
            ["type" => "auditing", "name" => "审核中"],
            ["type" => "rejected", "name" => "被驳回"],
            ["type" => "offline", "name" => "已下架"],
        ];

        $where = [];
        if ($type == "online") {
            $where["status"] = GoodsSku::STATUS_PASS;
            $where["online_status"] = GoodsSku::ONLINE_STATUS_ONLINE;
        }

        $where["life_account_id"] = $lifeAccountId;
        $list = GoodsSku::select(["goods_spu_id", "goods_sku_id", "name", "url", "total_amount_sold", "inventory_rest", "original_price",
            "price", "status", "online_status"], $where);

        $data = [
            "online" => [],
            "auditing" => [],
            "rejected" => [],
            "offline" => [],
        ];
        if (!empty($list)) {
            foreach ($list as $sku) {
                if ($sku["status"] == GoodsSku::STATUS_PASS && $sku["online_status"] == GoodsSku::ONLINE_STATUS_ONLINE) {
                    $data["online"][] = $sku;
                }
                if ($sku["status"] == GoodsSku::STATUS_AUDIT) {
                    $data["auditing"][] = $sku;
                }
                if ($sku["status"] == GoodsSku::STATUS_REJECT) {
                    $data["rejected"][] = $sku;
                }
                if ($sku["online_status"] == GoodsSku::ONLINE_STATUS_OFFLINE) {
                    $data["offline"][] = $sku;
                }
            }
        }

        return ["status_list" => $statusList, "list" => $data];
    }

    /**
     * 更新到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_pic" => $skuParams["url"],
                "name" => $skuParams["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"],
                "status" => $skuData["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_pic" => $skuParams["url"],
            "name" => $skuParams["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"],
            "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 和 version 获取实时商品信息
     * @param $params
     * @return array
     * @throws GoodsException
     */
    public static function getGoodsRealTimeInfo($params)
    {
        $data = [];
        $goodsSkuId = BaseConvert::otherToDec($params["goods_sku_id"]);
        $goodsSku = GoodsSku::get("*", ["goods_sku_id" => $goodsSkuId, "version" => $params["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 = [];
        $goodsSkuId = BaseConvert::otherToDec($params["goods_sku_id"]);
        $goodsSnapshot = GoodsSnapshot::getRecord(["goods_sku_id" => $goodsSkuId, "version" => $params["version"]]);
        if (empty($goodsSnapshot)) {
            throw new GoodsException(["cus" => 23]);
        }

        $data["name"] = $goodsSnapshot["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["url_list"] = [];
        if (!empty($goodsSnapshot["url"])) {
            $image = explode(",", $goodsSnapshot["url"]);
            $ksyun = Ksyun::getDownUrl($image, 'merchant-b', 'bp-yidian', 60);
            $data["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 = [];
        $goodsSkuId = BaseConvert::otherToDec($params["goods_sku_id"]);
        $goodsSku = GoodsSku::get("*", ["goods_sku_id" => $goodsSkuId, "version" => $params["version"]]);
        if (empty($goodsSku)) {
            throw new GoodsException(["cus" => 15]);
        }
        //todo

        return $data;
    }
}