package cn.com.qmth.examcloud.core.questions.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import cn.com.qmth.examcloud.api.commons.security.bean.User;
import cn.com.qmth.examcloud.core.questions.base.Model;
import cn.com.qmth.examcloud.core.questions.base.enums.ExportType;
import cn.com.qmth.examcloud.core.questions.dao.ExamFileRepo;
import cn.com.qmth.examcloud.core.questions.dao.ExportStructureRepo;
import cn.com.qmth.examcloud.core.questions.dao.entity.ExamFile;
import cn.com.qmth.examcloud.core.questions.dao.entity.ExportStructure;
import cn.com.qmth.examcloud.core.questions.dao.entity.ExtractConfig;
import cn.com.qmth.examcloud.core.questions.dao.entity.QuestionTypeNum;
import cn.com.qmth.examcloud.core.questions.service.ExamFileService;
import cn.com.qmth.examcloud.core.questions.service.ExportStructureService;
import cn.com.qmth.examcloud.support.filestorage.FileStorageUtil;

/**
 * @author chenken
 * @date 2017年7月12日 下午4:26:49
 * @company QMTH
 * @description 导出试卷结构设置
 */
@Service("exportStructureService")
public class ExportStructureServiceImpl implements ExportStructureService {

    @Autowired
    private ExportStructureRepo exportStructureRepo;

    @Autowired
    private ExamFileRepo examFileRepo;

    @Autowired
    private ExamFileService examFileService;

//    @Autowired
//    private ExtractConfigRepo extractConfigRepo;

    @Autowired
    private MongoTemplate mongoTemplate;

//    @Autowired
//    private SysProperty sysProperty;

    @Override
    public void saveExportStructure(ExportStructure exportStructure, User user) {
        if (StringUtils.isBlank(exportStructure.getId())) {
            exportStructure.setCreateUser(user.getDisplayName());
            exportStructure.setCreateTime(new Date());
        } else {
            exportStructure.setUpdateUser(user.getDisplayName());
            exportStructure.setUpdateTime(new Date());
        }
        exportStructure.setOrgId(user.getRootOrgId() + "");
        exportStructure.setOrgName(user.getRootOrgName());
        exportStructureRepo.save(exportStructure);
    }

    @Override
    public ExportStructure findByExportStructure(String orgId, String examId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("orgId").is(orgId));
        query.addCriteria(Criteria.where("examId").is(examId));
        List<ExportStructure> list = this.mongoTemplate.find(query, ExportStructure.class);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public Page<ExportStructure> findPageByExportStructure(ExportStructure exportStructure, int curPage, int pageSize) {
        Query query = new Query();
        query.addCriteria(Criteria.where("orgId").is(exportStructure.getOrgId()));
        if (exportStructure.getExamType() != null) {
            query.addCriteria(Criteria.where("examType").is(exportStructure.getExamType()));
        }
        if (StringUtils.isNotBlank(exportStructure.getExamId())) {
            query.addCriteria(Criteria.where("examId").is(exportStructure.getExamId()));
        }
        if (exportStructure.getExportType() != null) {
            query.addCriteria(Criteria.where("exportType").is(exportStructure.getExportType()));
        }
        long count = this.mongoTemplate.count(query, ExportStructure.class);
        query.limit(pageSize);
        query.skip((curPage - 1L) * pageSize);
        List<ExportStructure> list = this.mongoTemplate.find(query, ExportStructure.class);
        return new PageImpl<ExportStructure>(list, PageRequest.of(curPage - 1, pageSize), count);
    }

    @Override
    public ExportStructure findStructureByExamId(String examId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("examId").is(examId));
        ExportStructure exportStructure = this.mongoTemplate.findOne(query, ExportStructure.class);
        if (exportStructure == null) {
            return null;
        }
        if (exportStructure.getExportType() == ExportType.NORMAL) {
            List<QuestionTypeNum> questionTypeNums = exportStructure.getQuestionTypeNums();
            for (QuestionTypeNum questionTypeNum : questionTypeNums) {
                if (questionTypeNum.getQuantity() == null) {
                    //结构设置不完整
                    throw new RuntimeException("试卷结构导出设置不完整,请核实后重新设置导出规则！");
                }
            }
        }
        return exportStructure;
    }

    @Override
    public List<String> findExportStructureByExamType(String examType, User user) {
        Query query = new Query();
        query.addCriteria(Criteria.where("orgId").is(user.getRootOrgId() + ""));
        query.addCriteria(Criteria.where("examType").is(examType));
        List<ExportStructure> exportStructures = this.mongoTemplate.find(query, ExportStructure.class);
        if (exportStructures.size() > 0) {
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < exportStructures.size(); i++) {
                list.add(exportStructures.get(i).getExamId());
            }
            return list;
        }
        return null;
    }

    @Override
    public void deleteExportStructure(String id) {
        //首先根据id，查询到  exportStructure 对象
        ExportStructure exportStructure = Model.of(exportStructureRepo.findById(id));
        if (exportStructure != null) {
            //1.首先删除ExamFile表       根据  examId 和    orgId  查询   ExamFile对象
            List<ExamFile> list = examFileService.findExamFileListByExamFile(new ExamFile(exportStructure.getExamId(), exportStructure.getOrgId()));
            if (list.size() > 0) {
                //根据 ExamFile 对象查询  filePath ，并删除又拍云上的文件 , 然后在删除表里面的数据
//                UpYun upyun = new UpYun(sysProperty.getBucketName(), sysProperty.getUserName(), sysProperty.getPassword());
                for (int i = 0; i < list.size(); i++) {
//                    upyun.deleteFile(list.get(i).getFilePath());
                	//通用存储
                	FileStorageUtil.deleteFile(list.get(i).getFilePath());
                }
                examFileRepo.deleteAll(list);
            }
            //2.然后修改ExtractConfig表      根据 examId 和    orgId
            Query query = new Query();
            query.addCriteria(Criteria.where("orgId").is(exportStructure.getOrgId()));
            query.addCriteria(Criteria.where("examId").is(Long.valueOf(exportStructure.getExamId())));
            Update update = new Update();
            update.set("ifFinish", 0);
            update.unset("finishedPaperIdMap");
            mongoTemplate.updateMulti(query, update, ExtractConfig.class);
            exportStructureRepo.delete(exportStructure);
        }
    }


}

