package com.yizhi.application.exam.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.yizhi.core.application.context.TaskContext;
import com.yizhi.core.application.file.task.AbstractDefaultTask;
import com.yizhi.exam.application.feign.ExamQuestionClient;
import com.yizhi.exam.application.feign.QuestionLibraryClient;
import com.yizhi.exam.application.feign.QuestionLibrarySubjectClient;
import com.yizhi.exam.application.vo.TrQuestionLibrarySubjectVO;
import com.yizhi.exam.application.vo.TrQuestionSubjectOptionVO;
import com.yizhi.exam.application.vo.domain.QuestionLibrary;
import com.yizhi.exam.application.vo.domain.TrExamQuestion;
import com.yizhi.exam.application.vo.infile.ImportExamQuestionSubjectVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;



@Component
public class QuestionSubjectImport extends AbstractDefaultTask<List<ImportExamQuestionSubjectVO>, Map<String, Object>> {

    private static final Logger Log = LoggerFactory.getLogger(QuestionSubjectImport.class);

    //	private static String basePath = FileConstant.SAVE_EXAM_PATH;
    private static String BASEPATH = "e:/";
    private String XLSX = ".xlsx";
    private String TASKNAME = "考试试题导入";

    @Autowired
    QuestionLibraryClient questionLibraryClient;

    @Autowired
    QuestionLibrarySubjectClient questionLibrarySubjectClient;

    @Autowired
    ExamQuestionClient examQuestionClient;

