<?php

use Api\PhpUtils\Common\GoodsSkuId;
use Api\PhpUtils\Http\Request;
use App\Base\Cli;
use App\Exception\custom\GoodsException;
use App\Exception\custom\InterfaceException;
use App\Models\goods\mysql\GoodsSku;
use App\Models\goods\mysql\GoodsSpu;
use \App\Models\tmp\mysql\QyqTicketData;
use \App\Services\goods\GoodsService;
use \App\Services\shop\ShopService;
use \App\Models\shop\mysql\SubShop;
use \App\Models\shop\mysql\Shop;

/**
 * 导入老商品数据
 * php public/cli.php goodstoinit run
 * Class GoodsToInitController
 */
class GoodstoinitController extends Cli
{
    public function runAction()
    {
        $total = $this->getDataCount();
        $pageSize = 100;

        $pageTotal = floor($total / $pageSize) + 1;
        for ($i = 0; $i <= $pageTotal; $i++) {
            echo $i . "\n";
            $list = $this->getDataList($i, $pageSize);
            //处理 shop 数据
            $this->dealShopData($list);
            //处理商品数据
            $this->dealGoodsData($list);
        }
    }

    /**
     * 总数
     * @return \Api\PhpUtils\Mysql\MysqlBase
     */
    private function getDataCount()
    {
        $where = [];
//        $where["lifeAccountId[>]"] = 0;
        return QyqTicketData::count([], $where);
    }

    /**
     * 每页取指定条数数据处理
     * @param $page
     * @param $limit
     * @return \Api\PhpUtils\Mysql\MysqlBase
     */
    private function getDataList($page, $limit)
    {
        $from = $page * $limit;
//        $where["lifeAccountId[>]"] = 0;
        $where["LIMIT"] = [$from, $limit];
        return QyqTicketData::select("*", $where);
    }

    /**
     * 脚本第一步，把所有的shop数据处理
     */
    private function dealShopData($list)
    {
        echo "开始处理 shop 数据 \n";
        foreach ($list as $item) {
            $userId = $item["userId"];
            $accountRes = $this->getLifeAccountIdAndMerchantId($userId);
            if (!empty($accountRes)) {
                $lifeAccountId = $accountRes["life_account_id"];
                $merchantId = $accountRes["merchant_id"];
            } else {
                $lifeAccountInfo = $this->addCreateUnauthorized($userId);
                $lifeAccountId = empty($lifeAccountInfo["life_account_id"]) ? "" : $lifeAccountInfo["life_account_id"];
                $merchantId = empty($lifeAccountInfo["merchant_id"]) ? "" : $lifeAccountInfo["merchant_id"];
            }

            if (empty($lifeAccountId) || empty($merchantId)) {
                echo "add goods data, user_id: $userId 没有 life_account_id \n";
                continue;
            }

            $lifeAccount = [
                "life_account_id" => $lifeAccountId,
                "merchant_id" => $merchantId,
            ];

            $shopId = GoodsService::addShop($lifeAccount);
            echo "当前正在处理店铺id: $shopId \n";
            $subShop = json_decode($item["shopJson"], true);
            if (!empty($subShop)) {
                foreach ($subShop as $sub) {
                    $res = ShopService::getIdgenId(substr($shopId, -2), 'goods');
                    $subShopId = !empty($res[0]) ? $res[0] : '';

                    if (!empty($sub["lbs"])) {
                        $lbs = explode(",", $sub["lbs"]);
                    }
                    $data["sub_shop_id"] = $subShopId;
                    $data["life_account_id"] = $lifeAccountId;
                    $data["shop_id"] = $shopId;
                    $data["shop_name"] = $sub["shopName"];
                    $data["longitude"] = empty($lbs[0]) ? "" : $lbs[0];
                    $data["latitude"] =  empty($lbs[1]) ? "" : $lbs[1];
                    $data["address"] = $sub["address"];
                    $data["phone"] = $sub["phone"];

                    $this->addSubShop($data);
                }
            }
        }
        echo "门店数据处理完成 \n";
    }

