package com.goafanti.organization.service.impl;

import java.util.*;

import com.goafanti.common.dao.DepartmentMapper;
import com.goafanti.common.dao.NewOrderChangeMapper;
import com.goafanti.common.dao.TOrderNewMapper;
import com.goafanti.common.enums.OrderState;
import com.goafanti.common.model.Department;
import com.goafanti.common.utils.AsyncUtils;
import com.goafanti.order.enums.ProcessStatus;
import com.goafanti.organization.bo.DepOut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.organization.bo.OrganizationListOut;
import com.goafanti.organization.service.OrganizationService;
import com.goafanti.admin.bo.AdminListBo;
import com.goafanti.common.dao.TOrderMidMapper;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
@Service
public class OrganizationServiceImpl extends BaseMybatisDao<DepartmentMapper> implements OrganizationService {
	@Autowired
	private DepartmentMapper departmentMapper;
	@Autowired
	private TOrderMidMapper	tOrderMidMapper;
	@Autowired
	private TOrderNewMapper	tOrderNewMapper;
	@Autowired
	private NewOrderChangeMapper newOrderChangeMapper;
	@Autowired
	private AsyncUtils asyncUtils;

	@Override
	public Pagination<OrganizationListOut> listOrganizationManagement(OrganizationListOut olo, Integer pageNo,
			Integer pageSize) {
		/*olo.setCreateId(TokenManager.getAdminId());*/
		Map<String,Object> params =disposeParams(olo);
		@SuppressWarnings("unchecked")
		Pagination<OrganizationListOut> p=(Pagination<OrganizationListOut>)findPage("selectOrganizationList","selectOrganizationCount",params,pageNo,pageSize);
		return p;
	}
	private Map<String,Object> disposeParams(OrganizationListOut olo){
		Map<String,Object> params = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(olo.getId())) params.put("id", olo.getId());
		if(StringUtils.isNotBlank(olo.getCreateId())) params.put("createId", olo.getCreateId());
		if(StringUtils.isNotBlank(olo.getCreateTime())) params.put("createTime", olo.getCreateTime());
		if(StringUtils.isNotBlank(olo.getUpdateTime())) params.put("updateTime", olo.getUpdateTime());
		if(StringUtils.isNotBlank(olo.getDeletedSign())) params.put("deletedSign", olo.getDeletedSign());
		if(StringUtils.isNotBlank(olo.getName())) params.put("name", olo.getName());
		if(StringUtils.isNotBlank(olo.getType())) params.put("type", olo.getType());
		if(StringUtils.isNotBlank(olo.getManagerId())) params.put("managerId", olo.getManagerId());
		if(StringUtils.isNotBlank(olo.getDepNo())) params.put("depNo", olo.getDepNo());
		if(StringUtils.isNotBlank(olo.getSuperId())) params.put("superId", olo.getSuperId());
		if(StringUtils.isNotBlank(olo.getRemarks())) params.put("remarks", olo.getRemarks());
		if(StringUtils.isNotBlank(olo.getStatus())) params.put("status", olo.getStatus());
		return params;
	}
	@Override
	public List<DepOut> selectSuperId(Integer hideSign) {
		if(hideSign==null){
			hideSign=1;
		}
		//此处理用于前端不批量改接口
		if (hideSign>1){
			hideSign=null;
		}
		List<DepOut> depList=departmentMapper.selectSuperId(hideSign,null,null);
		return depList;
	}

	@Override
	public List<DepOut> getAllDep(Integer hideSign) {
		if(hideSign==null){
			hideSign=1;
		}
		//此处理用于前端不批量改接口
		if (hideSign>1){
			hideSign=null;
		}
		List<DepOut> allDep=departmentMapper.selectSuperId(hideSign,null,null);

		List<DepOut> dep1=new ArrayList<>();
		Integer x=3;//设置顶级
		for (DepOut e : allDep) {
			if (e.getLvl()==x){
				e.setList(selectDepLvl(allDep,e.getId(),x+1));
				dep1.add(e);
			}
		}
		return dep1;
	}

	private List<DepOut> selectDepLvl(List<DepOut> allDep,String id, Integer i) {
		List<DepOut> newDep=new ArrayList<>();
		for (DepOut depOut : allDep) {
			if (depOut.getLvl()==i&&depOut.getSuperId().equals(id)){
				if (i<7)depOut.setList(selectDepLvl(allDep,depOut.getId(),i+1));
				newDep.add(depOut);
			}
		}
		return newDep;
	}


	/**
	 *   XXIn form 提交 ,bo包中
	 *   xxOut 输出 bo包中
	 *   domain 类 model中
	 *
	 */
	@Override
	public int addOrganization( String name, String managerId, String type, String superId, String remarks,
								Integer workingHoursType,Integer hideSign,String depNo) {
		Department superDep=departmentMapper.selectByPrimaryKey(superId);
		String id = UUID.randomUUID().toString();
		Date now = new Date();
		Department dep=new Department();
		dep.setId(id);
		String createId =departmentMapper.selectAdminNameById(TokenManager.getAdminId());
		dep.setCreateId(createId);
		dep.setCreateTime(now);
		dep.setUpdateTime(now);
		dep.setDeletedSign(0);
		dep.setName(name);
		dep.setLvl(superDep.getLvl()+1);
		dep.setType(type);
		dep.setManagerId(managerId);
		dep.setDepNo(depNo);
	//	superId=departmentMapper.selectIdByName(superId);
		dep.setSuperId(superId);
		dep.setRemarks(remarks);
		dep.setStatus("0");
		dep.setHideSign(hideSign);
		dep.setWorkingHoursType(workingHoursType);
		departmentMapper.insertSelective(dep);
		return 1;
	}

	private String getMaxDep(Department superDep) {
		String sdepNo=superDep.getDepNo();
		Department maxDep=departmentMapper.selectByDepNo(superDep.getId());
		String depNo=new String();
		if (maxDep==null){
			depNo= sdepNo +"01";
		}else {
			String maxDepNo=maxDep.getDepNo();
			Integer countNo=Integer.valueOf(maxDepNo.substring(maxDepNo.length()-2));
			countNo++;
			if (countNo<10){
				depNo= sdepNo +"0"+countNo;
			}else {
				depNo= sdepNo +countNo;
			}
		}
		return depNo;
	}


	@Override
	public List<AdminListBo> selectName(String name) {
		List<AdminListBo> list=departmentMapper.selectName(name);
		return list;
	}
	@Override
	public OrganizationListOut selectAllById(String id) {
		OrganizationListOut olo=departmentMapper.selectAllById(id);
		olo.setSuperId(departmentMapper.selectNameById(olo.getSuperId()));
		return olo;
	}
	@Override
	public int deleteById(String id) {
		departmentMapper.deleteById(id);
		return 1;
	}
	@Override
	public int updateOrganization(String name, String type, String managerId, String superId, String status,Integer province,
			String remarks,String id,String abbreviation,String financeId,Integer workingHoursType,Integer hideSign,String depNo) {
		//获取上级编号
		Department superDep=departmentMapper.selectByPrimaryKey(superId);
		Date now=new Date();
		Department dep=new Department();
		dep.setLvl(superDep.getLvl()+1);
		dep.setName(name);
		dep.setType(type);
		dep.setUpdateTime(now);
		dep.setManagerId(managerId);
		dep.setStatus(status);
		dep.setRemarks(remarks);
		dep.setId(id);
		dep.setSuperId(superId);
		dep.setDepNo(depNo);
		dep.setAbbreviation(abbreviation);
		dep.setFinanceId(financeId);
		dep.setProvince(province);
		dep.setHideSign(hideSign);
		dep.setWorkingHoursType(workingHoursType);
		checkFinaceUpdate(id,financeId);
		int x=departmentMapper.updateByPrimaryKeySelective(dep);
		return x;
	}

	/**
	 * 如果更换了负责人刷新中间表
	 * @param id
	 * @param financeId
	 */
	private void checkFinaceUpdate(String id, String financeId) {
		Department dep = departmentMapper.selectByPrimaryKey(id);
		if (financeId!=null&&financeId.equals(dep.getFinanceId())){
			asyncUtils.updateFinanceExamineAndDep(id,financeId);
		}
	}

	@Override
	public boolean checkDepNo(String depNo,Integer type) {
		String useDepNo=departmentMapper.selectIdByDepNo(depNo);
		if (StringUtils.isNotBlank(useDepNo)){
			if (type==1){
				if (!depNo.equals(useDepNo)){
					return false;
				}else {
					return true;
				}
			}else {
				return true;
			}

		}
		return false;
	}

	private String countDepNo(String sdepNo, Integer count) {
		String dep=null;
		if(count<10){
			dep=sdepNo+"0"+count;
			String sid=departmentMapper.selectIdByDepNo(dep);
			while(sid!=null){
				count=(count+1)%100;
				if(count>=10){
					dep=sdepNo+count;
				}else{
					dep=sdepNo+"0"+count;
				}
				sid=departmentMapper.selectIdByDepNo(dep);
			}
		}else if(count>=10){
			dep=sdepNo+count;
			String sid=departmentMapper.selectIdByDepNo(dep);
			while(sid!=null){
				count=(count+1)%100;
				dep=sdepNo+count;
				sid=departmentMapper.selectIdByDepNo(dep);
			}
		}
		return dep;
	}

	private void updateLowerLevelNo(String id,String depNo,Integer lvl) {
		List<OrganizationListOut> Nos =departmentMapper.selectIDNBySuperId(id);
		int i=1;
		for (OrganizationListOut o : Nos) {
			o.setLvl(lvl+1);
			if(i<10){
				String dep=depNo+"0"+i;
				if(i>=10){
					dep=depNo+i;
				}else{
					dep=depNo+"0"+i;
				}
				o.setDepNo(dep);
			} else if(i>=10){
				String dep=depNo+i;
				dep=depNo+i;
				o.setDepNo(dep);
			}
			departmentMapper.updateByNumber(o);
			updateLowerLevelNo(o.getId(),o.getDepNo(),o.getLvl());
			i++;
		}
	}

}
