package cn.com.qmth.examcloud.core.questions.api.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.com.qmth.examcloud.api.commons.enums.AdminOperateType;
import cn.com.qmth.examcloud.api.commons.security.bean.User;
import cn.com.qmth.examcloud.core.basic.api.CourseCloudService;
import cn.com.qmth.examcloud.core.basic.api.request.GetCourseReq;
import cn.com.qmth.examcloud.core.questions.dao.entity.AudioTimeConfig;
import cn.com.qmth.examcloud.core.questions.service.AudioTimeConfigService;
import cn.com.qmth.examcloud.core.questions.service.cache.ExtractConfigPaperCache;
import cn.com.qmth.examcloud.reports.commons.bean.AdminOperateReport;
import cn.com.qmth.examcloud.reports.commons.util.ReportsUtil;
import cn.com.qmth.examcloud.web.support.ControllerSupport;
import io.swagger.annotations.ApiOperation;

/**
 * @author chenken
 * @date 2017年8月10日 下午3:31:42
 * @company QMTH
 * @description AudioTimeConfigController.java
 */
@Controller
@RequestMapping("${api_cqb}/")
public class AudioTimeConfigController extends ControllerSupport {
    @Autowired
    private ExtractConfigPaperCache extractConfigPaperCache;
    @Autowired
    private AudioTimeConfigService audioTimeConfigService;
    
    @Autowired
    private CourseCloudService courseCloudService;

    @ApiOperation(value = "根据examId查询音频设置 ", notes = "根据examId查询音频设置")
    @PostMapping(value = "/audioTimeConfig/{examId}/{courseCode}")
    public ResponseEntity<Object> findAudioTimeConfig(@PathVariable String examId, @PathVariable String courseCode) {
        List<AudioTimeConfig> audioTimeConfigs = audioTimeConfigService.findAudioTimeConfigByExamId(examId, courseCode);
        return new ResponseEntity<>(audioTimeConfigs, HttpStatus.OK);
    }

    @ApiOperation(value = "根据传入的对象查询音频题", notes = "根据传入的对象查询音频题")
    @PostMapping("/audioTimeConfig/all")
    public ResponseEntity<Object> findAudioTimeConfigList(@RequestBody List<AudioTimeConfig> audioTimeConfigModelList) {
        List<AudioTimeConfig> list = audioTimeConfigService.findAudioTimeConfigList(audioTimeConfigModelList);
        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    @ApiOperation(value = "根据传入的对象查询已经保存的音频题", notes = "根据传入的对象查询已经保存的音频题")
    @PostMapping("/audioTimeConfig/update")
    public ResponseEntity<Object> findUpdateList(@RequestBody List<AudioTimeConfig> audioTimeConfigModelList) {
        List<AudioTimeConfig> list = audioTimeConfigService.findUpdateAudioTimeConfigList(audioTimeConfigModelList);
        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    @ApiOperation(value = "新增音频播放次数", notes = "新增音频播放次数")
    @PostMapping("/addAudioTimeConfig")
    public ResponseEntity<Object> addAudioTimeConfig(@RequestBody List<AudioTimeConfig> audioTimeConfigList, @RequestParam String examId,@RequestParam String courseCode) {
        User user = getAccessUser();
        if (user != null) {
        	GetCourseReq req=new GetCourseReq();
        	req.setRootOrgId(user.getRootOrgId());
        	req.setCode(courseCode);
        	Long courseId=courseCloudService.getCourse(req).getCourseBean().getId();
        	boolean hasAudioChange=hasAudioChange(audioTimeConfigList, examId, courseCode);
            audioTimeConfigService.saveAudioTimeConfig(audioTimeConfigList, user);
            //清除缓存
            for(AudioTimeConfig ep:audioTimeConfigList) {
                Object[] keys=new Object[]{ep.getPaper().getId()};
                Object[] subkeys=new Object[]{Long.valueOf(ep.getExamId()), ep.getCourseCode(),ep.getGroupCode()};
                extractConfigPaperCache.refresh(keys,subkeys);
            }
            if(hasAudioChange) {
            	ReportsUtil.report(new AdminOperateReport(user.getRootOrgId(), user.getUserId(), AdminOperateType.TYPE22.getDesc(),"课程ID:"+courseId+" 考试ID:"+examId));
            }
            return new ResponseEntity<>(HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    
    private boolean hasAudioChange(List<AudioTimeConfig> audioTimeConfigs,String examId,String courseCode) {
    	List<AudioTimeConfig> old=audioTimeConfigService.findAudioTimeConfigByExamId(examId, courseCode);
    	if((old==null||old.size()==0)&&audioTimeConfigs != null&& audioTimeConfigs.size()!= 0) {
    		return true;
    	}
    	if((audioTimeConfigs==null||audioTimeConfigs.size()==0)&&old != null&& old.size()!= 0) {
    		return true;
    	}
    	if(old.size()!=audioTimeConfigs.size()) {
    		return true;
    	}
    	for(int i=0;i<audioTimeConfigs.size();i++) {
    		AudioTimeConfig nowc=audioTimeConfigs.get(i);
    		AudioTimeConfig oldc=old.get(i);
    		if(!nowc.getPaper().getId().equals(oldc.getPaper().getId())
    				||!nowc.getQuestionId().equals(oldc.getQuestionId())
    				||nowc.getPlayTime()!=oldc.getPlayTime()) {
    			return true;
    		}
    	}
    	return false;
    }

    @ApiOperation(value = "清理音频播放次数设置", notes = "清理音频播放次数设置")
    @PostMapping("/deleteAudioTimeConfig/{examId}/{courseCode}")
    public ResponseEntity<Object> deleteAudioTimeConfig(@PathVariable String examId, @PathVariable String courseCode) {
        User user = getAccessUser();
        if (user != null) {
            audioTimeConfigService.deleteByExamIdAndCourseCode(examId, courseCode);
            return new ResponseEntity<>(HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @ApiOperation(value = "根据examID，courseCode，groupCode，paperDetailUnit的ID查询音频次数", notes = "查询音频次数")
    @GetMapping("/seachAudioTimeConfig/{examId}/{courseCode}/{groupCode}/{paperDetailUnitId}")
    public ResponseEntity<Object> seachAudioTimeConfig(@PathVariable String examId,
                                                       @PathVariable String courseCode,
                                                       @PathVariable String groupCode,
                                                       @PathVariable String paperDetailUnitId) {
        Map<String, String> map = audioTimeConfigService.findAudioTimeConfig(examId, courseCode, groupCode, paperDetailUnitId);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }
}

