/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package web.operator;
import domain.Client;
import domain.Collaborator;
import domain.Lpu;
import domain.address.Address;
import domain.address.AddressObject;
import domain.editors.Editor;
import domain.shedule.WorkType;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import utils.Converter;
import utils.DateTimeUtils;
import web.generic.GenericCommandController;
import web.operator.request.ClientData;
/**
* Контроллер поиска пациента для записи на прием оператором:
* либо для первоначального поиска,
* либо для поиска при непосредственной записи на прием
* Параметры:
* lpu - ID ЛПУ
* collaborator - ID врача к которому идет запись
* type - ID типа приема записи
* time - время записи
* @author vip
*/
public class SelectClientController extends GenericCommandController {
protected static final Logger log = Logger.getLogger(SelectClientController.class);
public SelectClientController() {
setCommandClass(SelectClientDTO.class);
}
@Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Client.class, new Editor(getDao(), Client.class));
binder.registerCustomEditor(Collaborator.class, new Editor(getDao(), Collaborator.class));
binder.registerCustomEditor(WorkType.class, new Editor(getDao(), WorkType.class));
binder.registerCustomEditor(Lpu.class, new Editor(getDao(), Lpu.class));
}
private static String growFirst(String text){
String res = null;
if (text != null){
res = "";
if(!text.isEmpty()){
res = text.substring(0, 1).toUpperCase();
if (text.length() > 1){
res += text.substring(1).toLowerCase();
}
}
}
return res;
}
@Override
protected ModelAndView handle(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors) throws Exception {
SelectClientDTO dto = (SelectClientDTO) command;
HashMap model = new HashMap();
model.put("command", dto);
//инициализация полей, если клиент уже задан
Client predefClients = dto.getClient();
if (predefClients != null) {
dto.setName(predefClients.getName().getTitle().trim());
dto.setSurname(predefClients.getSurname().getTitle().trim());
dto.setPatron(predefClients.getPatronymic() == null ? "" : predefClients.getPatronymic().getTitle().trim());
}
boolean canWork = false;
DetachedCriteria queryCriteria = DetachedCriteria.forClass(Client.class).setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
//ФИО
if (dto.getSurname() != null && !dto.getSurname().isEmpty()
|| dto.getName() != null && !dto.getName().isEmpty()
|| dto.getPatron() != null && !dto.getPatron().isEmpty()) {
canWork = true;
if (dto.getSurname() != null && !dto.getSurname().isEmpty()) {
queryCriteria.createCriteria("surname").add(
Property.forName("title").like(growFirst(dto.getSurname()) + "%"));
}
if (dto.getName() != null && !dto.getName().isEmpty()) {
queryCriteria.createCriteria("name").add(
Property.forName("title").like(growFirst(dto.getName()) + "%"));
}
if (dto.getPatron() != null && !dto.getPatron().isEmpty()) {
queryCriteria.createCriteria("patronymic").add(
Property.forName("title").like(growFirst(dto.getPatron()) + "%"));
}
DetachedCriteria criteria = DetachedCriteria.forClass(Client.class);
criteria.createCriteria("surname").add(Property.forName("title").like(dto.getSurname()+"%"));
List list = getDao().getList(criteria, 0, 1000);
log.debug("TEST");
}
//Год рождения
if (dto.getBirthYear() != null && !dto.getBirthYear().isEmpty()) {
try {
int year = Integer.parseInt(dto.getBirthYear());
GregorianCalendar gc = new GregorianCalendar(year, 0, 1);
Date thisYear = gc.getTime();
gc.add(GregorianCalendar.YEAR, 1);
Date nextYear = gc.getTime();
queryCriteria.add(Property.forName("born").ge(thisYear));
queryCriteria.add(Property.forName("born").lt(nextYear));
canWork = true;
} catch (NumberFormatException ex) {
//DO NOTHING
}
}
//Телефон
if (dto.getTelephone() != null && !dto.getTelephone().isEmpty()) {
queryCriteria.add(
Property.forName("telephones").like("%" + dto.getTelephone() + "%"));
canWork = true;
}
//Полис
if (dto.getPolis() != null && !dto.getPolis().isEmpty()) {
queryCriteria.createCriteria("polisCollection").add(
Property.forName("number").like("%" + dto.getPolis() + "%"));
}
//Адресная часть
if (dto.getCity() != null && !dto.getCity().isEmpty()
|| dto.getStreet() != null && !dto.getStreet().isEmpty()
|| dto.getHouse() != null && !dto.getHouse().isEmpty()
|| dto.getFlat() != null && !dto.getFlat().isEmpty()) {
canWork = true;
String like = "";
if (dto.getCity() != null && !dto.getCity().isEmpty()) {
like += "%" + "нас. " + dto.getCity();
}
if (dto.getStreet() != null && !dto.getStreet().isEmpty()) {
like += "%" + "ул. " + dto.getStreet();
}
if (dto.getHouse() != null && !dto.getHouse().isEmpty()) {
like += "%" + "д. " + dto.getHouse();
}
if (dto.getFlat() != null && !dto.getFlat().isEmpty()) {
like += "%" + "кв. " + dto.getFlat();
}
like += "%";
queryCriteria.add(Property.forName("addressCashe").like(like));
}
Date current = GregorianCalendar.getInstance().getTime();
if (canWork) {
List<Client> clients = getDao().getList(queryCriteria, 0, 51);
List<ClientLine> lines = new ArrayList<ClientLine>();
for (Client client : clients) {
Address address = null;
if (client.getAddressID() != null) {
address = getDao().getById(Address.class, client.getAddressID());
}
if (address != null && dto.getHouse() != null && !dto.getHouse().isEmpty()) {
if (address.getBuilding() == null || !address.getBuilding().equals(dto.getHouse())) {
continue;
}
}
if (address != null && dto.getFlat() != null && !dto.getFlat().isEmpty()) {
if (address.getFlat() == null || !address.getFlat().equals(dto.getFlat())) {
continue;
}
}
if (address != null && dto.getCity() != null && !dto.getCity().isEmpty()) {
//Фильтруем по району/нас пункту
AddressObject item = address.getAddressObject();
boolean founded = false;
while (item != null) {
if ((item.getType().getLevel() == 3 || item.getType().getLevel() == 4)
&& item.getTitle().toUpperCase().startsWith(dto.getCity().toUpperCase())) {
founded = true;
}
item = item.getParent();
}
if (!founded) {
continue;
}
}
if (address != null && dto.getStreet() != null && !dto.getStreet().isEmpty()) {
//Фильтруем по улице
AddressObject item = address.getAddressObject();
boolean founded = false;
while (item != null) {
if (item.getType().getLevel() == 5
&& item.getTitle().toUpperCase().startsWith(dto.getStreet().toUpperCase())) {
founded = true;
}
item = item.getParent();
}
if (!founded) {
continue;
}
}
ClientLine cl = new ClientLine();
cl.client = client;
cl.date = Converter.dateToString(client.getBorn());
if (client.getBorn() != null) {
cl.age = Integer.toString(DateTimeUtils.calcAge(client.getBorn(), current));
} else {
cl.age = "";
}
cl.addressStr = address == null ? "" : address.getAsStringShort();
cl.lpu = client.getDistrict() == null ? "" : client.getDistrict().getLpu().getTitleShort();
lines.add(cl);
}
model.put("lines", lines);
model.put("linescount", lines.size());
} else {
List<ClientLine> lines = new ArrayList<ClientLine>();
model.put("lines", lines);
model.put("linescount", 51);
}
model.put("pageBreadcrumb", ReceptionController.initBreadCrumb(dto.getClient(),
dto.getType(),
dto.getLpu(),
dto.getCollaborator(),
dto.getTime()));
if (dto.getCollaborator() != null) {
return new ModelAndView("operator/chooseclient", model);
} else {
return new ModelAndView("operator/selectclient", model);
}
}
}