package cn.hmsoft.skill.school.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.hmsoft.frame.constants.FrameThreadCallbackType;
import cn.hmsoft.frame.constants.FrameThreadStatus;
import cn.hmsoft.frame.data.model.FrameOptr;
import cn.hmsoft.frame.data.model.FrameThread;
import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.frame.thread.FrameThreadHelper;
import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.skill.constants.StdLogType;
import cn.hmsoft.skill.data.dao.school.AreaRecruitDao;
import cn.hmsoft.skill.data.model.school.AreaRecruit;
import cn.hmsoft.skill.service.SkillService;

@Service
public class SchoolAreaRecruitService extends SkillService {

	@Autowired
	private AreaRecruitDao areaRecruitDao;
	
	/**
	 * 导入市州招生数据
	 * @param thread
	 * @param values
	 * @param frameOptr
	 */
	public void batchRecruit(FrameThread thread, List<List<String>> values, FrameOptr frameOptr) {
		int total = 0;
		int row = 2;
		for (List<String> list : values) {
			
			String year = list.get(0).trim() == null ? null : list.get(0).trim(); //年份
			String area = list.get(1).trim() == null ? null : list.get(1).trim(); //市州
			String recruit_num = list.get(2).trim() == null ? null : list.get(2).trim(); //招生任务数

			if (StringHelper.isEmpty(year)) {
				uploadError(thread, "第【" + row + "】行，年份不能为空");
			}
			if (StringHelper.isEmpty(area))
				uploadError(thread, "第【" + row + "】行，市州不能为空");
			if (StringHelper.isEmpty(recruit_num))
				uploadError(thread, "第【" + row + "】行，招生任务数不能为空");

			// 判断对应年份数据是否导入数据库
			AreaRecruit areaRecruit = this.areaRecruitDao.findByYear(year);
			if (areaRecruit != null) {
				uploadError(thread, "【" + year + "】年的市州招生数据已经导入数据库，不能重复导入市州招生数据！");
			} else {
				areaRecruit = new AreaRecruit();				
				areaRecruit.setYear(year);
				areaRecruit.setArea(area);
				areaRecruit.setRecruit_num(Integer.valueOf(recruit_num));
				try {
					this.areaRecruitDao.insert(areaRecruit);
				} catch (Exception e) {
					e.printStackTrace();
					uploadError(thread, "第【" + row + "】行，文字信息过长，请缩减后重新上传！");
				}
			}
			
			total++;
			row++;
			if (total % 2 == 0) {
				// 每100条记录下
				FrameThreadHelper.updateThread(thread, total * 2 / values.size(),
						"已处理【" + total + "】条市州招生任务数据，一共需要处理【" + values.size() + "】条记录");
			}

		}
		FrameThreadHelper.completeThread(thread, "导入成功：已处理【" + total + "】条市州招生任务数据");
		this.log(frameOptr, StdLogType.BatchReg.toString(), values.size());
	}


	
	private void uploadError(FrameThread thread, String value) {
		FrameThreadHelper.completeThread(thread, "出现业务错误，导入失败！", FrameThreadCallbackType.Swal, value,
				FrameThreadStatus.Error);
		throw new BusinessException(value);
	}
}
