package cc.smtweb.system.bpm.web.login;

import cc.smtweb.framework.core.annotation.SwBody;
import cc.smtweb.framework.core.annotation.SwParam;
import cc.smtweb.framework.core.annotation.SwService;
import cc.smtweb.framework.core.cache.CacheManager;
import cc.smtweb.framework.core.common.R;
import cc.smtweb.framework.core.common.SwConsts;
import cc.smtweb.framework.core.common.SwMap;
import cc.smtweb.framework.core.container.base.SwParameter;
import cc.smtweb.framework.core.container.base.SwReturn;
import cc.smtweb.framework.core.container.factory.ListenerFactory;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.exception.BizException;
import cc.smtweb.framework.core.session.SessionManager;
import cc.smtweb.framework.core.session.UserSession;
import cc.smtweb.framework.core.util.CommUtil;
import cc.smtweb.system.bpm.web.sys.user.party.Party;
import cc.smtweb.system.bpm.web.sys.user.party.PartyCache;
import cc.smtweb.system.bpm.web.sys.user.role.RoleCache;
import cc.smtweb.system.bpm.web.sys.user.user.User;
import cc.smtweb.system.bpm.web.sys.user.user.UserCache;
import cc.smtweb.system.bpm.web.sys.user.user.UserRoleCache;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@SwService
public class AuthService {
    @SwParam
    private DbEngine dbEngine;

    @SwParam
    private SessionManager sessionManager;

    public R getParty(@SwParam("username") String username) {
        Set<Party> partySet = PartyCache.getInstance().getTopSet();
        List<SwMap> list = new ArrayList<>();
        for (Party party : partySet) {
            SwMap data = new SwMap();
            data.put("id", party.getId());
            data.put("text", party.getName());
            data.put("isLeaf", true);
            data.put("children", new ArrayList<>());
            list.add(data);
        }
        return R.success(list);
    }
    // 映射登录
    public R mappingLogin(@SwBody MappingUserParam mappingUserParam){
        SwMap data = new SwMap();
        try {
            SwParameter parameter = new SwParameter();
            parameter.setSingleParam(mappingUserParam);
            SwReturn result = new SwReturn();
            ListenerFactory.fireListener(SwConsts.EventConst.LOGIN_MAPPING,parameter,result);
            MappingUserRet  mappingUserRet = (MappingUserRet)result.getSingleResult();
            User user = UserCache.getInstance().get(mappingUserRet.getUserId());
            if(user==null){
                data.put("isOk", false);
                data.put("extra", mappingUserRet.getExtra());
                data.put("msg", "映射登录失败！");
                return R.success(data);
            }
            UserSession userSession = LoginHelper.simpleLogin(mappingUserRet.getUserId());
            LoginAckVO loginAckVO = createLoginAckVO(user,userSession);
            data.put("user", loginAckVO);
            data.put("token", loginAckVO.getToken());
            data.put("isOk", true);
            data.put("msg", "");
            // 发布登录成功事件
            SwParameter parameter1 = new SwParameter();
            LoginSuccessParam loginSuccessParam = new LoginSuccessParam();
            loginSuccessParam.setUs(userSession);
            loginSuccessParam.setExtra(mappingUserParam.getExtra());
            parameter.setSingleParam(loginSuccessParam);
            ListenerFactory.fireListenerAsyc(SwConsts.EventConst.LOGIN_SUCCESS,parameter1);
            return R.success(data);
        }catch (Exception e){
            data.put("isOk", false);
            data.put("msg", "映射登录失败！");
            return R.success(data);
        }
    }
    public R login(@SwBody LoginVO loginPO) {
        SwMap data = new SwMap();
        User user = null;
        UserSession userSession = null;
        try {
            if ("admin".equals(loginPO.getUsername())) {
                userSession = UserSession.createSys();
//                user=new User();
//                return new UserSession(1);
            } else {
                user = LoginHelper.login(loginPO);
                userSession = LoginHelper.createUserSession(user);
            }
        } catch (BizException e) {
            data.put("isOk", false);
            data.put("msg", e.getMessage());
            return R.success(data);
        } catch (Exception e) {
            data.put("isOk", false);
            data.put("msg", "系统错误");
            return R.success(data);
        }
        userSession.setSiteId(1);
//       UserCache.getInstance().get(userSession.getUserId());
        if (user == null) {
            if (1 != userSession.getUserId()) {
                data.put("isOk", false);
                data.put("msg", "账户异常");
                return R.success(data);
            }
            user = new User();
            user.setId(1);
            user.setName("系统管理员");
        }
        LoginAckVO loginAckVO = createLoginAckVO(user,userSession);
        data.put("user", loginAckVO);
        data.put("token", loginAckVO.getToken());
        data.put("isOk", true);
        data.put("msg", "");
        // 发布登录成功事件
        SwParameter parameter = new SwParameter();
        LoginSuccessParam loginSuccessParam = new LoginSuccessParam();
        loginSuccessParam.setUs(userSession);
        loginSuccessParam.setExtra(loginPO.getExtra() != null?loginPO.getExtra():new SwMap());
        parameter.setSingleParam(loginSuccessParam);
        ListenerFactory.fireListenerAsyc(SwConsts.EventConst.LOGIN_SUCCESS,parameter);
        return R.success(data);
    }

