package thyyxxk.webserver.service;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.LoginDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.dictionary.CodeName;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.entity.login.VueMenu;
import thyyxxk.webserver.service.externalhttp.CorpWxSrvc;
import thyyxxk.webserver.service.redislike.RedisLikeService;
import thyyxxk.webserver.utils.*;

import java.util.*;

/**
 * @author dj
 */
@Slf4j
@Service
public class LoginService {
    private final LoginDao dao;
    private final TokenService tokenService;
    private final RedisLikeService redisLikeService;
    private final CorpWxSrvc srvc;

    @Autowired
    public LoginService(LoginDao dao, TokenService tokenService, RedisLikeService redisLikeService, CorpWxSrvc srvc) {
        this.dao = dao;
        this.tokenService = tokenService;
        this.redisLikeService = redisLikeService;
        this.srvc = srvc;
    }

    public ResultVo<UserInfo> login(UserInfo userInfo) {
        UserInfo tempUserInfo = dao.findUserByCodeRsFromDjUserBase(userInfo.getCodeRs());
        if (null == tempUserInfo) {
            tempUserInfo = dao.findUserByCodeRsFromEmployeeMi(userInfo.getCodeRs());
            if (null == tempUserInfo) {
                return ResultVoUtil.fail(ExceptionEnum.USER_NOT_EXIST);
            }
            dao.insertNewUserToDjUserBase(tempUserInfo);
        }
        if (!Objects.equals("fromTriageScreen", userInfo.getSid()) &&
                !userInfo.getPassword().equals(tempUserInfo.getPassword())) {
            return ResultVoUtil.fail(ExceptionEnum.INVALID_PASSWORD);
        }
        String token = tokenService.getToken(tempUserInfo);
        try {
            JSONObject json = srvc.getUserinfo(TokenUtil.getWeComAddressBookToken(), tempUserInfo.getCodeRs());
            tempUserInfo.setAvatar(json.getString("avatar"));
        } catch (Exception ignored) {
        }

        tempUserInfo.setToken(token);
        tempUserInfo.setSid(makeSid(tempUserInfo.getCode(), token, userInfo.getSid()));
        tempUserInfo.setRoles(dao.getUserRoles(tempUserInfo.getCode()));
        tempUserInfo.setDeptName(dao.getDeptName(tempUserInfo.getDeptCode()));
        redisLikeService.handleUserLogin(tempUserInfo.getCode());
        return ResultVoUtil.success(tempUserInfo);
    }

    public ResultVo<Map<String, Object>> fetchVueMenus() {
        List<Integer> roles = dao.getUserRoles(TokenUtil.getTokenUserId());
        if (null == roles || roles.isEmpty()) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "请联系管理员为您分配角色权限。");
        }
        List<VueMenu> temp = dao.selectVueMenusByRoles(roles);
        Map<String, Object> map = new HashMap<>();
        List<VueMenu> list = TreeUtil.getVueMenuTree(temp);
//        list.forEach(item -> {
//            if (null != item.getChildren() && item.getChildren().size() == 1) {
//                VueMenu child = item.getChildren().get(0);
//                item.setId(child.getId());
//                item.setPath(child.getPath());
//                item.setMetaTitle(child.getMetaTitle());
//                item.setMetaIcon(child.getMetaIcon());
//                item.setParent(child.getParent());
//                item.setCompleteRoute(child.getCompleteRoute());
//                item.setHideTabs(child.getHideTabs());
//                item.setHideMenu(child.getHideMenu());
//                item.setRedirect(child.getRedirect());
//                item.setMeta(child.getMeta());
//                item.setChildren(child.getChildren());
//            }
//        });
        map.put("routes", list);
        map.put("paths", dao.selectVueMenusPathByRoles(roles));
        return ResultVoUtil.success(map);
    }

    public ResultVo<List<CodeName>> getWards() {
        String code = TokenUtil.getTokenUserId();
        List<Integer> roles = dao.getUserRoles(code);
        if (roles.contains(1) || roles.contains(2) || roles.contains(8)) {
            return ResultVoUtil.success(dao.getAllWards());
        } else {
            return ResultVoUtil.success(dao.getUserWards(code));
        }
    }

    public UserInfo findUserByCode(String code) {
        return dao.findUserByCode(code);
    }

    private String makeSid(String code, String token, String sid) {
        String tempToken = token.replaceAll("\\.", "")
                .replaceAll("_", "")
                .replaceAll("-", "");
        String flakeIdSub = "-" + SnowFlakeId.instance().nextId() + "-";
        int random = new Random().nextInt(80);
        String tokenSub = tempToken.substring(random, random + 18);
        if (StringUtil.notBlank(sid) && "fromTriageScreen".equals(sid)) {
            tokenSub += "-triageFloorScreen";
        }
        return code + flakeIdSub + tokenSub;
    }
}
