<?php


namespace App\Services\goods;


use Api\PhpServices\Idgen\Idgen;
use App\Exception\custom\GoodsException;
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"],
            "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"],
            "price" => $skuData["price"],
        ];
        if (!empty($skuData["setmeal"])) {
            $skuParams["setmeal"] = $skuData["setmeal"];
        }
        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], ["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"];
        }
        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;
    }
}