package com.dfyy.service;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dfyy.bussiness.Djz;
import com.dfyy.bussiness.DjzAdd;
import com.dfyy.bussiness.DjzAddUser;
import com.dfyy.bussiness.SUser;
import com.dfyy.dao.DjzAddDao;
import com.dfyy.dao.DjzAddUserDao;
import com.dfyy.dao.DjzDao;
import com.dfyy.dao.DjzDao2;
import com.dfyy.dao.SUserDao;

@Service
@Transactional
public class DjzAddService {

	@Autowired
	private DjzAddDao dao;

	@Autowired
	private DjzDao2 djzDao2;

	@Autowired
	private DjzDao djzDao;

	@Autowired
	private DjzAddUserDao djzAddUserDao;

	@Autowired
	private SUserDao suserDao;

	@Autowired
	private PointLogService logService;

	@Autowired
	private ActiveLogService activeLogService;

	public List<DjzAdd> getByPage(int page, Integer size) {
		List<DjzAdd> all = dao.getRecords(new PageRequest(page, size));
		return all;

	}

	public int allCount() {
		return dao.getCount();
	}

	public DjzAdd getById(int id) {
		DjzAdd all = dao.findOne(id);
		return all;
	}

	public void delete(Integer id) {
		DjzAdd disease = dao.findOne(id);
		disease.setStatus(-1);
		dao.save(disease);
	}

	public List<Djz> search(String context, int page, Integer size, String uid) {
		if (StringUtils.isNotBlank(context)) {
			Pattern pattern = Pattern.compile("[0-9]{5,}");
			Matcher matcher = pattern.matcher((CharSequence) context);
			boolean result = matcher.matches();

			List<Djz> all;
			if (result) {
				String year = context.substring(0, 4);
				String code = context.substring(4);

				all = djzDao2.search(context, year, code, page);
			} else {
				all = djzDao.search(context, new PageRequest(page, size));
			}

			if (all.size() == 0) {
				DjzAdd disease = dao.findByCode(context);
				if (disease != null) {
					disease.setNumber(disease.getNumber() + 1);
				} else {
					disease = new DjzAdd();
					disease.setName(context);
					disease.setNumber(1);
					disease.setStatus(0);
				}
				dao.save(disease);

				if (StringUtils.isNotBlank(uid)) {
					SUser user = suserDao.findOne(uid);
					DjzAddUser djzAddUser = djzAddUserDao.getRecord(context, uid);

					if (djzAddUser == null && user != null) {
						djzAddUser = new DjzAddUser();
						djzAddUser.setName(context);
						djzAddUser.setUser(user);
						djzAddUserDao.save(djzAddUser);
					}
				}
			}
			return all;
		}
		return null;
	}

	public int searchCount(String context) {
		return djzDao.searchCount(context);
	}

	public List<DjzAddUser> searchUsers(String context) {
		List<DjzAddUser> all = djzAddUserDao.getRecords(context);
		return all;
	}
}