    /**
     * 获取 merchant_id
     * @param $lifeAccountId
     * @return mixed|string
     * @throws InterfaceException
     */
    private function getMerchantId($lifeAccountId)
    {
        $url = config('interface', 'merchant.lifeaccount.get_life_account_by_id');
        if (empty($url)) {
            throw new InterfaceException(['cus' => 0]);
        }
        $lifeAccountRes = (new Request())->get($url, ["life_account_id" => $lifeAccountId]);
        return empty($lifeAccountRes["response"]["result"]["merchant_id"]) ? "" : $lifeAccountRes["response"]["result"]["merchant_id"];
    }

    /**
     *
     * @param $userId
     * @return array|mixed
     * @throws InterfaceException
     */
    private function getLifeAccountIdAndMerchantId($userId)
    {
        $url = config('interface', 'merchant.lifeaccount.get_lid_by_uid');
        if (empty($url)) {
            throw new InterfaceException(['cus' => 0]);
        }
        $res = (new Request())->get($url, ["uid" => $userId]);
        return empty($res["response"]["result"]) ? [] : $res["response"]["result"][0];
    }

    private function addCreateUnauthorized($userId)
    {
        echo "add user_id: " . $userId . "\n";
        $url = config('interface', 'merchant.life_account.create_unauthorized');
        if (empty($url)) {
            throw new InterfaceException(['cus' => 0]);
        }
        $res = (new Request())->get($url, ["user_id" => $userId]);
        return empty($res["response"]["result"]) ? [] : $res["response"]["result"];
    }

    /**
     * 添加门店数据
     * @param $data
     */
    private function addSubShop($data)
    {
        $subShop = SubShop::getRecord(["life_account_id" => $data["life_account_id"], "shop_name" => $data["shop_name"]]);
        if (empty($subShop)) {
            SubShop::save($data);
        }
    }

