<?php

namespace app\common\repositories\user;

use app\common\dao\user\UserSignVrDao;
use app\common\enum\user\UserSignVrEnum;
use app\common\repositories\BaseRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\entity\data\user\UserEntity;
use app\entity\data\user\UserSignVrEntity;
use think\db\exception\DbException;
use think\exception\ValidateException;

class UserSignVrRepository extends BaseRepository
{
    public function __construct(UserSignVrDao $dao)
    {
        $this->dao = $dao;
    }

    public function create($data)
    {
        return $this->dao->create($data);
    }

    /**
     * @param int $id
     * @return UserSignVrEntity
     */
    public function getUserSignVrEntityById(int $id): UserSignVrEntity
    {
        $entityList = $this->getUserSignVrEntityListByIdList([$id]);
        $entity = array_shift($entityList);
        if ($entity instanceof UserSignVrEntity) {
            return $entity;
        } else {
            /** @var UserSignVrEntity */
            return UserSignVrEntity::newInstance();
        }
    }

    /**
     * @param array $idList
     * @return UserSignVrEntity[]
     */
    public function getUserSignVrEntityListByIdList(array $idList): array
    {
        return $this->dao->getUserSignVrEntityListByIdList($idList);
    }

    /**
     * 写入Vr记录
     * @param UserSignVrEntity $userSignVrEntity
     * @return UserSignVrEntity
     */
    public function createByEntity(UserSignVrEntity $userSignVrEntity): UserSignVrEntity
    {
        $result = $this->dao->create($userSignVrEntity->toUnderlineArray())->toArray();
        /** @var UserSignVrEntity $entity */
        $entity = UserSignVrEntity::newInstance($result);
        return $entity;
    }

    /**
     * 添加Vr记录
     * @param int $uid
     * @param int $type
     * @param float $number
     * @param string $mark
     * @param string $orderType
     * @param string $orderId
     * @return UserSignVrEntity
     */
    public function addUserSingVr(int $uid, int $type, float $number, string $mark = '', string $orderType = '', string $orderId = ''): UserSignVrEntity
    {
        if (!empty($orderType)) {
            if (!empty($orderId)) {
                if ($orderType == UserSignVrEnum::ORDER_TYPE['Platform']['code']) {
                    /** @var StoreOrderRepository $storeOrderRepository */
                    $storeOrderRepository = app()->make(StoreOrderRepository::class);
                    $storeOrderEntity = $storeOrderRepository->getStoreOrderEntityByOrderId((int)$orderId);
                    if (empty($storeOrderEntity->getOrderId())) {
                        throw new ValidateException('未查询到订单信息');
                    }
                }
            }
        }

        /** @var UserSignVrEntity $userSignVrEntity */
        $userSignVrEntity = UserSignVrEntity::newInstance();
        $userSignVrEntity->setUid($uid)
            ->setType($type)
            ->setNumber($number)
            ->setMark($mark)
            ->setOrderType($orderType)
            ->setOrderId($orderId)
            ->setSurplus(0.00)
            ->setAddtime(time());

        return $this->createByEntity($userSignVrEntity);
    }

    /**
     * 将 Vr 记录设置为生效状态 并对用户的 Vr 字段进行增减
     * @param int $id
     * @return int
     */
    public function execute(int $id): int
    {
        $result = $this->executeByIdList([$id]);
        return array_shift($result);
    }

    /**
     * @param array $idList
     * @return array
     */
    public function executeByIdList(array $idList): array
    {
        $userSignVrEntityList = $this->getUserSignVrEntityListByIdList($idList);
        $userIdList = [];

        // 忽略 已经生效的 记录
        $userSignVrEntityList = array_filter($userSignVrEntityList, function ($entity) use (&$userIdList) {
            // VR 结算字段为空
            if (empty($entity->getSettlementTime()) && !empty($entity->getUid())) {
                $userIdList[] = $entity->getUid();
                return true;
            }
            return false;
        });

        if (!empty($userSignVrEntityList)) {
            // 获取用户 映射信息
            /** @var UserRepository $userRepository */
            $userRepository = app()->make(UserRepository::class);
            /** @var UserEntity[] $userEntityMapByUid */
            $userEntityMapByUid = [];
            if (!empty($userIdList)) {
                $userEntityMapByUid = $userRepository->getUserEntityMapByUidList($userIdList);
            }

            /** @var UserEntity[] $updateUserEntityList */
            $updateUserEntityList = [];
            /** @var UserSignVrEntity[] $updateUserVrEntityList */
            $updateUserVrEntityList = [];
            foreach ($userSignVrEntityList as $userSignVrEntity) {

                $userEntity = $userEntityMapByUid[$userSignVrEntity->getUid()];
                if (empty($userEntity) || empty($userEntity->getUid())) {
                    throw new ValidateException("未查询到用户信息(vrId:{$userSignVrEntity->getId()})");
                }

                // 组建 更新 用户信息
                if (isset($updateUserEntityList[$userEntity->getUid()])) {
                    $updateUserEntity = $updateUserEntityList[$userEntity->getUid()];
                } else {
                    /** @var UserEntity $updateUserEntity */
                    $updateUserEntity = UserEntity::newInstance();
                    $updateUserEntity
                        ->setUid($userEntity->getUid())
                        ->setVr($userEntity->getVr());

                }
                // 组建 账单 记录
                if (isset($updateUserVrEntityList[$userSignVrEntity->getId()])) {
                    $updateUserSignVrEntity = $updateUserVrEntityList[$userSignVrEntity->getId()];
                } else {
                    /** @var UserSignVrEntity $updateUserSignVrEntity */
                    $updateUserSignVrEntity = UserSignVrEntity::newInstance();
                    // 更新 账单记录 状态
                    $updateUserSignVrEntity
                        ->setId($userSignVrEntity->getId())
                        ->setSettlementTime(date('Y-m-d H:i:s'));
                }

                if ($userSignVrEntity->getType() == UserSignVrEnum::TYPE['Consume']['code']) {
                    // 消耗
                    $updateUserEntity->setVr(bcsub($updateUserEntity->getVr(), $userSignVrEntity->getNumber(), 2));
                    if ($updateUserEntity->getVr() < 0.00) {
                        throw new ValidateException('用户Vr不足');
                    }
                } else {
                    $updateUserEntity->setVr(bcadd($updateUserEntity->getVr(), $userSignVrEntity->getNumber(), 2));
                }
                $updateUserSignVrEntity->setSurplus($updateUserEntity->getVr());

                $updateUserEntityList[$userSignVrEntity->getUid()] = $updateUserEntity;
                $updateUserVrEntityList[$userSignVrEntity->getId()] = $updateUserSignVrEntity;
            }

            try {
                if (!empty($updateUserEntityList)) {
                    $userRepository->batchUpdateUserDataByDataList(
                        array_map(function (UserEntity $updateUserEntity) {
                            return $updateUserEntity->toUnderlineArray();
                        }, $updateUserEntityList)
                    );
                }

                if (!empty($updateUserVrEntityList)) {
                    $this->batchUpdateUserSignVrDataByDataList(
                        array_map(function (UserSignVrEntity $updateUserSignVrEntity) {
                            return $updateUserSignVrEntity->toUnderlineArray();
                        }, $updateUserVrEntityList)
                    );
                }
            } catch (DbException $e) {

            }
        }
        return $idList;
    }

    /**
     * @param $dataList
     * @return array
     */
    public function batchUpdateUserSignVrDataByDataList($dataList): array
    {
        return $this->dao->saveAll($dataList);
    }
}