package com.sikey.wa04.business.application.service.user;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.StopWatch;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.sikey.wa04.business.application.service.BaseService;
import com.sikey.wa04.business.application.service.CoordinateConverterService;
import com.sikey.wa04.business.application.service.message.ContactMessageService;
import com.sikey.wa04.business.application.service.message.RejectStrangerMessageService;
import com.sikey.wa04.business.domain.adapter.*;
import com.sikey.wa04.business.domain.entity.*;
import com.sikey.wa04.business.domain.usecase.ChildIdFactory;
import com.sikey.wa04.business.domain.usecase.GroupIdFactory;
import com.sikey.wa04.business.infrastructure.adapter.weather.BaiduWeatherService;
import com.sikey.wa04.business.infrastructure.dto.model.*;
import com.sikey.wa04.business.infrastructure.dto.request.child.CreateChildRequest;
import com.sikey.wa04.business.infrastructure.dto.request.child.GetPhoneNumberRequest;
import com.sikey.wa04.business.infrastructure.dto.request.child.UpdateChildRequest;
import com.sikey.wa04.business.infrastructure.dto.request.messaging.ContactMessageRequest;
import com.sikey.wa04.business.infrastructure.dto.request.messaging.RejectStrangerMessageRequest;
import com.sikey.wa04.business.infrastructure.dto.response.blockunknowncall.GetBlockUnknownCallResponse;
import com.sikey.wa04.business.infrastructure.dto.response.child.CreateChildResponse;
import com.sikey.wa04.business.infrastructure.dto.response.child.GetChildResponse;
import com.sikey.wa04.business.infrastructure.dto.response.child.GetPhoneNumberResponse;
import com.sikey.wa04.business.infrastructure.repository.*;
import com.sikey.wa04.common.dto.header.GenericManufacturerHeader;
import com.sikey.wa04.common.enums.ContactRole;
import com.sikey.wa04.common.enums.Gender;
import com.sikey.wa04.common.enums.IdentityEnum;
import com.sikey.wa04.common.enums.UserType;
import com.sikey.wa04.common.exception.BusinessException;
import com.sikey.wa04.common.exception.errors.Errors;
import com.sikey.wa04.common.interceptor.CurrentRequestUser;
import com.sikey.wa04.common.utils.LocationUtil;
import jakarta.annotation.Resource;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 小孩
 */
@Slf4j
@Service
public class ChildService extends BaseService {

    @Resource
    private GroupAdapter groupAdapter;

    @Resource
    private UserAdapter userAdapter;

    @Resource
    private ContactRepository contactRepository;

    @Resource
    private ChildRepository childRepository;

    @Resource
    private ChildRefRepository childRefRepository;

    @Resource
    private ChildAdapter childAdapter;

    @Resource
    private ChildQueryAdapter childQueryAdapter;

    @Resource
    private DeviceQueryAdapter deviceQueryAdapter;

    @Resource
    private LocationAdapter locationAdapter;

    @Resource
    private CoordinateConverterService coordinateConverterService;

    @Qualifier("myTaskExecutor")
    @Autowired
    private ThreadPoolTaskExecutor myTaskExecutor;

    @Resource
    private RejectStrangerMessageService rejectStrangerMessageService;

    @Resource
    private DeviceBindStateAdapter deviceBindStateAdapter;

    @Resource
    private UserRepository userRepository;

    @Resource
    private GroupMemberAdapter groupMemberAdapter;

    @Resource
    private ContactMessageService contactMessageService;

    @Resource
    private BaiduWeatherService baiduWeatherService;

    @Resource
    private MapTrajectoryPoiRepository mapTrajectoryPoiRepository;

    // trainSpeed the train has moved at a speed of 83 meters per second
    private float trainSpeed = 0.0833333333F; //  300 / (1 * 60 * 60) = 0.0833333333 km/s

