/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workdailyroutine.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workdailyroutine.entity.WorkDailyRoutineDetail;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.workdailyroutine.entity.WorkDailyRoutine;
import com.jeeplus.modules.workdailyroutine.dao.WorkDailyRoutineDao;

/**
 * 日常事务Service
 * @author ssrh
 * @version 2018-07-11
 */
@Service
@Transactional(readOnly = true)
public class WorkDailyRoutineService extends CrudService<WorkDailyRoutineDao, WorkDailyRoutine> {
    @Autowired
    private WorkDailyRoutineDetailService routineDetailService;
    @Autowired
    private WorkClientAttachmentDao workClientAttachmentDao;
    @Autowired
    private WorkProjectNotifyService workProjectNotifyService;

	public WorkDailyRoutine get(String id) {
        WorkDailyRoutine workDailyRoutine = super.get(id);
        queryDetails(workDailyRoutine);
        return workDailyRoutine;
	}

    public void queryDetails(WorkDailyRoutine workDailyRoutine) {
        if(workDailyRoutine!=null&& StringUtils.isNotBlank(workDailyRoutine.getId())){
            WorkClientAttachment attachment = new WorkClientAttachment();
            attachment.setAttachmentId(workDailyRoutine.getId());
            workDailyRoutine.setWorkAttachments(workClientAttachmentDao.findList(attachment));
            WorkDailyRoutineDetail routineDetail = new WorkDailyRoutineDetail();
            routineDetail.setWorkDailyRoutine(workDailyRoutine);
            workDailyRoutine.setDetailList(routineDetailService.findList(routineDetail));
        }
    }

    public List<WorkDailyRoutine> findList(WorkDailyRoutine workDailyRoutine) {
        if(!UserUtils.getUser().isAdmin()) {
            String dataScopeSql = dataScopeFilter(workDailyRoutine.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_DAILYROUTINE.getValue());
            workDailyRoutine.getSqlMap().put("dsf", dataScopeSql);
        }
		return super.findList(workDailyRoutine);
	}
	
	public Page<WorkDailyRoutine> findPage(Page<WorkDailyRoutine> page, WorkDailyRoutine workDailyRoutine) {
        if(!UserUtils.getUser().isAdmin()) {
            String dataScopeSql = dataScopeFilter(workDailyRoutine.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_DAILYROUTINE.getValue());
            workDailyRoutine.getSqlMap().put("dsf", dataScopeSql);
        }
		return super.findPage(page, workDailyRoutine);
	}
	
	@Transactional(readOnly = false)
	public void save(WorkDailyRoutine workDailyRoutine) {
	    if(workDailyRoutine.getOffice()==null){
	        workDailyRoutine.setOffice(UserUtils.getSelectOffice());
        }
        if(workDailyRoutine.getCompany()==null){
	        workDailyRoutine.setCompany(UserUtils.getSelectCompany());
        }
		super.save(workDailyRoutine);
        this.saveAttachments(workDailyRoutine);
        List<User> userList = this.saveDetail(workDailyRoutine);
        if (userList==null||userList.size()<=0){
            return;
        }
        String contentStr = "创建人："+workDailyRoutine.getCreateBy().getName()+"，事务来源："+ workDailyRoutine.getSource()+"，创建时间："+DateUtils.formatDate(workDailyRoutine.getCreateDate());
        String titleStr = "事务名称："+ workDailyRoutine.getName();
        String remark = "待处理";
        this.sendMessage(workDailyRoutine,userList,"58",contentStr,titleStr,remark);
	}

    private void sendMessage(WorkDailyRoutine workDailyRoutine, List<User> userList, String type,String contentStr, String titleStr, String remark) {
        WorkProjectNotify workProjectNotify = UtilNotify.saveNotify(workDailyRoutine.getId(),null, workDailyRoutine.getCompany().getId(),
                titleStr, contentStr,type,"0",remark,"");
        List<String> userIds = new ArrayList<>(userList.size());
        for (User u : userList){
            userIds.add(u.getId());
            workProjectNotify.setUser(u);
            workProjectNotify.setId("");
            workProjectNotify.setNotifyRole("");
            workProjectNotify.setCreateBy(u);
            workProjectNotify.setUpdateBy(u);
            workProjectNotifyService .save(workProjectNotify);
        }
        UserUtils.pushIm(userIds,contentStr);
    }

