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

import cn.com.qmth.examcloud.tool.config.SysProperty;
import cn.com.qmth.examcloud.tool.service.CommonService;
import cn.com.qmth.examcloud.tool.service.export_student_photo.vo.StudentVO;
import cn.com.qmth.examcloud.tool.utils.FileHelper;
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.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.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ExportStudentPhotoTask {

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

    @Autowired
    private SysProperty sysProperty;

    @Autowired
    private CommonService commonService;

    private static final String EXPORT_DIR = "D:/home/captures/photo/";

    public void start(User user) {
        // List<StudentVO> hasPhotoStudents = this.loadStudentFromUrl(user);
        List<StudentVO> hasPhotoStudents = this.loadStudentFromExcel();
        this.downloadStudents(hasPhotoStudents);
    }

    private List<StudentVO> loadStudentFromUrl(User user) {
        Map<String, String> headers = new HashMap<>();
        headers.put("key", user.getKey());
        headers.put("token", user.getToken());

        JsonMapper jsonMapper = new JsonMapper();
        long pageNo = 0, pageSize = 100, total = 0, finishedCount = 0, noPhotoCount = 0;

        final String url = user.getServerUrl()
                + "/api/ecs_core/student/studentPage/%s/%s?rootOrgId=%s&identityNumber=&studentCode=&name=";

        List<StudentVO> hasPhotoStudents = new ArrayList<>();
        while (true) {
            String json = HttpHelper.get(String.format(url, pageNo, pageSize, user.getRootOrgId()), 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()) {
                if (StringUtils.isEmpty(student.getPhotoPath())) {
                    noPhotoCount++;
                    continue;
                }

                student.setPhotoPath(this.fixPhotoUrl(student.getPhotoPath()));
                hasPhotoStudents.add(student);
            }

            pageNo++;
            total = page.getTotal();
            finishedCount += page.getList().size();
            float finishedRate = finishedCount * 100f / total;
            log.info("【{}】 总数:{} 已获取学生数:{} 无底照学生数:{} 进度:{}%", pageNo, total, finishedCount,
                    noPhotoCount, finishedRate);
        }

        return hasPhotoStudents;
    }

    private List<StudentVO> loadStudentFromExcel() {
        List<StudentVO> hasPhotoStudents = new ArrayList<>();
        //todo
        return hasPhotoStudents;
    }

    private void downloadStudents(List<StudentVO> students) {
        for (StudentVO student : students) {
            // 下载底照
            this.downloadPhoto(student);
        }
    }

    private void downloadPhoto(StudentVO student) {
        String identityNumber = student.getIdentityNumber();

        String studentCode;
        if (CollectionUtils.isNotEmpty(student.getStudentCodeList())) {
            studentCode = student.getStudentCodeList().get(0);
        } else {
            log.warn("【无学号】 studentCode:{} identityNumber:{}", student.getStudentCodesStr(),
                    student.getIdentityNumber());
            studentCode = "IDCard_" + student.getIdentityNumber();
        }

        String filePath = EXPORT_DIR + "/" + student.getRootOrgId() + "/" + studentCode + ".jpg";
        if (new File(filePath).exists()) {
            log.info("【已下载】 studentCode:{} identityNumber:{} filePath:{}", studentCode, identityNumber, filePath);
            return;
        }

        try {
            FileHelper.saveImageToFile(student.getPhotoPath(), filePath);
        } catch (Exception e) {
            log.error("studentCode:{} identityNumber:{} err:{}", studentCode, identityNumber, e.getMessage());
        }
    }

    public String fixPhotoUrl(String url) {
        if (StringUtils.isEmpty(url)) {
            return "";
        }

        // ecs-static-upyun.qmth.com.cn 去掉 -upyun
        return url.replace("-upyun.qmth.com.cn", ".qmth.com.cn");
    }

}