    /**
     * 创建小孩
     *
     * @param request 请求参数
     * @return 返回结果
     * @throws Exception 异常
     */
    @Transactional(rollbackOn = Exception.class)
    public CreateChildResponse create(CreateChildRequest request) throws Exception {
        ChildId childId = ChildIdFactory.generate();
        GroupId groupId = GroupIdFactory.generate();
        PhoneNumber phoneNumber = new PhoneNumber(request.phoneNumber(), request.areaCode());
        UserId userId = new UserId(CurrentRequestUser.get().getId());

        Child child = new Child()
                .setId(childId.getId())
                .setUserId(userId.getId())
                .setName(request.name())
                .setPhoneNumber(phoneNumber)
                .setAvatar(request.avatar())
                .setGender(Gender.valueOf(request.gender()))
                .setBirthday(request.birthday())
                .setHeight(request.height())
                .setWeight(request.weight())
                .setIsEnableBlockUnknownCall(true)
                .setIsEnableFence(false);

        // Verify whether the mobile phone number is used by other children
        /*List<ChildModel> childModels = childRepository.findByPhoneNumberAndAreaCode(phoneNumber.number(), phoneNumber.areaCode(), Limit.of(1));
        if (!childModels.isEmpty()) {
            throw Errors.PHONE_NUMBER_EXIST.getException();
        }*/

        // Verify whether the mobile phone number is used by other users
        /*User user = userAdapter.findByPhoneNumber(phoneNumber);
        if (Objects.nonNull(user)) {
            throw Errors.PHONE_NUMBER_EXIST.getException();
        }*/

        // Initialize group chat information
        groupAdapter.initialize(groupId, childId, userId);

        // Initialize ref information
        ChildRefModel refModel = new ChildRefModel();
        refModel.setUserId(userId.getId());
        refModel.setChildId(childId.getId());

        // 新增身份
        refModel.setIdentity(IdentityEnum.IDENTITY_SUPER_ADMIN.getValue());

        childRefRepository.save(refModel);

        // Initialize contact information
        ContactModel contactModel = new ContactModel();
        contactModel.setChildId(childId.getId());
        contactModel.setRefId(userId.getId());
        contactModel.setRemarkName(request.appellation());
        contactModel.setRefType(UserType.USER.getValue());
        contactModel.setRefRole(ContactRole.SUPER_ADMIN.getValue());
        contactRepository.save(contactModel);

        // Create child data
        childAdapter.create(child);

        log.info("Create child success, childId: {}, groupId: {}", childId.getId(), groupId.getId());
        return new CreateChildResponse(childId.getId(), groupId.getId());
    }

    /**
     * 预注册用户, 已经存在数据将不注册
     *
     * @return 用户ID
     */
    private UserModel preRegistrationUser(PhoneNumber phoneNumber) {
        UserModel userModel = userRepository.findByPhoneNumberAndAreaCode(phoneNumber.number(), phoneNumber.areaCode());
        return userModel;
    }

    /**
     * 校验联系人
     *
     * @param childId     儿童id
     * @param phoneNumber 新增用户手机号
     * @param areaCode    国家编码
     * @return
     */
    private void checkConcat(String childId, String phoneNumber, String areaCode) {
        log.info("[校验联系人]校验联系人，cId：{}，phoneNumber：{}", childId, phoneNumber);
        // 查询儿童通讯录
        List<ContactModel> contactModelList = contactRepository.findByChildId(childId);
        log.info("[校验联系人]通讯录联系人，返回数据：{}", JSONUtil.toJsonPrettyStr(contactModelList));
        List<String> refIdList;
        if (CollectionUtil.isNotEmpty(contactModelList)) {
            refIdList = contactModelList.stream().map(ContactModel::getRefId).collect(Collectors.toList());
            List<ChildModel> childContactModelList = childRepository.findAllById(refIdList);
            childContactModelList = childContactModelList.stream().filter(c -> StringUtils.equals(c.getPhoneNumber(), phoneNumber)).toList();

            if (CollectionUtil.isNotEmpty(childContactModelList)) {
                // 校验是否编辑儿童自己
                List<ChildModel> childModelList = childRepository.findByPhoneNumberAndAreaCode(phoneNumber, areaCode);
                if (CollectionUtil.isNotEmpty(childModelList) && !StringUtils.equals(childModelList.getFirst().getId(), childId)) {
                    log.info("[校验联系人]查询儿童，refId：{}，返回数据：{}", childId, JSONUtil.toJsonPrettyStr(childContactModelList));
                    throw new BusinessException(HttpStatus.HTTP_INTERNAL_ERROR, "不能与联系人手机号相同");
                }
            }
        }

    }