    @Override
    protected List<ImportExamQuestionSubjectVO> execute(Map<String, Object> map) {
        QuestionLibrary questionLibrary;
        TrQuestionLibrarySubjectVO trQuestionLibrarySubjectVO = new TrQuestionLibrarySubjectVO();
        List<TrQuestionSubjectOptionVO> trQuestionSubjectOptionVOList;
        TrQuestionSubjectOptionVO trQuestionSubjectOptionVO;
        TrExamQuestion trExamQuestion;
        String url = (String) map.get("url");
        Long examId = (Long) map.get("examId");
        Long companyId = (Long) map.get("companyId");
        Long accountId = (Long) map.get("accountId");
        String accountName = (String) map.get("accountName");
        Long siteId = (Long) map.get("siteId");
        Long orgId = (Long) map.get("orgId");
        int type = 0;

        trQuestionLibrarySubjectVO.setCompanyId(companyId);
        trQuestionLibrarySubjectVO.setSiteId(siteId);
        trQuestionLibrarySubjectVO.setOrgId(orgId);
        trQuestionLibrarySubjectVO.setAccountId(accountId);
        trQuestionLibrarySubjectVO.setAccountName(accountName);

        Date time = new Date();
        //String path = getFile(url);
        //String path;
        TaskContext taskContext = new TaskContext(examId, TASKNAME, accountId, time);
        //path = "C:\\Users\\phone\\Downloads\\考试试题导入.xlsx";
        URL urlPath = null;
        try {

            urlPath = new URL(url);
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            Log.error("路径转换错误");

        }
        List<ImportExamQuestionSubjectVO> list = null;
        try {
            list = readExcelFile(urlPath, taskContext);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        if (urlPath != null) {
            int sort = 0;        //生成默认排序
            for (ImportExamQuestionSubjectVO importExamQuestionSubjectVO : list) {
                sort += 1;
                questionLibrary = questionLibraryClient.nameIsExist(importExamQuestionSubjectVO.getLibraryName());
                try {
                    if (null != questionLibrary) {
                        //题库存在
                        String typeString = importExamQuestionSubjectVO.getType();
                        if (typeString.equals("单选题")) {
                            type = 1;
                        } else if (typeString.equals("多选题")) {
                            type = 2;
                        } else if (typeString.equals("判断题")) {
                            type = 3;
                        } else if (typeString.equals("问答题")) {
                            type = 4;
                        }
                        trQuestionLibrarySubjectVO.setType(type);
                        trQuestionLibrarySubjectVO.setQuestionLabel(importExamQuestionSubjectVO.getQuestionLabel());
                        trQuestionLibrarySubjectVO.setStem(importExamQuestionSubjectVO.getStem());
                        trQuestionLibrarySubjectVO.setAnalysis(importExamQuestionSubjectVO.getAnalysis());
                        trQuestionLibrarySubjectVO.setLibraryId(questionLibrary.getId());
                        if (type == 4) {
                            trQuestionLibrarySubjectVO.setScoreRule(importExamQuestionSubjectVO.getIsAnswer());
                        }
                        List<String> options = importExamQuestionSubjectVO.getOption();
                        int index = 0;
                        if (null != options && options.size() > 0) {
                            index += 1;
                            trQuestionSubjectOptionVOList = new ArrayList<TrQuestionSubjectOptionVO>();
                            for (String option : options) {
                                trQuestionSubjectOptionVO = new TrQuestionSubjectOptionVO();
                                if (StringUtils.isBlank(option)) {
                                    continue;
                                }
                                trQuestionSubjectOptionVO.setContent(option);
                                if (null != importExamQuestionSubjectVO.getIsAnswer() && importExamQuestionSubjectVO.getIsAnswer().contains("选项" + index)) {
                                    //是正确答案
                                    trQuestionSubjectOptionVO.setIsAnswer(1);
                                } else {
                                    trQuestionSubjectOptionVO.setIsAnswer(0);
                                }
                                trQuestionSubjectOptionVO.setSort(index);
                                trQuestionSubjectOptionVOList.add(trQuestionSubjectOptionVO);
                            }
                            trQuestionLibrarySubjectVO.setTrQuestionSubjectOptionVOList(trQuestionSubjectOptionVOList);
                        }
                        Long resultId = questionLibrarySubjectClient.insert(trQuestionLibrarySubjectVO);
                        if (resultId != null && resultId > 0) {
                            //保存题库题目成功后保存考试题目
                            trExamQuestion = new TrExamQuestion();
                            trExamQuestion.setUpdateTime(time);
                            trExamQuestion.setUpdateById(accountId);
                            trExamQuestion.setUpdateByName(accountName);
                            trExamQuestion.setCreateTime(time);
                            trExamQuestion.setCreateByName(accountName);
                            trExamQuestion.setCreateById(accountId);
                            trExamQuestion.setExamId(examId);
                            trExamQuestion.setSubjectId(resultId);
                            trExamQuestion.setSort(sort);
                            trExamQuestion.setLibraryId(questionLibrary.getId());
                            Long examQuestionId = examQuestionClient.insertOne(trExamQuestion);
                            if (null == examQuestionId || examQuestionId < 1) {
                                fail(taskContext, "保存考试题目失败,该错误存在于" + sort + "行");
                            }
                        } else {
                            fail(taskContext, "保存题目失败,该错误存在于" + sort + "行");
                        }
                    } else {
                        //题库不存在
                        fail(taskContext, "题库不存在,该错误存在于" + sort + "行");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    public String getFile(String url) {
        String fileName = url.substring(url.lastIndexOf("/") + 1) + XLSX;
        String path = BASEPATH + fileName;
        try (InputStream ins = new URL(url).openStream()) {
            Path target = Paths.get(BASEPATH, fileName);
            Files.createDirectories(target.getParent());
            Files.copy(ins, target, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    public List<ImportExamQuestionSubjectVO> readExcelFile(URL urlPath, TaskContext taskContext) throws IOException {
        List<ImportExamQuestionSubjectVO> list = new ArrayList<ImportExamQuestionSubjectVO>();
        ImportExamQuestionSubjectVO vo = null;

        InputStream in = null;
        HttpURLConnection conn = null;
        Workbook wookbook = null;
        Sheet sheet = null;
        try {
            //in = new FileInputStream(path);

            conn = (HttpURLConnection) urlPath.openConnection();//利用HttpURLConnection对象,我们可以从网络中获取网页数据.
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            conn.connect();
            in = conn.getInputStream();    //得到网络返回的输入流
            wookbook = WorkbookFactory.create(in);
            sheet = wookbook.getSheetAt(0); // 获取Excel的第一个子页
            Row row = null;
            String errorMessage;
            List<String> options;
            boolean isAdd = false;
            for (int i = 2; i <= sheet.getLastRowNum(); i++) {
                isAdd = true;
                vo = new ImportExamQuestionSubjectVO();
                int index = 0; // 列数
                row = sheet.getRow(i); // 第几个格子
                int cellNum = row.getPhysicalNumberOfCells();
                //读取所有选项
                options = new ArrayList<String>();
                for (int j = 6; j < cellNum; j++) {
                    try {
                        String context = row.getCell(j).toString();
                        options.add(context);
                    } catch (Exception e) {
                        isAdd = false;
                        errorMessage = "第" + (i + 2) + "行" + "第" + (j + 1) + "列解析出错！";
                        e.printStackTrace();
                        fail(taskContext, errorMessage);
                    }
                }
                try {
                    //读取题库名称
                    vo.setLibraryName(row.getCell(index++).toString());
                } catch (Exception e) {
                    isAdd = false;
                    errorMessage = "第" + (i + 2) + "行" + "第" + (index + 1) + "列解析出错！";
                    e.printStackTrace();
                    fail(taskContext, errorMessage);
                }
                try {
                    vo.setType(row.getCell(index++).toString());
                } catch (Exception e) {
                    isAdd = false;
                    errorMessage = "第" + (i + 2) + "行" + "第" + (index + 1) + "列解析出错！";
                    e.printStackTrace();
                    fail(taskContext, errorMessage);
                }
                try {
                    vo.setStem(row.getCell(index++).toString());
                } catch (Exception e) {
                    isAdd = false;
                    errorMessage = "第" + (i + 2) + "行" + "第" + (index + 1) + "列解析出错！";
                    e.printStackTrace();
                    fail(taskContext, errorMessage);
                }
                try {
                    vo.setIsAnswer(row.getCell(index++).toString());
                } catch (Exception e) {
                    isAdd = false;
                    errorMessage = "第" + (i + 2) + "行" + "第" + (index + 1) + "列解析出错！";
                    e.printStackTrace();
                    fail(taskContext, errorMessage);
                }
                try {
                    vo.setAnalysis(row.getCell(index++).toString());
                } catch (Exception e) {
                    isAdd = false;
                    errorMessage = "第" + (i + 2) + "行" + "第" + (index + 1) + "列解析出错！";
                    e.printStackTrace();
                    fail(taskContext, errorMessage);
                }
                try {
                    vo.setQuestionLabel(row.getCell(index++).toString());
                } catch (Exception e) {
                    isAdd = false;
                    errorMessage = "第" + (i + 2) + "行" + "第" + (index + 1) + "列解析出错！";
                    e.printStackTrace();
                    fail(taskContext, errorMessage);
                }
                vo.setOption(options);

                if (isAdd) {
                    list.add(vo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } // 获取文件输入流
        finally {
            if (in != null) {
                in.close();
            }
            if (wookbook != null) {
                wookbook.close();
            }
        }
        return list;
    }

}
