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

import cn.com.qmth.examcloud.tool.config.SysProperty;
import cn.com.qmth.examcloud.tool.service.CommonService;
import cn.com.qmth.examcloud.tool.service.reset_student_password.vo.StudentVO;
import cn.com.qmth.examcloud.tool.utils.HttpHelper;
import cn.com.qmth.examcloud.tool.utils.JsonMapper;
import cn.com.qmth.examcloud.tool.vo.PageInfo;
import cn.com.qmth.examcloud.tool.vo.user.User;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class ResetStudentPasswordTask {

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

    @Autowired
    private SysProperty sysProperty;

    @Autowired
    private CommonService commonService;

    public void start(User user, Long rootOrgId) {
        this.execute(user, rootOrgId);
    }

    /**
     * 将某个学校的所有学生重置密码
     */
    private void execute(User user, Long rootOrgId) {
        Map<String, String> headers = new HashMap<>();
        headers.put("key", user.getKey());
        headers.put("token", user.getToken());

        JsonMapper jsonMapper = new JsonMapper();
        int sum = 0, pageNo = 0, pageSize = 100;

        String url = user.getServerUrl()
                + "/api/ecs_core/student/studentPage/%s/%s?rootOrgId=%s&identityNumber=&studentCode=&name=";
        while (true) {
            String json = HttpHelper.get(String.format(url, pageNo, pageSize, rootOrgId), headers, null);

            PageInfo<StudentVO> page = jsonMapper.parseJson(json, new TypeReference<PageInfo<StudentVO>>() {

            });
            if (page == null || CollectionUtils.isEmpty(page.getList())) {
                break;
            }

            for (StudentVO student : page.getList()) {
                HttpHelper.put(user.getServerUrl() + "/api/ecs_core/student/resetPass/" + student.getId(), headers,
                        null);
            }

            pageNo++;
            sum += page.getList().size();
            float rate = sum * 100f / page.getTotal();
            log.info("rootOrgId:{} 已重置学生密码数:{} 进度:{}%", rootOrgId, sum, rate);
        }
    }

}
