<?php

namespace app\common\repositories\user;

use app\common\dao\user\UserCertificationDao;
use app\common\enum\user\UserCertificationEnum;
use app\common\repositories\BaseRepository;
use app\entity\data\user\UserCertificationEntity;

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

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

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

    /**
     * @param array $uidList
     * @return UserCertificationEntity[]
     */
    public function getUserCertificationEntityListByUidList(array $uidList): array
    {
        return $this->dao->getUserCertificationEntityListByUidList($uidList);
    }

    /**
     * 获取 已通过的 用户实名认证实体 映射 根据用户ID
     * @param array $uidList
     * @return UserCertificationEntity[]
     */
    public function getUserCertificationEntityMapByUidListApproved(array $uidList): array
    {
        /** @var UserCertificationEntity[] $userCertificationEntityMapByUid */
        $userCertificationEntityMapByUid = [];
        $userCertificationEntityList = $this->getUserCertificationEntityListByUidList($uidList);
        foreach ($userCertificationEntityList as $userCertificationEntity) {
            if ($userCertificationEntity->getStatus() == UserCertificationEnum::STATUS['Approved']['code'] && !empty($userCertificationEntity->getUserCard())) {
                $userCertificationEntityMapByUid[$userCertificationEntity->getUid()] = $userCertificationEntity;
            }
        }
        return $userCertificationEntityMapByUid;
    }

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

    /**
     * 写入实名认证记录
     * @param UserCertificationEntity $UserCertificationEntity
     * @return UserCertificationEntity
     */
    public function createByEntity(UserCertificationEntity $UserCertificationEntity): UserCertificationEntity
    {
        $result = $this->dao->create($UserCertificationEntity->toUnderlineArray())->toArray();
        /** @var UserCertificationEntity $entity */
        $entity = UserCertificationEntity::newInstance($result);
        return $entity;
    }
}