<?php


namespace App\Services\goods;


use Api\PhpServices\Idgen\Idgen;
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\GoodsSpu;
use App\Models\goods\mysql\Shop;

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);

        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"],
            "u_id" => $spuData["u_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]);
        }

        $skuParams = [
            "goods_spu_id" => $spuId,
            "goods_sku_id" => $skuId,
            "shop_id" => $shopId,
            "life_account_id" => $skuData["life_account_id"],
            "category_1_id" => $skuData["category_1_id"],
            "category_2_id" => $skuData["category_2_id"],
            "name" => $skuData["name"],
            "url" => $skuData["url"],
            "desc" => $skuData["desc"],
            "expiration_time" => $skuData["expiration_time"],
            "rule_limit" => $skuData["rule_limit"],
            "rule_desc" => $skuData["rule_desc"],
            "rule_refund" => $skuData["rule_refund"],
            "inventory_total" => $skuData["inventory_total"],
            "inventory_rest" => $skuData["inventory_total"],
            "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 = $params["uid"];
        $operatorName = $params["username"];

        $goodsSpu = GoodsSpu::get("*", ["goods_spu_id" => $goodsSpuId]);
        //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 = $params["uid"];
        $operatorName = $params["username"];

        $goodsSpu = GoodsSpu::get("*", ["goods_spu_id" => $goodsSpuId]);
        //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($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]);

                //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" => $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::commit()) {
            GoodsSku::rollback();
            throw new GoodsException(["cus" => 11]);
        }
        return true;
    }

    /**
     * 商品名是否可用
     * @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]);
        }

        $skuParams = [
            "category_1_id" => $params["category_1_id"],
            "category_2_id" => $params["category_2_id"],
            "name" => $params["name"],
            "url" => $params["url"],
            "desc" => $params["desc"],
            "expiration_time" => $params["expiration_time"],
            "rule_limit" => $params["rule_limit"],
            "rule_desc" => $params["rule_desc"],
            "rule_refund" => $params["rule_refund"],
            "inventory_total" => $params["inventory_total"],
            "inventory_rest" => $params["inventory_total"],
            "original_price" => $params["original_price"] * 100,
            "price" => $params["price"] * 100,
            "version" => (int)$skuData["version"] + 1,
        ];
        if (!empty($params["setmeal"])) {
            $skuParams["setmeal"] = $params["setmeal"];
        }
        //同步到es
        self::updateGoodsInfoToEs($skuData, $skuParams);

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

    /**
     * 后台用商品详情
     * @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) {
                //todo::图片处理，门店，套餐，生活号信息
                $data["goods_info"] = $sku;
            }
        }
        $recordList = GoodsOperationRecord::select("*", ["goods_spu_id" => $goodsSpuId]);
        if (!empty($recordList)) {
            //todo::处理展示内容
            $data["record_list"] = $recordList;
        }
        return $data;
    }

    /**
     * 商品sku详情
     * @param array $params
     * @return array
     * @throws GoodsException
     */
    public static function getGoodsSkuInfo($params = [])
    {
        $data = [];
        $goodsSkuId = $params["goods_sku_id"];
        $goodsSku = GoodsSku::get("*", ["goods_sku_id" => $goodsSkuId]);
        if (empty($goodsSku)) {
            throw new GoodsException(["cus" => 15]);
        }

        //todo::处理展示内容
        $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"])) {
            $where["category_1_id"] = $params["category_1_id"];
        }
        if (!empty($params["category_2_id"])) {
            $where["category_2_id"] = $params["category_2_id"];
        }
        if (!empty($params["life_account_id"])) {
            $where["life_account_id"] = $params["life_account_id"];
        }
        if (!empty($params["status"])) {
            $where["status"] = $params["status"];
        }
        if (!empty($params["online_status"])) {
            $where["online_status"] = $params["online_status"];
        }

        $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",
            "u_id", "update_time", "create_time", "status", "online_status"],
            $where);
        return ["list" => $list, "count" => $count];
    }

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

    }

    /**
     * 商家 c端商品列表
     * @param $lifeAccountId
     * @return array
     */
    public static function getCGoodsSkuList($lifeAccountId)
    {
        $statusList = [
            ["type" => "online", "name" => "上架中"],
            ["type" => "auditing", "name" => "审核中"],
            ["type" => "rejected", "name" => "被驳回"],
            ["type" => "offline", "name" => "已下架"],
        ];
        $list = GoodsSku::select(["goods_sku_id", "name", "url", "total_amount_sold", "inventory_rest", "original_price",
            "price", "status", "online_status"],
            ["life_account_id" => $lifeAccountId]);

        $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, "data" => $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;
    }
}