package org.dromara.mp.dubbo;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboService;
import org.dromara.common.core.enums.UserStatus;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.map.api.RemoteUserWokerService;
import org.dromara.map.api.domain.RemoteUserWorkerVo;
import org.dromara.map.api.model.LoginMpUser;
import org.dromara.mp.domain.UserWorker;
import org.dromara.mp.mapper.UserWorkerMapper;
import org.dromara.mp.service.IUserWorkerService;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author sunzexing
 * @version 1.0
 * @title RemoteUserWorkerServiceImpl
 * @description
 * @create 2024-03-29 10:57
 */
@RequiredArgsConstructor
@Service
@DubboService
public class RemoteUserWorkerServiceImpl  implements RemoteUserWokerService {


    @Resource
    private IUserWorkerService  userWorkerService;

    @Resource
    private UserWorkerMapper userWorkerMapper;


    @Override
    public LoginMpUser selectUserWorkByPhonenumer(String phonenumber, String tenantId) {
        return TenantHelper.dynamic(phonenumber,()->{
                UserWorker userWorker =  userWorkerMapper.selectOne(new LambdaQueryWrapper<UserWorker>()
                    .select(UserWorker::getPhone, UserWorker::getId,UserWorker::getStatus)
                    .eq(UserWorker::getPhone, phonenumber));
                if (ObjectUtil.isNotNull(userWorker)) {
                    if (userWorker.getStatus() == 2) {
                        throw new UserException("user.blocked", phonenumber);
                    }
                    LoginMpUser userWorkVo = getLoginMpUser(userWorker);
                    return userWorkVo;
                }else{
                    UserWorker uw = new UserWorker();
                    uw.setPhone(phonenumber);
                    uw.setIsAuth(0);
                    uw.setStatus(1);
                    uw.setAddTime(DateUtil.date().toJdkDate());
                    this.userWorkerMapper.insert(uw);
                    LoginMpUser userWorkVo = getLoginMpUser(uw);

//                    LoginMpUser  userWorkVo = new LoginMpUser();
//                    userWorkVo.setUserId(IdUtil.getSnowflakeNextId());
                    return userWorkVo;
                }
        });

    }

    @NotNull
    private LoginMpUser getLoginMpUser(UserWorker userWorker) {
        LoginMpUser  userWorkVo = new LoginMpUser();
        userWorkVo.setUserId(userWorker.getId());
        userWorkVo.setPhone(userWorker.getPhone());
        userWorkVo.setName(userWorker.getName());
//        userWorkVo.setIsAuth(userWorker.getIsAuth());
        return userWorkVo;
    }


}
