package com.yonge.cooleshow.auth.service.impl;

import java.util.Date;
import java.util.List;

import com.yonge.toolset.mybatis.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonge.cooleshow.auth.api.dto.RealnameAuthReq;
import com.yonge.cooleshow.auth.api.dto.SysUserInfo;
import com.yonge.cooleshow.auth.api.dto.SysUserQueryInfo;
import com.yonge.cooleshow.auth.api.dto.UserSetReq;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.auth.api.vo.UserSetVo;
import com.yonge.cooleshow.auth.dal.dao.SysUserDao;
import com.yonge.cooleshow.auth.service.SysConfigService;
import com.yonge.cooleshow.auth.service.SysRoleMenuService;
import com.yonge.cooleshow.auth.service.SysUserRoleService;
import com.yonge.cooleshow.auth.service.SysUserService;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.toolset.mybatis.dal.BaseDAO;
import com.yonge.cooleshow.common.entity.ImUserModel;
import com.yonge.cooleshow.common.exception.BizException;

@Service
public class SysUserServiceImpl extends BaseServiceImpl<Long, SysUser> implements SysUserService {

    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysConfigService sysConfigService;

    @Override
    public BaseDAO<Long, SysUser> getDAO() {
        return sysUserDao;
    }

    @Override
    public SysUser queryByUsername(String username) {
        return sysUserDao.queryByUsername(username);
    }

    @Override
    public SysUser queryByPhone(String phone) {
        return sysUserDao.queryByPhone(phone);
    }

    @Override
    public SysUser queryLockByPhone(String phone) {
        return sysUserDao.queryLockByPhone(phone);
    }

    @Override
    public SysUser queryByPhoneAndClient(String phone, String client) {
        return sysUserDao.queryByPhoneAndClient(phone, client);
    }

    @Override
    public SysUserInfo queryUserInfoByUsername(String username) {
        return getSysUserInfo(queryByUsername(username));
    }

    @Override
    public SysUserInfo queryUserInfoByPhone(String phone) {
        return getSysUserInfo(queryLockByPhone(phone));
    }

    @Override
    public SysUserInfo queryUserInfoByPhoneAndClient(String phone, String client) {
        return getSysUserInfo(queryByPhoneAndClient(phone, client));
    }

    private SysUserInfo getSysUserInfo(SysUser sysUser) {
        if (sysUser == null) {
            return null;
        }
        SysUserInfo userInfo = new SysUserInfo();
        userInfo.setSysUser(sysUser);

        List<String> roleCodeList = sysUserRoleService.queryRoleCodeListByUserId(sysUser.getId());
        userInfo.setRoles(roleCodeList.toArray(new String[roleCodeList.size()]));

        List<Long> roleIdList = sysUserRoleService.queryRoleIdListByUserId(sysUser.getId());
        List<String> permissionList = sysRoleMenuService.queryPermissionsByRoleIdList(roleIdList);

        userInfo.setPermissions(permissionList.toArray(new String[permissionList.size()]));

        return userInfo;
    }

    @Override
    public boolean deleteById(Long id) {
        SysUser user = get(id);

        if (user == null) {
            throw new BizException("账户不存在");
        }

        user.setUpdateTime(new Date());
        user.setDelFlag(true);

        update(user);

        return true;
    }

    @Override
    public void updatePassword(String mobile, String password) {
        sysUserDao.updatePassword(mobile, password);
    }

    @Override
    public Long add(SysUser sysUser) {
        sysUserDao.insert(sysUser);
        return sysUser.getId();
    }

    @Override
    public ImUserModel getBasic(Long userId) {
        return sysUserDao.getBasic(userId);
    }

    @Override
    public void updateBaseInfo(SysUser sysUser) {
        sysUserDao.update(sysUser);
    }

    @Override
    public SysUser queryUserInfo(Long userId) {
        return sysUserDao.get(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysUserInfo registerUser(String phone, String clientId) {
        SysUser sysUser = new SysUser();
        sysUser.setPhone(phone);
        String password = sysUser.getPhone().substring(sysUser.getPhone().length() - 6);
        sysUser.setPassword(new BCryptPasswordEncoder().encode(password));
        String defaultHeard = sysConfigService.findConfigValue(SysConfigConstant.DEFAULT_HEARD);
        sysUser.setAvatar(defaultHeard);
        if (StringUtils.equalsIgnoreCase(clientId, "TEACHER")) {
            sysUser.setUserType("TEACHER");
            sysUserDao.insert(sysUser);
            //添加用户现金账户
            //imFeignService.register(new ImUserModel(sysUser.getId().toString(),phone,null));
            //userFeignService.createCashAccount(sysUser.getId());
            //sysTenantAccount
            //创建teacher表
            sysUserDao.saveTeacher(sysUser.getId());
            //创建老师账户
            sysUserDao.createUserAccount(sysUser.getId());
            return queryUserInfoByPhone(phone);
        } else if (StringUtils.equalsIgnoreCase(clientId, "STUDENT")) {
            sysUser.setUserType("STUDENT");
            sysUserDao.insert(sysUser);
            saveStudent(sysUser);
            return queryUserInfoByPhone(phone);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refreshImToken(SysUser sysUser) {
        sysUserDao.refreshImToken(sysUser.getId(), sysUser.getImToken());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveStudent(SysUser sysUser) {
        sysUserDao.saveStudent(sysUser.getId());
        if(!sysUser.getUserType().contains("TEACHER")){
            sysUserDao.createUserAccount(sysUser.getId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTeacher(SysUser sysUser) {

        sysUserDao.saveTeacher(sysUser.getId());
        if(!sysUser.getUserType().contains("STUDENT")){
            sysUserDao.createUserAccount(sysUser.getId());
        }
    }

    @Override
    public void updateUserCard(RealnameAuthReq realNameAuthDto) {
        sysUserDao.updateUserCard(realNameAuthDto);
    }

    @Override
    public UserSetVo getSetDetail(Long id) {
        return sysUserDao.getSetDetail(id);
    }

    @Override
    public void submitSetDetail(UserSetReq setReq, Long id) {
        sysUserDao.updatetSetDetail(setReq, id);
    }

    @Override
    public List<SysUser> queryEmployeeList(SysUserQueryInfo queryInfo) {

        return sysUserDao.queryEmployeeList(queryInfo);
    }

}
