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

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

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

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.ApprovalFlowDao;
import com.uas.platform.b2b.dao.UserBaseInfoDao;
import com.uas.platform.b2b.mobile.dao.AppFlowOperationDao;
import com.uas.platform.b2b.mobile.dao.ApprovalLogDao;
import com.uas.platform.b2b.mobile.dao.WorkDailyDao;
import com.uas.platform.b2b.mobile.enumeration.MobileStatus;
import com.uas.platform.b2b.mobile.model.AppFlowOperation;
import com.uas.platform.b2b.mobile.model.AppLog;
import com.uas.platform.b2b.mobile.model.ApprovalLog;
import com.uas.platform.b2b.mobile.model.WorkDaily;
import com.uas.platform.b2b.mobile.service.WorkDailyService;
import com.uas.platform.b2b.model.ApprovalFlow;
import com.uas.platform.b2b.model.FlowNode;
import com.uas.platform.b2b.service.ApprovalFlowService;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.model.PageParams;

@Service
public class WorkDailyServiceImpl implements WorkDailyService {

	@Autowired
	private WorkDailyDao workDailyDao;

	@Autowired
	private ApprovalFlowService approvalFlowService;

	@Autowired
	private ApprovalLogDao approvalLogDao;

	@Autowired
	private AppFlowOperationDao appFlowOperationDao;

	@Autowired
	private UserBaseInfoDao userBaseInfoDao;

	@Autowired
	private ApprovalFlowDao approvalFlowDao;