    /**
     * 更新小孩
     *
     * @param request 请求参数
     * @throws Exception 异常
     */
    public void update(UpdateChildRequest request, GenericManufacturerHeader  genericManufacturerHeader) throws Exception {
        PhoneNumber phoneNumber = new PhoneNumber(request.phoneNumber(), request.areaCode());
        ChildId childId = ChildIdFactory.create(request.cid());
        UserId userId = new UserId(CurrentRequestUser.get().getId());

        Child child = new Child().setId(childId.getId())
                .setName(request.name())
                .setPhoneNumber(phoneNumber)
                .setAvatar(request.avatar())
                .setGender(Gender.valueOf(request.gender()))
                .setBirthday(request.birthday())
                .setHeight(request.height())
                .setWeight(request.weight());
        childAdapter.updateChild(child, userId, request.appellation());
        // .setIsEnableBlockUnknownCall(false)
        //.setIsEnableFence(true);

        // Verify whether the mobile phone number is used by other children
        // Modify the logic here and do not allow modification of mobile phone numbers.
        // but it does not include the mobile phone number which is your own.
        /*List<ChildModel> childModels = childRepository.findByPhoneNumberAndAreaCode(phoneNumber.number(), phoneNumber.areaCode(), Limit.of(1));
        if (!childModels.isEmpty()
                && childModels.stream().anyMatch(childModel -> !childModel.getId().equals(childId.getId()))) {
            throw Errors.PHONE_NUMBER_EXIST.getException();
        }*/


        // Verify whether the mobile phone number is used by other users
        /*User user = userAdapter.findByPhoneNumber(phoneNumber);
        if (Objects.nonNull(user)) {
            throw Errors.PHONE_NUMBER_EXIST.getException();
        }*/

        List<ContactModel> contactModelList = contactRepository.findByRefId(childId.getId());
        //更新所有好友中的昵称 和 发送变动通讯录消息通知推送给此小孩的所有好友
        if (CollectionUtil.isNotEmpty(contactModelList)) {
            for (ContactModel model : contactModelList) {
                if (model.getRefType().intValue() == UserType.CHILD.getValue()) {
                    log.info("[修改小孩]推送通知好友：好友小孩Id：{};好友小孩身份：{}", model.getChildId(), model.getRefType());
                    //发送变动通讯录消息通知 推送给手表好友
                    ContactMessageRequest contactMessageRequest = new ContactMessageRequest();
                    contactMessageRequest.setCid(model.getChildId());
                    contactMessageRequest.setRole(model.getRefRole());
                    contactMessageRequest.setHeader(genericManufacturerHeader);
                    contactMessageRequest.setUserId(userId.getId());
                    contactMessageService.contactMessageChangeWatch(contactMessageRequest, childId.getId());
                }
            }
        }

        log.info("Update child success, childId: {}", childId.getId());
    }