    private function dealGoodsData($list)
    {
        echo "开始 goods 数据处理 \n";
        foreach ($list as $item) {
            $userId = $item["userId"];
            $accountRes = $this->getLifeAccountIdAndMerchantId($userId);
            if (!empty($accountRes)) {
                $lifeAccountId = $accountRes["life_account_id"];
            } else {
                $lifeAccountInfo = $this->addCreateUnauthorized($userId);
                $lifeAccountId = empty($lifeAccountInfo["life_account_id"]) ? "" : $lifeAccountInfo["life_account_id"];
            }
            if (empty($lifeAccountId)) {
                echo "add goods data, user_id: $userId 没有 life_account_id \n";
                continue;
            }
            $shopInfo = Shop::getRecord(["life_account_id" => $lifeAccountId]);
            $shopId = $shopInfo["shop_id"];

            $res = GoodsService::getIdgenId(substr($shopId, -2), "goods", 2);
            if (empty($res)) {
                throw new GoodsException(['cus' => 2]);
            }
            $categoryOneId = 1;
            $categoryTwoId = 13;

            $goodsSpuId = $res[0];
            $goodsSkuId = GoodsSkuId::generateGoodSkuId($res[1], $categoryOneId, $categoryTwoId, 1);

            $publicUserId = $item["userId"];
            $goodsName = $item["title"];
            $descPicUrl = "";
            if (!empty($item["images"])) {
                $images = explode(",", $item["images"]);
                foreach ($images as $image) {
                    $descPicUrl .= "https://qn.zhiyueapp.cn/" . $image . ",";
                }
                $descPicUrl = trim($descPicUrl, ",");
            }
            $desc = $item["desc"];
            $introduce = $item["introduce"];
            $introducePicUrl = $item["productImages"];
            $expirationTime = empty($item["outDate"]) ? null : $item["outDate"];
            $ruleLimit = $item["canBuy"];
            $ruleDesc = $item["ruleIntroduce"];
            $ruleRefund = empty($item["useRule"]) ? 1 : $item["useRule"];
            $ruleDateType = $item["holidayUse"] == 0 ? 2 : 1;
            $ruleStartTime = $item["starTime"];
            $ruleEndTime = $item["endTime"];
            $inventoryTotal = $item["buyCount"];
            $inventoryRest = $item["buyCount"];
            $totalAmountOrder = $item["sellCount"];
            $originalPrice = empty($item["price"]) ? '' : $item["price"] * 100;
            $price = $item["rawPrice"] * 100;

            $goodsSpu = GoodsSpu::getRecord(["life_account_id"=>$lifeAccountId, "goods_name"=>$goodsName]);
            if (empty($goodsSpu)) {
                $spuParams = [
                    "goods_spu_id" => $goodsSpuId,
                    "shop_id" => $shopId,
                    "life_account_id" => $lifeAccountId,
                    "publish_user_id" => $publicUserId,
                    "goods_name" => $goodsName,
                    "desc_pic_url" => $descPicUrl,
                    "desc" => $desc,
                    "goods_type" => GoodsSpu::TYPE_VIRTUAL,
                    "goods_sub_type" => GoodsSpu::SUB_TYPE_TO_SHOP,
                    "goods_sale_type" => GoodsSpu::SALE_TYPE_NO_COMBINATION,
                    "rule_limit" => $ruleLimit,
                    "rule_desc" => $ruleDesc,
                    "rule_refund" => $ruleRefund,
                ];
                GoodsSpu::save($spuParams);
            }

            $goodsSku = GoodsSku::getRecord(["life_account_id"=>$lifeAccountId, "goods_name"=>$goodsName]);

            if (empty($goodsSku)) {
                $skuParams = [
                    "goods_sku_id" => $goodsSkuId,
                    "goods_spu_id" => $goodsSpuId,
                    "life_account_id" => $lifeAccountId,
                    "shop_id" => $shopId,
                    "publish_user_id" => $publicUserId,
                    "category_1_id" => $categoryOneId,
                    "category_2_id" => $categoryTwoId,
                    "goods_name" => $goodsName,
                    "desc_pic_url" => $descPicUrl,
                    "desc" => $desc,
                    "introduce" => $introduce,
                    "introduce_pic_url" => $introducePicUrl,
                    "expiration_time" => $expirationTime,
                    "rule_limit" => $ruleLimit,
                    "rule_desc" => $ruleDesc,
                    "rule_refund" => $ruleRefund,
                    "rule_date_type" => $ruleDateType,
                    "rule_start_time" => $ruleStartTime,
                    "rule_end_time" => $ruleEndTime,
                    "inventory_total" => $inventoryTotal,
                    "inventory_rest" => $inventoryRest,
                    "total_amount_order" => $totalAmountOrder,
                    "total_amount_sold" => $totalAmountOrder,
                    "original_price" => $originalPrice,
                    "price" => $price,
                    "is_import" => 1,
                ];
                GoodsSku::save($skuParams);
            } else {
                $skuParams = [
                    "original_price" => $originalPrice,
                    "price" => $price,
                ];
                GoodsSku::save($skuParams, ["goods_sku_id"=>$goodsSku["goods_sku_id"]]);
            }


            $subShop = json_decode($item["shopJson"], true);
            if (!empty($subShop)) {
                $subShopIdStr = "";
                foreach ($subShop as $sub) {
                    $subShopId = SubShop::select("sub_shop_id", ["life_account_id" => $lifeAccountId, "shop_name" => $sub["shopName"]]);
                    if (!empty($subShopId)) {
                        $subShopIdStr .= $subShopId[0] . ",";
                    }
                }
                $subShopIdStr = trim($subShopIdStr, ",");
            }

            if (!empty($subShopIdStr)) {
                GoodsService::addDealSubShopList($subShopIdStr, $shopId, $goodsSkuId);
            }
        }
        echo "完成 goods 数据处理 \n";
    }
}