	@Override
	public ModelMap saveWorkDaily(WorkDaily workDaily) {
		ModelMap map = new ModelMap();
		WorkDaily daily = new WorkDaily();
		if (workDaily.getWd_id() == null) {// 新增单据
			workDaily.setWd_date(new Date());
			workDaily.setOrderdate(new Date());
			workDaily.setWd_status(MobileStatus.ENTERING.getPhrase());
			workDaily.setWd_statuscode(MobileStatus.ENTERING.name());
			SimpleDateFormat sdf = new SimpleDateFormat("yyMMHHss");
			workDaily.setWd_code("WD" + sdf.format(new Date()));
			workDaily.setWd_emp(userBaseInfoDao.findByUserUU(workDaily.getEmcode()).getUserName());
			daily = workDailyDao.save(workDaily);
		} else {// 重新提交和更新单据
			daily = workDailyDao.findOne(workDaily.getWd_id());
			daily.setWd_status(MobileStatus.ENTERING.getPhrase());
			daily.setWd_statuscode(MobileStatus.ENTERING.name());
			daily.setWd_date(new Date());
			daily.setOrderdate(new Date());
			daily.setWd_comment(workDaily.getWd_comment());
			daily.setWd_plan(workDaily.getWd_plan());
			daily.setWd_experience(workDaily.getWd_experience());
			daily.setWd_emp(userBaseInfoDao.findByUserUU(workDaily.getEmcode()).getUserName());
			daily = workDailyDao.save(daily);
		}
		map.put("data", daily);
		// 审批流
		// TODO 暂时这里先只做人员的线路
		String appName = MobileStatus.WORKDAILY.getPhrase();
		ApprovalFlow flow = approvalFlowDao.findByEnuuAndAppname(daily.getEnuu(), appName);
		FlowNode node = approvalFlowService.getNodeInfoByEnuuAndEmcodeAndAppName(daily.getEnuu(), daily.getEmcode(),
				appName);
		Integer nodelevel = -1;
		if (node != null) {
			nodelevel = node.getNodelev();
		}
		Integer maxNode = approvalFlowService.getMaxNodeByEnuuAndAppName(daily.getEnuu(), appName);
		if (flow != null) { // 该企业的该单据的审批流存在
			if (nodelevel < maxNode) {
				AppLog log = new AppLog();
				log.setStatus(MobileStatus.ENTERING.getPhrase());
				log.setStatusCode(MobileStatus.ENTERING.name());
				log.setSourceid(daily.getWd_id());
				log.setSourcedate(new Date());
				log.setKeyvalue(daily.getWd_id());
				log.setCaller(appName);
				log.setEmcode(daily.getEmcode());
				log.setEnuu(daily.getEnuu());
				for (int i = nodelevel + 1; i <= maxNode; i++) {
					ApprovalLog applog = new ApprovalLog(log);
					applog.setNodedealman(approvalFlowService
							.getNodeInfoByEnuuAndAppNameAndNodelev(daily.getEnuu(), appName, i).getEmcode());
					applog.setNodename(approvalFlowService
							.getNodeInfoByEnuuAndAppNameAndNodelev(daily.getEnuu(), appName, i).getNodename());
					applog.setProcessid(approvalFlowService
							.getNodeInfoByEnuuAndAppNameAndNodelev(daily.getEnuu(), appName, i).getId());
					applog = approvalLogDao.save(applog);
					node = approvalFlowService.getNodeInfoByEnuuAndAppNameAndNodelev(daily.getEnuu(), appName,
							nodelevel + 1);
					if (applog.getId() != null) {
						// 新增待审批
						if (applog.getNodedealman()
								.equals(approvalFlowService
									.getNodeInfoByEnuuAndAppNameAndNodelev(daily.getEnuu(), appName, nodelevel + 1)
										.getEmcode())) {
							AppFlowOperation operation = new AppFlowOperation();
							operation.setCaller(appName);
							operation.setDealname(daily.getWd_emp());
							operation.setDealuu(daily.getEmcode());
							operation.setKeyvalue(applog.getId());
							operation.setNodedealname(node.getEmname());
							operation.setRecorddate(new Date());
							operation.setStatus(MobileStatus.UNAUDIT.getPhrase());
							operation.setStatuscode(MobileStatus.UNAUDIT.name());
							operation.setEnuu(daily.getEnuu());
							operation.setNodedealuu(node.getEmcode());
							operation.setNodelevel(node.getNodelev());
							operation.setSourceid(daily.getWd_id());
							operation = appFlowOperationDao.save(operation);
							if (operation.getId() != null) {
								daily = workDailyDao.findOne(daily.getWd_id());
								daily.setWd_status(MobileStatus.COMMITED.getPhrase());
								daily.setWd_statuscode(MobileStatus.COMMITED.name());
								workDailyDao.save(daily);
								map.put("success", true);
							} else {
								map.put("success", false);
							}
						}
					}

				}
			}
			if (Objects.equals(nodelevel, maxNode)) {
				daily = workDailyDao.findOne(daily.getWd_id());
				daily.setWd_status(MobileStatus.AUDITED.getPhrase());
				daily.setWd_statuscode(MobileStatus.AUDITED.name());
				workDailyDao.save(daily);
			}
		}
		return map;
	}

	@Override
	public ModelMap getWorkDaily(Long emcode, Integer pageNumber, Integer pageSize, Long enuu) {
		ModelMap map = new ModelMap();
		PageParams params = new PageParams();
		params.setCount(pageSize);
		params.setPage(pageNumber);
		String sorting = "{\"orderdate\":\"desc\"}";
		params.setSorting(sorting);
		final PageInfo pageInfo = new PageInfo(params);
		pageInfo.filter("enuu", enuu);
		pageInfo.filter("emcode", emcode);
		Page<WorkDaily> workDaily = workDailyDao.findAll(new Specification<WorkDaily>() {
			@Override
            public Predicate toPredicate(Root<WorkDaily> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
				return query.where(pageInfo.getPredicates(root, query, builder)).getRestriction();
			}
		}, pageInfo);
		map.put("data", workDaily.getContent());
		return map;
	}

	@Override
	public ModelMap deleteById(Long id) {
		ModelMap map = new ModelMap();
		WorkDaily oldDaily = workDailyDao.findOne(id);
		if (null == oldDaily) {
			map.put("data", "日报不存在，可能已被删除");
			map.put("success", false);
		} else {
			workDailyDao.delete(id);
			map.put("success", true);
		}
		return map;
	}

	@Override
	public WorkDaily getById(Long id) {
		return workDailyDao.findOne(id);
	}

}