    /**
     * 删除小孩
     *
     * @param cid 小孩ID
     * @throws Exception 异常
     */
    public void delete(String cid, GenericManufacturerHeader genericManufacturerHeader) throws Exception {
        UserId userId = new UserId(CurrentRequestUser.get().getId());
        ChildId childId = ChildIdFactory.create(cid);

        // Verify whether the child is your own child
        ChildRefModel childRefModel = childRefRepository.findByUserIdAndChildId(userId.getId(), childId.getId());
        if (Objects.isNull(childRefModel)) {
            throw Errors.CHILD_NOT_EXIST.getException();
        }

        String childIdValue = childId.getId();
        Integer identity = childRefModel.getIdentity();
        //管理员删除小孩 需要发送消息通知 推送变更通讯录消息给此小孩所有好友，所以获取当前此小孩的好友列表，因为是会删除通讯录，所以先查询出来。
        List<ContactModel> contactModelList = contactRepository.findByChildId(childIdValue);
        // Delete child data
        childAdapter.delete(childId, userId, identity);
        if (Objects.nonNull(identity) && (identity.intValue() == IdentityEnum.IDENTITY_ADMIN.getValue() || identity.intValue() == IdentityEnum.IDENTITY_SUPER_ADMIN.getValue())) {
            //发送变动通讯录消息通知 推送给此小孩的所有好友
            if (CollectionUtil.isNotEmpty(contactModelList)) {
                for (ContactModel model : contactModelList) {
                    if (model.getRefType().intValue() == UserType.CHILD.getValue()) {
                        log.info("[管理员删除小孩]推送通知好友：好友小孩Id：{};好友小孩身份：{}", model.getRefId(), model.getRefType());
                        //发送变动通讯录消息通知 推送给手表好友
                        ContactMessageRequest contactMessageRequest = new ContactMessageRequest();
                        contactMessageRequest.setCid(model.getRefId());
                        contactMessageRequest.setRole(model.getRefRole());
                        contactMessageRequest.setHeader(genericManufacturerHeader);
                        contactMessageRequest.setUserId(userId.getId());
                        contactMessageService.contactMessageChangeWatch(contactMessageRequest, childIdValue);
                    }
                }
            }
        } else {
            log.info("[家庭成员删除小孩]推送通知给小孩手表：{}", childIdValue);
            // 非管理员业务
            String userIdId = userId.getId();
            //发送变动通讯录消息通知 推送给小孩手表
            ContactMessageRequest contactMessageRequest = new ContactMessageRequest();
            contactMessageRequest.setCid(childIdValue);
            contactMessageRequest.setRole(identity);
            contactMessageRequest.setHeader(genericManufacturerHeader);
            contactMessageRequest.setUserId(userId.getId());
            contactMessageService.contactMessageChangeWatch(contactMessageRequest, userIdId);
        }

        log.info("Delete child success, childId: {}", cid);
    }

