package com.uas.platform.b2b.mobile.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import com.uas.platform.b2b.dao.CommonDao;
import com.uas.platform.b2b.dao.OfficeTaskDao;
import com.uas.platform.b2b.dao.OfficeTaskReplyDao;
import com.uas.platform.b2b.dao.UserBaseInfoDao;
import com.uas.platform.b2b.mobile.enumeration.MobileStatus;
import com.uas.platform.b2b.mobile.model.AppFlowOperation;
import com.uas.platform.b2b.mobile.service.MobileTaskService;
import com.uas.platform.b2b.model.OfficeTask;
import com.uas.platform.b2b.model.OfficeTaskReply;
import com.uas.platform.b2b.temporary.model.OfficeTaskInfo;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.model.PageParams;

@Service
public class MobileTaskServiceImpl implements MobileTaskService {

	@Autowired
	private UserBaseInfoDao userBaseInfoDao;

	@Autowired
	private OfficeTaskDao officeTaskDao;

	@Autowired
	private OfficeTaskReplyDao officeTaskReplyDao;

	@Autowired
	private CommonDao commonDao;

	@Override
	public ModelMap saveTask(OfficeTaskInfo task) {
		ModelMap map = new ModelMap();
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMddss");
		task.setCode(sdf.format(new Date()));
		task.setRecorddate(new Date());
		task.setStatus(MobileStatus.start.getPhrase());
		task.setStatuscode(MobileStatus.start.name());
		task.setRecorder(userBaseInfoDao.findByUserUU(task.getRecordercode()).getUserName());
		String[] emcodes = task.getDomancode().split(",");
		for (String emcode : emcodes) {
			OfficeTask ta = new OfficeTask(task);
			ta.setDomancode(Long.valueOf(emcode));
			ta.setDoman(userBaseInfoDao.findByUserUU(Long.valueOf(emcode)).getUserName());
			ta = officeTaskDao.save(ta);
			if (ta.getId() != null) {
				map.put("success", true);
			} else {
				map.put("success", false);
			}
		}
		return map;
	}

	@Override
	public ModelMap getAllTasks(Long emuu, Long enuu, Integer pageNumber, Integer pageSize, String status) {
		ModelMap map = new ModelMap();
		PageParams params = new PageParams();
		params.setCount(pageSize);
		params.setPage(pageNumber);
		final PageInfo pageInfo = new PageInfo(params);
		pageInfo.filter("uu", enuu);
		pageInfo.filter("domancode", emuu);
		pageInfo.filter("status", status);
		Page<OfficeTask> officeTask = officeTaskDao.findAll(new Specification<OfficeTask>() {
			@Override
            public Predicate toPredicate(Root<OfficeTask> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
				return query.where(pageInfo.getPredicates(root, query, builder)).getRestriction();
			}
		}, pageInfo);
		map.put("listdata", officeTask.getContent());
		return map;
	}

	@Override
	public ModelMap getTaskReply(Long id) {
		ModelMap map = new ModelMap();
		map.put("listdata", officeTaskReplyDao.findByTaskid(id));
		return map;
	}

	@Override
	public ModelMap changeTaskStaus(OfficeTask task, OfficeTaskReply taskreply) {
		ModelMap map = new ModelMap();
		OfficeTask offtask = officeTaskDao.findOne(task.getId());
		offtask.setStatus(task.getStatus());
		offtask.setStatuscode(task.getStatuscode());
		officeTaskDao.save(offtask);
		taskreply = officeTaskReplyDao.save(taskreply);
		if (taskreply.getId() != null) {
			map.put("success", true);
		}
		return map;
	}

	@Override
	public ModelMap getTaskCounts(Long emcode, Long enuu) {
		ModelMap map = new ModelMap();
		String doing = "select count(*) from office$task where ta_domancode = " + emcode + " and ta_uu =" + enuu
				+ " and ta_statuscode = 'start'";
		String todo = "select count(*) from mobile$flowoperation where fop_nodedealuu = " + emcode
				+ " and fop_nodeenuu =" + enuu + " and fop_statuscode = 'UNAUDIT'";
		Integer processcount = commonDao.queryForObject(todo, Integer.class);
		Integer taskcount = commonDao.queryForObject(doing, Integer.class);
		List<OfficeTask> lasttask = commonDao.query(
				"select t.ta_taskname taskname, t.ta_startdate startdate from office$task t where t.ta_statuscode = 'start' and t.ta_domancode = '"
						+ emcode + "' and t.ta_uu = " + enuu + " order by t.ta_id desc limit 1",
				OfficeTask.class);
		List<AppFlowOperation> nowProcess = commonDao.query(
				"select t.fop_caller caller, t.fop_dealname dealname, t.fop_dealtime dealtime,t.fop_nodelevel nodelevel,t.fop_sourceid sourceid from mobile$flowoperation t where t.fop_statuscode = 'UNAUDIT' and t.fop_nodedealuu = "
						+ emcode + " and t.fop_nodeenuu = " + enuu + " order by t.fop_id desc limit 1",
				AppFlowOperation.class);
		if (!CollectionUtils.isEmpty(nowProcess)) {
			List<AppFlowOperation> lastProcess = commonDao
					.query("select * from( select t.fop_caller caller, t.fop_dealname dealname, t.fop_dealtime dealtime from mobile$flowoperation t where t.fop_nodeenuu = "
							+ enuu + " and t.fop_nodelevel = " + (nowProcess.get(0).getNodelevel() - 1)
							+ " and t.fop_sourceid = " + nowProcess.get(0).getSourceid() + ") a", AppFlowOperation.class);
			if (!CollectionUtils.isEmpty(lastProcess)) {
				map.put("lastProcessTime", lastProcess.get(0).getDealtime());
				if (nowProcess.get(0).getDealname() != null) {
					map.put("lastProcess", nowProcess.get(0).getDealname() + "的" + nowProcess.get(0).getCaller());
				} else {
					map.put("lastProcess", nowProcess.get(0).getCaller());
				}
			} else {
				map.put("lastProcessTime", null);
				map.put("lastProcess", null);
			}
		} else {
			map.put("lastProcessTime", null);
			map.put("lastProcess", null);
		}
		map.put("processcount", processcount);
		map.put("taskcount", taskcount);
		if (!CollectionUtils.isEmpty(lasttask)) {
			map.put("lasttask", lasttask.get(0).getTaskname());
			map.put("lasttaskTime", lasttask.get(0).getStartdate());
		} else {
			map.put("lasttask", null);
			map.put("lasttaskTime", null);
		}
		return map;
	}

	@Override
	public ModelMap getMyTasks(Long emuu, Long enuu, Integer pageNumber, Integer pageSize) {
		ModelMap map = new ModelMap();
		PageParams params = new PageParams();
		params.setCount(pageSize);
		params.setPage(pageNumber);
		final PageInfo pageInfo = new PageInfo(params);
		pageInfo.filter("uu", enuu);
		pageInfo.filter("recordercode", emuu);
		Page<OfficeTask> officeTask = officeTaskDao.findAll(new Specification<OfficeTask>() {
			@Override
            public Predicate toPredicate(Root<OfficeTask> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
				return query.where(pageInfo.getPredicates(root, query, builder)).getRestriction();
			}
		}, pageInfo);
		map.put("listdata", officeTask.getContent());
		return map;
	}
}
