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

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.mapper.JsonMapper;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.sys.dao.AreaDao;
import com.jeeplus.modules.sys.dao.RoleDao;
import com.jeeplus.modules.sys.entity.Area;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workclientinfo.dao.WorkClientLinkmanDao;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workclientinfo.entity.WorkClientLinkman;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workcontractinfo.dao.WorkContractAnnexDao;
import com.jeeplus.modules.workcontractinfo.dao.WorkContractInfoDao;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workfullexecute.dao.WorkFullExecuteDao;
import com.jeeplus.modules.workfullexecute.entity.WorkFullExecute;
import com.jeeplus.modules.workfullmanage.dao.WorkFullConstructDao;
import com.jeeplus.modules.workfullmanage.dao.WorkFullDesignDao;
import com.jeeplus.modules.workfullmanage.dao.WorkFullManageDao;
import com.jeeplus.modules.workfullmanage.dao.WorkFullSurveyDao;
import com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.modules.workproject.entity.WorkProject;
import com.jeeplus.modules.workreimbursement.utils.VarStr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 全过程管理Service
 * @author mapengbo
 * @version 2017-10-24
 */
@Service
@Transactional(readOnly = true)
public class WorkFullManageService extends CrudService<WorkFullManageDao, WorkFullManage> {


	@Autowired
	private WorkFullManageDao workFullManageDao;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkContractInfoDao workContractInfoDao;
	@Autowired
	private WorkFullConstructDao workFullConstructDao;
	@Autowired
	private WorkFullSurveyDao workFullSurveyDao;
	@Autowired
	private WorkFullDesignDao workFullDesignDao;
	@Autowired
	private WorkClientInfoService workClientInfoService;
	@Autowired
	private WorkClientAttachmentDao workClientAttachmentDao;
	@Autowired
	private WorkFullExecuteDao workFullExecuteDao;
	@Autowired
	private WorkContractAnnexDao workContractAnnexDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private WorkClientLinkmanDao workClientLinkmanDao;
	@Autowired
	private AreaDao areaDao;