    /**
     * 获取小孩
     *
     * @param genericManufacturerHeader 请求
     * @return 小孩列表
     * @throws Exception 异常
     */
    public GetChildResponse get(GenericManufacturerHeader genericManufacturerHeader) throws Exception {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("获取小孩开始计时");

        UserId userId = new UserId(CurrentRequestUser.get().getId());
        List<Child> children = childQueryAdapter.findChildren(userId);
        log.info("[获取小孩]查询家长的小孩: {}", children);

        List<GetChildResponse.GetChild> results = new ArrayList<>();
        for (Child child : children) {

            // Find your role
            List<ContactModel> contactModels = contactRepository.findByChildId(child.getId());
            ContactModel contactModel = contactModels.stream().filter(ct ->
                    ct.getRefId().equals(userId.getId())).findFirst().orElseThrow();
            ContactRole role = ContactRole.valueOf(contactModel.getRefRole());

            // Set the result
            GetChildResponse.GetChild result = new GetChildResponse.GetChild();
            result.setCid(child.getId())
                    .setName(child.getName())
                    .setPhoneNumber(child.getPhoneNumber().number())
                    .setAreaCode(child.getPhoneNumber().areaCode())
                    .setBirthday(child.getBirthday())
                    .setGender(child.getGender().getValue())
                    .setWeight(child.getWeight())
                    .setHeight(child.getHeight())
                    .setAvatar(child.getAvatar())
                    .setAppellation(contactModel.getRemarkName())
                    .setRole(role.getValue());
            Device device = deviceQueryAdapter.findByChildId(new ChildId(child.getId()));
            log.info("[获取小孩] 查询设备返回数据: {}，儿童编码：{}", JSONUtil.toJsonPrettyStr(device), child.getId());
            if (Objects.nonNull(device)) {

                Integer battery = null;
                Integer signal = null;
                Integer maxSignal = null;
                Integer stepCount = null;
                Boolean startup = null;
                DeviceConfig deviceConfig = device.getConfig();
                if (Objects.nonNull(deviceConfig)) {
                    battery = deviceConfig.getBattery();
                    signal = deviceConfig.getSignal();
                    maxSignal = deviceConfig.getMaxSignal();
                    stepCount = deviceConfig.getStepCount();
                    startup = deviceConfig.getStartup();
                }

                GetChildResponse.GetChildDevice resultDevice = new GetChildResponse.GetChildDevice();
                resultDevice.setDid(device.getId().getId())
                        .setVideoCallChannel(device.getVideoCallChannel().getChannel())
                        .setTicket(device.getTicket())
                        .setBattery(battery)
                        .setSignal(signal)
                        .setMaxSignal(maxSignal)
                        .setStartup(startup)
                        .setVersion(device.getVersion())
                        .setModel(device.getModel());
                result.setDevice(resultDevice);

                Optional<Location> optionalLocation = Optional.ofNullable(locationAdapter.findLastLocation(new ChildId(child.getId())));
                if (optionalLocation.isPresent()) {
                    Location location = optionalLocation.get();
                    log.info("[获取小孩]存在地理定位数据：{}", location);
                    result.setLastLocation(new GetChildResponse.GetChildLocation()
                            .setLatitude(location.getAddress().getLatitude())
                            .setLongitude(location.getAddress().getLongitude())
                            .setPositionTime(String.valueOf(location.getPositionTime().toEpochMilli()))
                            .setRadius(location.getAddress().getRadius())
                            .setPointType(Integer.parseInt(location.getType().getTargetValue())));

                    //查询天气返回数据
                    //查询定位的城市信息
                    Optional<MapTrajectoryPoiModel> optionalMapTrajectoryPoiModel = mapTrajectoryPoiRepository.findByTrajectoryId(location.getId());
                    if (optionalMapTrajectoryPoiModel.isPresent()) {
                        MapTrajectoryPoiModel trajectoryPoiModel = optionalMapTrajectoryPoiModel.get();
                        if (trajectoryPoiModel.getAdCode() != null) {
                            //根据城市id查询天气
                            Weather weather = baiduWeatherService.getWeather(trajectoryPoiModel.getAdCode());
                            //组装设置天气返回数据
                            result.setWeather(new GetChildResponse.GetWeather()
                                    .setCityId(weather.getCityId())
                                    .setMyTextCode(weather.getMyTextCode())
                                    .setTextCode(weather.getTextCode())
                                    .setHigh(weather.getHigh())
                                    .setLow(weather.getLow())
                                    .setNow(weather.getNow())
                            );
                        }

                    }
                    // GlobalCoordinates coordinates = location.getCoordinates();

                    // Convert the coordinate system
                    // If you are in 中国大陆 you need to convert location to GCJ02

                    /*List<List<GlobalCoordinates>> chinaPoints = coordinateConverterService.getPoints(CoordinateConverter.CoordinatePoints.CHINA);
                    log.info("[获取小孩]获取点位大小：{}", chinaPoints.size());*/
                    // 中国大陆
                    // location.setCoordinates(coordinateConverterService.BD09toGCJ02(coordinates.getLongitude(), coordinates.getLatitude()));
                    // log.info("[获取小孩]地理定位在中国大陆，源经度：{}，纬度：{}，转换后经度：{}，纬度：{}", coordinates.getLongitude(), coordinates.getLatitude(), location.getCoordinates().getLongitude(), location.getCoordinates().getLatitude());

                    /*if (coordinateConverterService.isPointInPolygonAreas(coordinates, chinaPoints)) {
                        // 中国大陆
                        location.setCoordinates(coordinateConverterService.BD09toGCJ02(coordinates.getLongitude(), coordinates.getLatitude()));
                        log.info("[获取小孩]地理定位在中国大陆，源经度：{}，纬度：{}，转换后经度：{}，纬度：{}", coordinates.getLongitude(), coordinates.getLatitude(), location.getCoordinates().getLongitude(), location.getCoordinates().getLatitude());
                    } else {
                        // 非中国大陆
                        location.setCoordinates(coordinateConverterService.BD09toWGS84(coordinates.getLongitude(), coordinates.getLatitude()));
                        log.info("[获取小孩]地理定位不在中国大陆，源经度：{}，纬度：{}，转换后经度：{}，纬度：{}", coordinates.getLongitude(), coordinates.getLatitude(), location.getCoordinates().getLongitude(), location.getCoordinates().getLatitude());
                    }*/

                    // If the final latitude and longitude are too far apart,
                    // remove the location points and do not add them to the database
                    //Location findPreviousPosition = locationAdapter.findPreviousPosition(device.getId().getId());
//                    if (Objects.nonNull(findPreviousPosition)) {
//                        // 有上一个点位时, 验证手表两个点位的时速多少, 如果超过阈值这个点位将被抛弃
//                        double timeDiff = Duration.between(location.getPositionTime(), findPreviousPosition.getPositionTime()).toNanos() / 1_000_000_000.0;
//
//                        Address address = findPreviousPosition.getAddress();
//                        if (Objects.nonNull(address)) {
//                            double lat2 = Double.parseDouble(address.getLatitude());
//                            double lng2 = Double.parseDouble(address.getLongitude());
//                            // Unit is kilometers meters 除以1000，获得公里数
//                            double distanceDiff = LocationUtil.haversine(Double.parseDouble(location.getAddress().getLatitude()), Double.parseDouble(location.getAddress().getLongitude()), lat2, lng2) / 1000;
//                            if (!(distanceDiff / timeDiff >= trainSpeed)) {
//                                result.setLastLocation(new GetChildResponse.GetChildLocation()
//                                        .setLatitude(location.getAddress().getLatitude())
//                                        .setLongitude(location.getAddress().getLongitude())
//                                        .setPositionTime(String.valueOf(location.getPositionTime().toEpochMilli()))
//                                        .setRadius(location.getAddress().getRadius())
//                                        .setPointType(Integer.parseInt(location.getType().getTargetValue())));
//                            }
//                        }
//                    }

                }

                result.setStepCount(stepCount);
            } else {
                result.setStepCount(0);
            }
            results.add(result);
        }

        stopWatch.stop();

        log.info("[获取小孩]用时：{}", stopWatch.prettyPrint());
        log.info("[获取小孩]返回数据：{}", JSONUtil.toJsonPrettyStr(results));
        return new GetChildResponse(results);
    }