    public R ping(@SwParam("msg") String msg) {
        return R.success(msg);
    }

    public R config(@SwParam("username") String username) {
        return R.success("config: " + username);
    }


    /**
     * 退出登录
     *
     * @return code
     */
    public R logout() {
        sessionManager.logout();
        return R.success();
    }

    public R refreshCache() {
        CacheManager.getIntance().refresh();
        return R.success();
    }
    // 加载个人信息
    public R userInfo(@SwBody SwMap params, UserSession us) {
        SwMap data = new SwMap();

        User user = (User) UserCache.getInstance().get(us.getUserId()).clone();
        user.setId(us.getUserId());
        user.put("create_time", user.getCreate());
        user.put("sur_party", PartyCache.getInstance().get(us.getPartyId()));
        user.put("sur_roles", RoleCache.getInstance().getNamesByIds(UserRoleCache.getInstance().getRoleIdByUP(us.getUserId(), us.getPartyId())));
        data.put("userInfo", user);

        return R.success(data);
    }
    // 修改个人信息
    public R saveUser(@SwBody SwMap params, UserSession us) {
        SwMap userInfo = params.readMap("userInfo");
        User user = UserCache.getInstance().get(us.getUserId());
        user.getData().putAll(userInfo);
        DbEngine.getInstance().findDao(User.ENTITY_NAME).updateEntity(user);
        UserCache.getInstance().put(user);
        return R.success();
    }
    // 修改密码
    public R changePwd(@SwBody SwMap params, UserSession us) {
        String old_pwd = params.readString("old_pwd");
        String new_pwd = params.readString("new_pwd");
        User user = UserCache.getInstance().get(us.getUserId());
        if (!LoginHelper.verifyPwd(user, old_pwd)) {
            return R.error("旧密码错误");
        }
        LoginHelper.resetUserPwd(user, new_pwd);
        return R.success();
    }
    // 创建前端登录对象值对象
    private LoginAckVO createLoginAckVO(User user,UserSession userSession){
        LoginAckVO loginAckVO = new LoginAckVO();
        loginAckVO.setUserId(user.getId());
        loginAckVO.setUserName(user.getName());
        loginAckVO.setRealName(user.getName());
        loginAckVO.setPartyId(userSession.getPartyId());
        loginAckVO.setAvatar("");
        loginAckVO.setDesc(user.getSign());
        loginAckVO.setToken(sessionManager.login(userSession));
        loginAckVO.setUserLevel(user.getLevel() + "");
        loginAckVO.setUserNicky(user.getNicky());
        loginAckVO.setUserTel(user.getTel());
        return loginAckVO;
    }
}
