package cn.com.qmth.examcloud.tool.service;

import cn.com.qmth.examcloud.tool.cache.LoginSessionManager;
import cn.com.qmth.examcloud.tool.config.SysProperty;
import cn.com.qmth.examcloud.tool.service.batch_create_user.vo.RoleInfo;
import cn.com.qmth.examcloud.tool.service.batch_create_user.vo.UserInfo;
import cn.com.qmth.examcloud.tool.service.export_student_answer_and_score_detail.vo.CourseVO;
import cn.com.qmth.examcloud.tool.service.update_correct_answer_and_re_fix_score.vo.ExamStudentVO;
import cn.com.qmth.examcloud.tool.utils.HttpHelper;
import cn.com.qmth.examcloud.tool.utils.JsonMapper;
import cn.com.qmth.examcloud.tool.vo.Pager;
import cn.com.qmth.examcloud.tool.vo.user.User;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class CommonService {

    private final static Logger log = LoggerFactory.getLogger(CommonService.class);

    @Autowired
    private SysProperty sysProperty;

    public User login(String serverUrl, String loginName, String password, String smsCode) {
        // serverUrl 示例：abc.exam-cloud.cn
        String[] values = serverUrl.split("\\.");
        String domain = values[0] + ".ecs.qmth.com.cn";
        String httpUrl = "https://" + serverUrl;
        log.info("serverUrl:{}  domain:{}", httpUrl, domain);

        Map<String, Object> params = new HashMap<>();
        // params.put("rootOrgId", 0);
        params.put("domain", domain);
        params.put("accountType", "COMMON_LOGIN_NAME");
        params.put("accountValue", loginName);
        params.put("password", password);
        if (StringUtils.isNotBlank(smsCode)) {
            params.put("smsCode", smsCode);
        }

        return this.doLogin(httpUrl, params);
    }

    private User doLogin(String serverUrl, Map<String, Object> params) {
        String url = serverUrl + "/api/ecs_core/auth/login";
        String result = HttpHelper.post(url, null, params);
        log.info("LOGIN_IN {}", result);

        User user = new JsonMapper().parseJson(result, User.class);
        user.setServerUrl(serverUrl);

        LoginSessionManager.addLoginSession(user);
        return user;
    }

    /**
     * 获取考试相关的课程列表
     */
    public List<CourseVO> getExamCourseList(User loginUser, Long examId) {
        Map<String, String> headers = new HashMap<>();
        headers.put("key", loginUser.getKey());
        headers.put("token", loginUser.getToken());

        Map<String, Object> params = new HashMap<>();
        params.put("examId", examId);
        params.put("pageNo", 1);
        params.put("pageSize", 1000);

        String url = loginUser.getServerUrl() + "/api/ecs_exam_work/exam/course/list";
        String json = HttpHelper.post(url, headers, params);

        Pager<CourseVO> page = new JsonMapper().parseJson(json, new TypeReference<Pager<CourseVO>>() {

        });

        if (page != null && page.getContent() != null) {
            return page.getContent();
        }
        return new ArrayList<>();
    }


    public Long queryCourseIdByCode(User loginUser, String courseCode) {
        if (StringUtils.isBlank(courseCode)) {
            return null;
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("key", loginUser.getKey());
        headers.put("token", loginUser.getToken());

        Map<String, String> params = new HashMap<>();
        params.put("rootOrgId", String.valueOf(loginUser.getRootOrgId()));
        params.put("code", courseCode);

        String result;
        try {
            String url = loginUser.getServerUrl() + "/api/ecs_core/course/byCode";
            result = HttpHelper.get(url, headers, params);
        } catch (Exception e) {
            log.error("courseCode:{} {}", courseCode, e.getMessage());
            return null;
        }

        JsonNode value = new JsonMapper().getNode(result);
        if (value == null) {
            return null;
        }

        String id = value.get("id").asText();
        if (StringUtils.isNotEmpty(id)) {
            return Long.parseLong(id);
        }

        return null;
    }

    public Long queryOrgIdByCode(User loginUser, String orgCode) {
        if (StringUtils.isBlank(orgCode)) {
            return null;
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("key", loginUser.getKey());
        headers.put("token", loginUser.getToken());

        Map<String, String> params = new HashMap<>();
        params.put("rootOrgId", String.valueOf(loginUser.getRootOrgId()));
        params.put("code", orgCode);

        String result;
        try {
            String url = loginUser.getServerUrl() + "/api/ecs_core/org/byCode";
            result = HttpHelper.get(url, headers, params);
        } catch (Exception e) {
            log.error("orgCode:{} {}", orgCode, e.getMessage());
            return null;
        }

        JsonNode value = new JsonMapper().getNode(result);
        if (value == null) {
            return null;
        }

        String id = value.get("id").asText();
        if (StringUtils.isNotEmpty(id)) {
            return Long.parseLong(id);
        }

        /*Map<String, String> params = new HashMap<>();
        params.put("parentId", String.valueOf(loginUser.getRootOrgId()));
        params.put("code", orgCode);

        String result;
        try {
            String url = loginUser.getServerUrl() + "/api/ecs_core/org/subOrgPage/0/5";
            result = HttpHelper.get(url, headers, params);
        } catch (Exception e) {
            log.error("orgCode:{} {}", orgCode, e.getMessage());
            return null;
        }

        JsonNode value = new JsonMapper().getNode(result);
        if (value == null) {
            return null;
        }

        int total = value.get("total").asInt();
        if (total > 0) {
            Iterator<JsonNode> list = value.get("list").iterator();
            while (list.hasNext()) {
                JsonNode node = list.next();
                if (orgCode.equals(node.get("code").asText())) {
                    return node.get("id").asLong();
                }
            }
        }*/

        return null;
    }

    public Map<String, Long> queryRoles(User loginUser) {
        Map<String, String> headers = new HashMap<>();
        headers.put("key", loginUser.getKey());
        headers.put("token", loginUser.getToken());

        String url = loginUser.getServerUrl() + "/api/ecs_core/rolePrivilege/getRoles?includeSuperAdmin=true";
        String result = HttpHelper.post(url, headers, null);
        log.info(result);

        List<RoleInfo> roles = new JsonMapper().toList(result, RoleInfo.class);
        Map<String, Long> maps = new HashMap<>();
        if (CollectionUtils.isNotEmpty(roles)) {
            for (RoleInfo role : roles) {
                maps.put(role.getRoleName(), role.getRoleId());
            }
        }

        return maps;
    }

    public UserInfo queryUserByLoginName(User loginUser, String loginName) {
        Map<String, String> headers = new HashMap<>();
        headers.put("key", loginUser.getKey());
        headers.put("token", loginUser.getToken());

        Map<String, String> params = new HashMap<>();
        params.put("rootOrgId", String.valueOf(loginUser.getRootOrgId()));
        params.put("loginName", loginName);

        String url = loginUser.getServerUrl() + "/api/ecs_core/user/query";
        String result = HttpHelper.get(url, headers, params);
        // log.info(result);

        List<UserInfo> users = new JsonMapper().toList(result, UserInfo.class);
        if (CollectionUtils.isNotEmpty(users)) {
            for (UserInfo user : users) {
                if (user.getLoginName().equals(loginName)) {
                    return user;
                }
            }
        }

        return null;
    }

    /**
     * 获取网考考生列表
     */
    public List<ExamStudentVO> getExamStudentList(User loginUser, Long examId, Long courseId, String identityNumber) {
        Map<String, Object> params = new HashMap<>();
        params.put("examId", examId);
        if (courseId != null) {
            params.put("courseId", courseId);
        }
        if (StringUtils.isNotBlank(identityNumber)) {
            params.put("identityNumber", identityNumber);
        }
        params.put("pageSize", 500);

        Map<String, String> headers = new HashMap<>();
        headers.put("key", loginUser.getKey());
        headers.put("token", loginUser.getToken());

        String url = loginUser.getServerUrl() + "/api/ecs_oe_admin/exam/student/simple/list";
        List<ExamStudentVO> all = new ArrayList<>();
        JsonMapper jsonMapper = new JsonMapper();

        int sum = 0, pageNo = 0;
        while (true) {
            params.put("pageNo", ++pageNo);
            String json = HttpHelper.post(url, headers, params);

            Pager<ExamStudentVO> page = jsonMapper.parseJson(json, new TypeReference<Pager<ExamStudentVO>>() {

            });
            if (page == null || CollectionUtils.isEmpty(page.getContent())) {
                break;
            }
            all.addAll(page.getContent());

            sum += page.getContent().size();
            float rate = sum * 100f / page.getTotalElements();
            log.info("examId:{} courseId:{} 已获取考生数:{} 进度:{}%", examId, courseId, sum, rate);
        }

        return all;
    }

}