    /**
     * 获取小孩是否开启陌生人拦截
     *
     * @param cid 小孩ID
     * @return 返回结果
     */
    public GetBlockUnknownCallResponse getBlockUnknownCall(String cid) {
        ChildModel childModel = childRepository.findById(cid)
                .orElseThrow();
        log.info("Get block unknown call, cid: {}, isEnable: {}", cid, childModel.getIsEnableBlockUnknownCall());
        return new GetBlockUnknownCallResponse()
                .setIsEnable(childModel.getIsEnableBlockUnknownCall());
    }

    /**
     * 更新小孩是否开启陌生人拦截
     *
     * @param cid                       小孩ID
     * @param isEnable                  是否开启
     * @param genericManufacturerHeader header
     * @return
     */
    public void updateBlockUnknownCall(String cid, Boolean isEnable, GenericManufacturerHeader genericManufacturerHeader) {
        log.info("Update block unknown call, cid: {}, isEnable: {}", cid, isEnable);
        Optional<ChildModel> childModel = childRepository.findById(cid);
        if (!childModel.isPresent()) {
            log.warn("[更新小孩是否开启陌生人拦截]不存在小孩，小孩编码：{}", cid);
            throw Errors.CHILD_NOT_EXIST.getException();
        }

        ChildModel cm = childModel.get();
        cm.setIsEnableBlockUnknownCall(isEnable);
        cm.setUpdatedAt(Instant.now());
        childRepository.save(cm);

        String currentUserId = CurrentRequestUser.get().getId();

        // 是否拒接陌生人消息
        myTaskExecutor.execute(() -> {
            Device device = deviceQueryAdapter.findByChildId(new ChildId(cid));
            RejectStrangerMessageRequest rejectStrangerMessageRequest = new RejectStrangerMessageRequest();
            rejectStrangerMessageRequest.setCid(cid);
            rejectStrangerMessageRequest.setDid(device.getId().getId().intValue());
            rejectStrangerMessageRequest.setStatus(isEnable);
            rejectStrangerMessageRequest.setHeader(genericManufacturerHeader);
            rejectStrangerMessageService.contactMessageChange(rejectStrangerMessageRequest, currentUserId);
        });

    }

    /**
     * 获取手机号
     *
     * @param request 获取手机号
     * @return
     */
    public GetPhoneNumberResponse getPhoneNumber(GetPhoneNumberRequest request) {
        String childId = deviceBindStateAdapter.getBinder(request.getTicket()).getId();
        Optional<ChildModel> childModel = childRepository.findById(childId);

        GetPhoneNumberResponse getPhoneNumberResponse = new GetPhoneNumberResponse();
        if (childModel.isPresent()) {
            ChildModel cm = childModel.get();
            getPhoneNumberResponse.setPhoneNumber(cm.getPhoneNumber());
        }

        return getPhoneNumberResponse;
    }

}
