package com.ylx.massage.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylx.common.utils.StringUtils;
import com.ylx.massage.domain.TWxUser;
import com.ylx.massage.domain.vo.TWxUserVo;
import com.ylx.massage.mapper.TWxUserMapper;
import com.ylx.massage.service.TWxUserService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Optional;


/**
 * 服务实现类
 */
@Service
public class TWxUserServiceImpl extends ServiceImpl<TWxUserMapper, TWxUser> implements TWxUserService {

    @Override
    public TWxUser getByOpenId(String openId) {
        LambdaQueryWrapper<TWxUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TWxUser::getcOpenid,openId);
        return getOne(wrapper);
    }

    @Override
    public TWxUser getByPhone(String phone) {
        LambdaQueryWrapper<TWxUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TWxUser::getcPhone, phone);
        return getOne(wrapper);
    }

    @Override
    public Page<TWxUserVo> getUserList(Page<TWxUserVo> page, TWxUserVo user) {

        Page<TWxUserVo> tWxUserVoPage = baseMapper.selectTWxUserList(page, user);
        List<TWxUserVo> records = tWxUserVoPage.getRecords();
        if(CollectionUtil.isNotEmpty(records)){
            records.forEach(item->{
                if(StringUtils.isBlank(item.getCPhone())){
                    item.setCPhone(Optional.ofNullable(item.getPhone()).orElse(StringUtils.EMPTY));
                }
            });
            tWxUserVoPage.setRecords(records);
        }
        return tWxUserVoPage;
    }

    @Override
    public boolean bindPhone(String openId, String phone) {
        TWxUser user = getByOpenId(openId);
        if (user == null) {
            return false;
        }
        user.setcPhone(phone);
        return updateById(user);
    }

    @Override
    public TWxUser phoneLogin(String phone) {
        // 根据手机号查询用户
        TWxUser user = getByPhone(phone);
        // 如果用户不存在，则创建新用户
        if (user == null) {
            user = new TWxUser();
            user.setcPhone(phone);
            // 设置默认角色为普通用户
            user.setRole(0);
            //设置默认头像
            user.setcIcon("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            //设置默认昵称
            user.setcNickName("用户"+phone.substring(7,11));
            save(user);
        }
        return user;
    }
}
