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

import cn.com.qmth.examcloud.tool.config.SysProperty;
import cn.com.qmth.examcloud.tool.entity.TaskEntity;
import cn.com.qmth.examcloud.tool.service.CommonService;
import cn.com.qmth.examcloud.tool.service.TaskService;
import cn.com.qmth.examcloud.tool.service.unbind_student_code.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.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class UnbindStudentCodeTask implements TaskService {

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

    @Autowired
    private SysProperty sysProperty;

    @Autowired
    private CommonService commonService;

    @Override
    public void start(TaskEntity task) {
        // this.execute(loginUser, task);
    }

    /**
     * 将某个学校的所有学生解绑学号
     */
    public void unbindStudentCodeForExcel(User loginUser) {
        String dataFilePath = "D:/home/data/unbindStudentCodes.xlsx";

        long startTime = System.currentTimeMillis();
        List<StudentVO> list = new ArrayList<>();
        try {
            EasyExcel.read(dataFilePath, StudentVO.class, new AnalysisEventListener<StudentVO>() {
                        @Override
                        public void invoke(StudentVO data, AnalysisContext analysisContext) {
                            list.add(data);
                        }

                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                            // ignore
                        }
                    }
            ).sheet().doRead();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("Excel内容解析错误，请使用标准模板！");
        }

        log.info("待解绑条数:{}", list.size());

        final String unbindUrl = loginUser.getServerUrl() + "/api/ecs_core/student/unbindStudentCode?rootOrgId=%s&studentCode=%s";
        Map<String, String> headers = new HashMap<>();
        headers.put("key", loginUser.getKey());
        headers.put("token", loginUser.getToken());

        for (StudentVO student : list) {
            String url = String.format(unbindUrl, loginUser.getRootOrgId(), student.getStudentCodesStr());
            log.info("identityNumber:{} studentCode:{}", student.getIdentityNumber(), student.getStudentCodesStr());
            HttpHelper.post(url, headers, null);
        }
        log.info("解绑完成，耗时:{}ms", System.currentTimeMillis() - startTime);
    }

    /**
     * 将某个学校的所有学生解绑学号
     */
    public void unbindStudentCodeForAll(User loginUser) {
        Map<String, String> headers = new HashMap<>();
        headers.put("key", loginUser.getKey());
        headers.put("token", loginUser.getToken());

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

        String url = loginUser.getServerUrl() + "/api/ecs_core/student/studentPage/%s/%s";
        while (true) {
            String json = HttpHelper.get(String.format(url, pageNo, pageSize), headers, null);
            PageInfo<StudentVO> page = jsonMapper.parseJson(json, new TypeReference<PageInfo<StudentVO>>() {

            });

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

            String unbindUrl = loginUser.getServerUrl() + "/api/ecs_core/student/unbindStudentCode?rootOrgId=%s&identityNumber=%s";
            for (StudentVO student : page.getList()) {
                HttpHelper.post(String.format(unbindUrl, student.getRootOrgId(), student.getIdentityNumber()), headers, null);
            }

            pageNo++;
            sum += page.getList().size();
            float rate = sum * 100f / page.getTotal();
            log.info("总数:{} 已解绑学号数:{} 进度:{}%", page.getTotal(), sum, rate);
        }
    }

}
