package ink.wgink.register.wechat.service.official.account.impl;

import ink.wgink.common.base.DefaultBaseService;
import ink.wgink.exceptions.SearchException;
import ink.wgink.exceptions.UpdateException;
import ink.wgink.interfaces.expand.register.IRegisterHandlerService;
import ink.wgink.module.wechat.pojo.pos.official.account.OfficialAccountUserPO;
import ink.wgink.module.wechat.service.official.account.IOfficialAccountUserService;
import ink.wgink.register.wechat.service.miniapp.OfficialAccountRegisterPhoneVO;
import ink.wgink.register.wechat.service.official.account.IOfficialAccountRegisterService;
import ink.wgink.service.user.pojo.vos.UpdateUsernameVO;
import ink.wgink.service.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: OfficialAccountRegisterServiceImpl
 * @Description: 公众号注册
 * @Author: wanggeng
 * @Date: 2021/5/2 3:56 下午
 * @Version: 1.0
 */
@Service
public class OfficialAccountRegisterServiceImpl extends DefaultBaseService implements IOfficialAccountRegisterService {

    @Autowired(required = false)
    private IRegisterHandlerService registerHandler;
    @Autowired
    private IUserService userService;
    @Autowired
    private IOfficialAccountUserService officialAccountUserService;

    @Override
    public void registerPhone(OfficialAccountRegisterPhoneVO officialAccountRegisterPhoneVO, Map<String, Object> params) throws Exception {
        OfficialAccountUserPO officialAccountUserPO = officialAccountUserService.getPOByUserCode(officialAccountRegisterPhoneVO.getUserCode());
        if (officialAccountUserPO == null) {
            throw new SearchException("验证码错误");
        }
        if (officialAccountUserPO.getIsInitAccount() == 0) {
            throw new UpdateException("已经绑定用户");
        }
        // 更新用户名
        UpdateUsernameVO updateUsernameVO = new UpdateUsernameVO();
        updateUsernameVO.setUsername(officialAccountRegisterPhoneVO.getPhone());
        updateUsernameVO.setUpdateReason("公众号验证码绑定手机");
        userService.updateUsername(officialAccountUserPO.getUserId(), updateUsernameVO);
        // 修改初始账号标识
        officialAccountUserService.updateIsInitAccount(officialAccountUserPO.getOpenId(), 0);
        if (registerHandler == null) {
            registerHandler.handler(officialAccountUserPO.getUserId(), params);
        }
    }


}
