package cn.tsy.idsse.dsds.control.sar;

import java.io.File;
import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.hme.framework.helper.date.LocalDateHelper;
import cn.hme.framework.helper.file.FileHelper;
import cn.hme.framework.jdbc.provider.builder.DirectionEnum;
import cn.hme.framework.jdbc.provider.page.OrderBy;
import cn.hme.framework.web.control.Ajax;
import cn.hme.framework.web.helper.FrameAssertHelper;
import cn.hme.framework.web.helper.WebHelper;
import cn.tsy.data.idsse.dsds.mapper.sar.SarFileMapper;
import cn.tsy.data.idsse.dsds.mapper.sar.SarRegMapper;
import cn.tsy.data.idsse.dsds.model.sar.SarFile;
import cn.tsy.data.idsse.dsds.model.sar.SarReg;
import cn.tsy.idsse.dsds.control.DSDSControl;
import cn.tsy.idsse.dsds.helper.DSDSParamHelper;
import cn.tsy.idsse.dsds.service.sar.SarRegService;

@RestController
@RequestMapping("sar/file")
@CrossOrigin
public class SarFileControl extends DSDSControl {

	@Autowired
	private SarRegMapper mSar;
	@Autowired
	private SarFileMapper mFile;

	@Autowired
	private SarRegService sSar;

	@RequestMapping("list.htm")
	public Ajax list(int sar_id) {
		return new Ajax(this.mFile.selectListByColumnAndSimpleOrder("sar_id", sar_id, OrderBy.of("upload_time", DirectionEnum.DESC)));
	}

	@RequestMapping("delete.htm")
	public Ajax delete(int tsy_id) {
		this.mFile.deleteByKey(tsy_id);
		return new Ajax();
	}
	
	@RequestMapping("edit.htm")
	public Ajax edit(int tsy_id,String file_remark) {
		SarFile f =new SarFile();
		f.setTsy_id(tsy_id);
		f.setFile_remark(file_remark);
		this.mFile.update(f);
		return new Ajax();
	}


	@CrossOrigin
	@RequestMapping("upload.htm")
	public Ajax upload(int sar_id,String file_remark, MultipartFile file) {
		SarReg sar = this.mSar.find(sar_id);
		FrameAssertHelper.isNotNull(sar, "未找到指定的任务！");
		String path = LocalDateHelper.replace(DSDSParamHelper.SarFileRoot + sar.getSar_name());
		new File(path).mkdirs();
		File f = new File(path + File.separator + sar.getSar_name() + "_" + LocalDateHelper.formatLongNoSplit(LocalDateTime.now()) + "_" + file.getOriginalFilename());
		FileHelper.fromUpload(file, f);
		this.sSar.updateFile(sar,file.getOriginalFilename(),file_remark, f, getFrameOptr());
		return new Ajax();
	}
	
	@RequestMapping("download.htm")
	public void download(int tsy_id) {
		SarFile file = this.mFile.find(tsy_id);
		File f = new File(file.getFile_path());
		if(!f.exists()) {
			WebHelper.writeAlert("文件已被清理，请联系管理人员！");
			return ;
		}
		WebHelper.downloadFile(f, file.getFile_name());
	}

}