	public WorkFullManage getSimpleWorkFullManage(String id){
		return super.get(id);
	}
	public WorkFullManage getByPId(WorkProject workProject){
		return workFullManageDao.getByPId(workProject);
	}
	public WorkFullManage getWF(String id){
		WorkFullManage workFullManage = super.get(id);
		if(workFullManage != null){
			WorkClientInfo workClientInfo = workClientInfoService.get(workFullManage.getClientId());
			workClientInfo.setCreditRank(DictUtils.getDictLabel(workClientInfo.getCreditRank(),"credit_rank",workClientInfo.getCreditRank()));
			workFullManage.setWorkClientInfo(workClientInfo);
			WorkFullManage wf = workFullManageDao.get(workFullManage.getTotalFullId());
			if(wf != null){
				workFullManage.setTotalFullName(wf.getTotalFullName());
			}
		}
		return workFullManage;
	}
	public WorkFullManage get(String id) {
		if(StringUtils.isBlank(id)){
			return new WorkFullManage();
		}
		WorkFullManage workFullManage = super.get(id);
		if(workFullManage==null){
			return new WorkFullManage();
		}
		//获取附件信息
		WorkClientAttachment workClientAttachment = new WorkClientAttachment();
		workClientAttachment.setAttachmentId(id);
		workClientAttachment.setAttachmentFlag(VarStr.attachmentFlag[2]);
		workFullManage.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));
		//公司信息
		workFullManage.setHostCompany(officeService.get(workFullManage.getHostCompany()));
		workFullManage.setFollowCompany(officeService.get(workFullManage.getFollowCompany()));
		//合同信息
		WorkContractInfo contract = workContractInfoDao.findUniqueByProperty("contract_num", workFullManage.getContractId());
		if(contract != null){
			WorkContractInfo workContractInfo = workContractInfoDao.get(contract.getId());
//			workContractInfo.setWorkContractAnnexList(workContractAnnexDao.findList(new WorkContractAnnex(workContractInfo)));
			workFullManage.setWorkContractInfo(workContractInfo);
		}
		if(workFullManage.getConstructId() != null){
			workFullManage.setConstructId(workFullConstructDao.get(workFullManage.getConstructId().getId()));
		}
		if(workFullManage.getDesignId() != null){
			workFullManage.setDesignId(workFullDesignDao.get(workFullManage.getDesignId().getId()));
		}
		if(workFullManage.getSurveyId() != null){
			workFullManage.setSurveyId(workFullSurveyDao.get(workFullManage.getSurveyId().getId()));
		}
		//委托方信息
		WorkClientInfo workClientInfo = workClientInfoService.get(workFullManage.getClientId());
		if(workClientInfo != null){
			workClientInfo.setCreditRank(DictUtils.getDictLabel(workClientInfo.getCreditRank(),"credit_rank",workClientInfo.getCreditRank()));
			List<WorkClientLinkman>  workClientLinkmanList = workClientLinkmanDao.findByClientId(workClientInfo.getId());
			if(workClientLinkmanList!=null && workClientLinkmanList.size()>0){
				workClientInfo.setWorkClientLinkman(workClientLinkmanList.get(0));
			}
			workFullManage.setWorkClientInfo(workClientInfo);
		}
		//建设方信息
		WorkClientInfo workBuildInfo = workClientInfoService.get(workFullManage.getBuildId());
		if(workBuildInfo != null){
			workBuildInfo.setCreditRank(DictUtils.getDictLabel(workBuildInfo.getCreditRank(),"credit_rank",workClientInfo.getCreditRank()));
			workFullManage.setWorkBuildInfo(workBuildInfo);
		}
		if(!Strings.isNullOrEmpty(workFullManage.getHostMaster())){
			String[] split = workFullManage.getHostMaster().split(",");
			String hostMasterName = getPeople(split);
			workFullManage.setHostMasterName(hostMasterName);
		}

		if(!Strings.isNullOrEmpty(workFullManage.getFollowMaster())){
			String[] split1 = workFullManage.getFollowMaster().split(",");
			String followMasterName = getPeople(split1);
			workFullManage.setFollowMasterName(followMasterName);
		}
		if(!Strings.isNullOrEmpty(workFullManage.getHostMember())){
			String[] split2 = workFullManage.getHostMember().split(",");
			String hostMemberName = getPeople(split2);
			workFullManage.setHostMemberName(hostMemberName);
		}
		if(!Strings.isNullOrEmpty(workFullManage.getFollowMember())){
			String[] split3 = workFullManage.getFollowMember().split(",");
			String followMemberName = getPeople(split3);
			workFullManage.setFollowMemberName(followMemberName);
		}
		return workFullManage;
	}

	public List<WorkFullManage> findList(WorkFullManage workFullManage) {
		return super.findList(workFullManage);
	}

		public Page<WorkFullManage> findPage(Page<WorkFullManage> page, WorkFullManage workFullManage) {
		if (StringUtils.isNotBlank(workFullManage.getTotalFullIds())){
			workFullManage.setTotalFullIds(","+workFullManage.getTotalFullIds()+",");
		}
		workFullManage.setOfficeId(UserUtils.getSelectOffice().getId());
		workFullManage.getSqlMap().put("dsf", dataScopeFilterOR(workFullManage.getCurrentUser(), "o", "u","s", MenuStatusEnum.END.getValue()));
		workFullManage.setPage(page);
		workFullManage.setIsTotal("1");
		List<WorkFullManage> list = Lists.newArrayList();
		List<WorkFullManage> totals = dao.findList(workFullManage);
		List<WorkFullManage> workFullManages = new ArrayList<>();
		for (WorkFullManage fullManage:totals){
			WorkFullManage wfm = new WorkFullManage();
			wfm.setTotalFullId(fullManage.getId());
			List<WorkFullManage> workEngineeringProjectLists = dao.findList(wfm);
			if (workEngineeringProjectLists!=null && workEngineeringProjectLists.size()!=0){
				workFullManages.addAll(workEngineeringProjectLists);
			}
		}
		workFullManages.addAll(totals);
		sortList(list,workFullManages,"0",true);
		page.setList(list);
		return page;
	}

	public static void sortList(List<WorkFullManage> list, List<WorkFullManage> sourcelist, String parentId, boolean cascade){
		for (int i=0; i<sourcelist.size(); i++){
			WorkFullManage e = sourcelist.get(i);
			if (e.getTotalFullId()!=null && e.getTotalFullId().equals(parentId)){
				list.add(e);
				if (cascade){
					// 判断是否还有子节点, 有则继续获取子节点
					for (int j=0; j<sourcelist.size(); j++){
						WorkFullManage child = sourcelist.get(j);
						if (child.getTotalFullId()!=null && child.getTotalFullId().equals(e.getId())){
							sortList(list, sourcelist, e.getId(), true);
							break;
						}
					}
				}
			}
		}
	}

	@Transactional(readOnly = false)
	public void save(WorkFullManage workFullManage) {
		Area area = workFullManage.getArea();
		area = areaDao.get(area.getId());
		workFullManage.setArea(area);
//		// 主办公司负责人
//		List<User> hostMasterList = new ArrayList<User>();
//		// 协办公司负责人
//		List<User> followMasterList = new ArrayList<>();
//		// 主办公司项目成员
//		List<User> hostMemberList = new ArrayList<>();
//		// 协办公司项目成员
//		List<User> followMemberList = new ArrayList<>();
//
//		String hostMasters = dealPeople(workFullManage.getHostMasterList(), hostMasterList);
//		String followMasters = dealPeople(workFullManage.getFollowMasterList(), followMasterList);
//		String hostMembers = dealPeople(workFullManage.getHostMemberList(), hostMemberList,hostMasters);
//		String followMembers = dealPeople(workFullManage.getFollowMemberList(), followMemberList,followMasters);
//		workFullManage.setHostMaster(hostMasters);
//		workFullManage.setHostMember(hostMembers);
//		workFullManage.setFollowMaster(followMasters);
//		workFullManage.setFollowMember(followMembers);

//		workFullManage.setHostMasterList(hostMasterList);
//		workFullManage.setFollowMasterList(followMasterList);
//		workFullManage.setHostMemberList(hostMemberList);
//		workFullManage.setFollowMemberList(followMemberList);
//		if(hostMasterList.size() > 0){
//			workFullManageDao.insertHostMaster(workFullManage);
//		}
//		if(followMasterList.size() > 0){
//			workFullManageDao.insertFollowMaster(workFullManage);
//		}
//		if(hostMemberList.size() > 0){
//			workFullManageDao.insertHostMember(workFullManage);
//		}
//		if(followMemberList.size() > 0){
//			workFullManageDao.insertFollowMember(workFullManage);
//		}
		super.save(workFullManage);
		//附件信息
		for (WorkClientAttachment workClientAttachment : workFullManage.getWorkAttachments()){
			if (workClientAttachment.getId() == null){
				continue;
			}
			if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())){
				workClientAttachment.setAttachmentId(workFullManage.getId());
				workClientAttachment.setAttachmentFlag(VarStr.attachmentFlag[2]);
				workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
				workClientAttachment.setCompanyId(UserUtils.getSelectCompany().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(WorkFullManage workFullManage) {
		super.delete(workFullManage);
	}

	/**
	 * 查询附件列表
	 * @param workClientAttachment
	 * @return
	 */
	@Transactional(readOnly = false)
	public List<WorkClientAttachment> findList(WorkClientAttachment workClientAttachment){
		return workClientAttachmentDao.findList(workClientAttachment);
	}
	/**
	 * 删除附件
	 * @param workClientAttachment
	 * @return
	 */
	@Transactional(readOnly = false)
	public int deleteAttach(WorkClientAttachment workClientAttachment){
		return workClientAttachmentDao.delete(workClientAttachment);
	}

	/**
	 * 修改项目状态
	 * @param workFullManage
	 * @return
	 */
	@Transactional(readOnly = false)
	public int updStatusById(WorkFullManage workFullManage){
		return workFullManageDao.update(workFullManage);
	}

	/**
	 * 查询施工阶段的所有文件
	 * @return
	 */
	public List<WorkClientAttachment> queryEngeerFile(String companyId,String workFullManageId){
		WorkFullExecute workFullExecute = new WorkFullExecute();
		workFullExecute.setCompanyId(companyId);
		workFullExecute.setWorkFullManageId(workFullManageId);
		List<WorkFullExecute> list = workFullExecuteDao.findList(workFullExecute);
		List<WorkClientAttachment> li = new ArrayList<WorkClientAttachment>();
		for (WorkFullExecute worke : list) {
			WorkClientAttachment workClientAttachment = new WorkClientAttachment();
			workClientAttachment.setAttachmentId(worke.getId());
			workClientAttachment.setAttachmentFlag("2");
			List<WorkClientAttachment> workList = workClientAttachmentDao.findList(workClientAttachment);
			li.addAll(workList);
		}
		return li;
	}

	/**
	 * 处理人员
	 * @param list
	 * @param reList
	 * @return
	 */
	public String dealPeople(List<User> list,List<User> reList){
		String member = "";
		for (int i = 0; i < list.size(); i++) {
			User user = list.get(i);
			if (user.getId() == null) {
				continue;
			}
			reList.add(user);
			if(i + 1 == list.size()){
				member += user.getId();
			}else {
				member += user.getId()+",";
			}
		}
		return member;
	}
	/**
	 * 处理人员 去掉成员中的项目负责人
	 * @param list
	 * @param reList
	 * @return
	 */
	public String dealPeople(List<User> list,List<User> reList,String reMember){
		String member = "";
		for (int i = 0; i < list.size(); i++) {
			User user = list.get(i);
			if (user.getId() == null || reMember.contains(user.getId())) {
				continue;
			}
			reList.add(user);
			if(i + 1 == list.size()){
				member += user.getId();
			}else {
				member += user.getId()+",";
			}
		}
		return member;
	}

	/**
	 * 处理人员,返回人员名称
	 * @return
	 */
	public String getPeople(String[] split){
		if(split.length == 0){
			return "";
		}
		String name = "";
		for (int i = 0; i < split.length; i++) {
			if(i == split.length -1){
				name += UserUtils.get(split[i]).getName();
			}else{
				name += UserUtils.get(split[i]).getName()+",";
			}
		}
		return name;
	}

	/**
	 * 获取所有涉及人员的部门负责人
	 * @param split
	 * @return
	 */
	public String getPeopleMaster(String[] split){
		if(split.length == 0){
			return "";
		}
		String masterId = "";
		for (int i = 0; i < split.length; i++) {
			User user = UserUtils.get(split[i]);
			Map<Object,Object> map = new HashMap<>();
			map.put("ename","bmzr");
			map.put("companyId",user.getCompany().getId());
			map.put("officeId",user.getOffice().getId());
			if(i == split.length -1){
				masterId += roleDao.queryMasterByEnameAndOfficeId(map);
			}else{
				masterId += roleDao.queryMasterByEnameAndOfficeId(map) + ",";
			}
		}
		return masterId;
	}

	public Page<WorkFullManage> findPageByproject(Page<WorkFullManage> page, WorkFullManage workFullManage) {
		workFullManage.setPage(page);
		page.setList(dao.findListByprojectt(workFullManage));
		return page;
	}

	public List<WorkFullManage> findByList(WorkFullManage workFullManage) {
		return dao.findByList(workFullManage);
	}


    public String parseList2Json(WorkClientInfo workClientInfo) {
		if(workClientInfo == null){
			return "";
		}
		List<WorkClientLinkman> list = workClientInfo.getWorkClientLinkmanList();
		List<Map<Object,Object>> resultList = Lists.newArrayList();
		String creditRank = DictUtils.getDictLabel(workClientInfo.getCreditRank(),"credit_rank","");
		if(list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				HashMap<Object, Object> map = Maps.newHashMap();
				map.put("linkmanName", list == null ? "" : list.get(i).getName());
				map.put("linkmanOffice", list == null ? "" : list.get(i).getOffice());
				map.put("linkmanPosition", list == null ? "" : list.get(i).getPosition());
				map.put("QQ", list == null ? "" : list.get(i).getQq());
				map.put("linkmanPhone", list == null ? "" : list.get(i).getLinkPhone());
				map.put("linkmanMobile", list == null ? "" : list.get(i).getLinkMobile());
				map.put("linkmanEmail", list == null ? "" : list.get(i).getEmail());
				map.put("clientName", workClientInfo.getName()==null ? "" :workClientInfo.getName());
				map.put("clientId", workClientInfo.getId() ==null?"":workClientInfo.getId());
				map.put("creditRank",creditRank);
				resultList.add(map);
			}
		}
		String resultJsonStr = JsonMapper.toJsonString(resultList);
		return resultJsonStr;
    }
}