<?php

namespace app\controller\api\store\order;

use app\common\repositories\store\order\StoreGroupOrderRepository;
use app\entity\request\api\store\order\StoreOrderCreateRequestEntity;
use app\validate\api\store\order\StoreOrderCreateValidate;
use crmeb\basic\BaseController;
use think\App;
use think\facade\Cache;

class StoreGroupOrder extends BaseController
{

    /**
     * @var StoreGroupOrderRepository
     */
    protected $repository;
    // private $source;
    // private $merId;

    /**
     * StoreOrder constructor.
     * @param App $app
     * @param StoreGroupOrderRepository $repository
     */
    public function __construct(App $app, StoreGroupOrderRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;

        // $this->source = request()->header('source');
        // $this->merId = request()->header('merId');
    }

    /**
     * @param StoreOrderCreateValidate $storeOrderCreateValidate
     * @return mixed
     */
    public function createStoreGroupOrder(StoreOrderCreateValidate $storeOrderCreateValidate)
    {
        // 1、接收参数
        $storeOrderCreateValidateResult = $storeOrderCreateValidate->validateRequest();
        // 如果验证失败，返回错误
        if ($storeOrderCreateValidateResult['status'] == 'error') {
            return app('json')->fail($storeOrderCreateValidateResult['message']);
        }

        // 根据用户ID 获取用户实体信息
        $uid = $this->request->uid();
        // 验证通过，继续处理数据
        /** @var StoreOrderCreateRequestEntity $storeOrderCreateRequestEntity */
        $storeOrderCreateRequestEntity = $storeOrderCreateValidateResult['data'];
        $storeOrderCreateRequestEntity->setUid($uid);

        // 2、加锁
        // 增加锁，防止同一用户重读点击
        $redisHandler = Cache::store('redis')->handler();
        $cartIdList = $storeOrderCreateRequestEntity->getCartIdList();
        sort($cartIdList);
        $isSet = $redisHandler->set('createStoreGroupOrder' . '-' . implode('-', $cartIdList), 1, ['nx', 'ex' => 30]);
        if (!$isSet) {
            return app('json')->fail('请勿重复下单');
        }

        // 3、创建订单
        makeLock()->lock();
        try {
            $result = $this->repository->createStoreGroupOrder($storeOrderCreateRequestEntity);
        } catch (\Throwable $e) {
            makeLock()->unlock();
            throw $e;
        }
        makeLock()->unlock();

        if (!empty($result['code'])) {
            return app('json')->fail($result['message']);
        }
        return app('json')->success($result['message'], $result['data']);
    }
}