    private List<User> saveDetail(WorkDailyRoutine workDailyRoutine) {
        if(workDailyRoutine==null||workDailyRoutine.getDetailList()==null){
            return null;
        }
        List<User> userList = new ArrayList<>();
        for (WorkDailyRoutineDetail routineDetail : workDailyRoutine.getDetailList()) {
            routineDetail.setWorkDailyRoutine(workDailyRoutine);
            routineDetail.setOffice(UserUtils.get(routineDetail.getOperator().getId()).getOffice());
            routineDetail.setStatus("未完成");
            routineDetailService.save(routineDetail);
            userList.add(routineDetail.getOperator());
        }
        return userList;
    }

    private void saveAttachments(WorkDailyRoutine workDailyRoutine) {
	    if(workDailyRoutine==null||workDailyRoutine.getWorkAttachments()== null){
	        return;
        }
        for (WorkClientAttachment workClientAttachment : workDailyRoutine.getWorkAttachments()) {
            if (workClientAttachment.getId() == null) {
                continue;
            }
            if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
                workClientAttachment.setAttachmentId(workDailyRoutine.getId());
                workClientAttachment.setAttachmentFlag(WorkDailyRoutine.ATTACHMENT_TYPE);
                workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
                if (StringUtils.isBlank(workClientAttachment.getId()) || "null".equals(workClientAttachment.getId())) {
                    workClientAttachment.preInsert();
                    workClientAttachmentDao.insert(workClientAttachment);
                } else {
                    workClientAttachment.preUpdate();
                    workClientAttachmentDao.update(workClientAttachment);
                }
            } else {
                workClientAttachmentDao.delete(workClientAttachment);
            }
        }
    }

    @Transactional(readOnly = false)
	public void delete(WorkDailyRoutine workDailyRoutine) {
		super.delete(workDailyRoutine);
	}

    @Transactional(readOnly = false)
    public void close(String id) {
        WorkDailyRoutine workDailyRoutine = new WorkDailyRoutine();
        workDailyRoutine.setStatus("已关闭");
        workDailyRoutine.setId(id);
        dao.updateStatusById(workDailyRoutine);
        WorkProjectNotify workProjectNotify = new WorkProjectNotify();
        workProjectNotify.setNotifyId(workDailyRoutine.getId());
        workProjectNotifyService.readByNotifyId(workProjectNotify);
    }

    @Transactional(readOnly = false)
    public void save(WorkDailyRoutineDetail workDailyRoutineDetail) {
        workDailyRoutineDetail.setStatus("已完成");
        if(workDailyRoutineDetail.getCreateDate()==null) {
            workDailyRoutineDetail.setUpdateDate(new Date());
        }
        routineDetailService.save(workDailyRoutineDetail);
        WorkDailyRoutine workDailyRoutine = dao.get(workDailyRoutineDetail.getWorkDailyRoutine().getId());
        if("已关闭".equals(workDailyRoutine.getStatus())||"已完成".equals(workDailyRoutine.getStatus())){
            return;
        }
        WorkDailyRoutineDetail select = new WorkDailyRoutineDetail();
        select.setWorkDailyRoutine(workDailyRoutine);
        select.setStatus("未完成");
        Integer count = routineDetailService.countUndone(select);
        if(count==null||count==0){
            workDailyRoutine.setStatus("已完成");
            dao.updateStatusById(workDailyRoutine);
        }
        WorkProjectNotify workProjectNotify = new WorkProjectNotify();
        workProjectNotify.setNotifyId(workDailyRoutine.getId());
        workProjectNotify.setUser(workDailyRoutineDetail.getOperator());
        workProjectNotifyService.readByNotifyIdAndNotifyUser(workProjectNotify);
        String contentStr = "事务来源："+workDailyRoutine.getSource()+"，执行人："+workDailyRoutineDetail.getOperator().getName()+"，完成日期："+ DateUtils.formatDate(workDailyRoutineDetail.getUpdateDate());
        String titleStr = "事务名称："+ workDailyRoutine.getName();
        String remark = "待通知";
        List<User> userList = new ArrayList<>();
        userList.add(workDailyRoutine.getCreateBy());
        this.sendMessage(workDailyRoutine,userList,"58",contentStr,titleStr,remark);
    }

    public List<WorkDailyRoutine> findBySourceId(String sourceId) {
	    return dao.findBySourceId(sourceId);
    }
}