package com.huigou.topsun.common;

import com.huigou.cache.SystemCache;
import com.huigou.context.Operator;
import com.huigou.context.OrgUnit;
import com.huigou.context.ThreadLocalUtil;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.uasp.annotation.Expression;
import com.huigou.uasp.bmp.fn.AbstractDaoFunction;
import com.huigou.uasp.bmp.fn.impl.OrgFun;
import com.huigou.uasp.bmp.opm.OpmUtil;
import com.huigou.uasp.bmp.opm.domain.model.org.Org;
import com.huigou.uasp.bmp.opm.proxy.OrgApplicationProxy;
import com.huigou.uasp.bmp.opm.repository.org.OrgRepository;
import com.huigou.util.ClassHelper;
import com.huigou.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

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

/**
 * 硬X射线使用函数
 *
 * @author xiexin
 */
@Expression
@Service("function")
public class Function extends AbstractDaoFunction {
	/**
	 * 建安采购类别编码
	 */
	private static final String BUILD_KIND_CODE = "CE";

	@Autowired
	private OrgFun orgFun;

	@Autowired
	protected OrgApplicationProxy orgApplication;

	@Autowired
	private OrgRepository orgRepository;

	/**
	 * 根据数据判断是否为建安类
	 * 
	 * @param purchaseKind
	 * @return
	 */
	public static boolean isBuildPurchaseKind(String purchaseKind) {
		if (StringUtil.isBlank(purchaseKind)) {
			return false;
		}
		return purchaseKind.toUpperCase().startsWith(BUILD_KIND_CODE);
	}

	/**
	 * 根据数据判断是否为建安类
	 * 
	 * @param data
	 * @return
	 */
	public static boolean isBuildKindPurchase(Map<String, Object> data) {
		String purchaseKind = ClassHelper.convert(data.get("purchaseKind"), String.class, "0");
		return isBuildPurchaseKind(purchaseKind);
	}

	private String getSqlByname(String sqlName) {
		QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery("config/topsun/base/function.xml",
				"function");
		return queryDescriptor.getSqlByName(sqlName);
	}

	/**
	 * 查询输入组织对应的系统
	 * 
	 * @param orgUnitId
	 * @return
	 */
	public Org findTechHxSystemNode(String orgUnitId) {
		String sql = this.getSqlByname("queryTechHxSystemNode");
		Org org = this.sqlExecutorDao.queryOneToObject(sql, Org.class, orgUnitId, orgUnitId);
		return org;
	}

	/**
	 * 查询当前用户对应的系统
	 * 
	 * @return
	 */
	public String findHxCurrentPersonSystemId() {
		Operator operator = ThreadLocalUtil.getOperator();
		Org org = this.findTechHxSystemNode(operator.getFullId());
		if (org == null) {
			return operator.getDeptId();
		}
		return org.getId();
	}

	/**
	 * 查询当前用户对应的总体
	 * 
	 * @return
	 */
	public String findHxCurrentPersonZtFullId() {
		Operator operator = ThreadLocalUtil.getOperator();
		String sql = this.getSqlByname("queryHxOrgByPersonIdAndType");
		Org org = this.sqlExecutorDao.queryOneToObject(sql, Org.class, operator.getUserId(), "zt");
		if (org == null) {
			return operator.getFullId();
		}
		return org.getFullId();
	}

	/**
	 * 获取系统，分总体,总体负责人
	 * 
	 * @param fullId
	 * @param type
	 * @return
	 */
	public List<OrgUnit> findHxOrgManagerByType(String fullId, String type) {
		String sql = this.getSqlByname("queryHxOrgByFullIdAndType");
		Org org = this.sqlExecutorDao.queryOneToObject(sql, Org.class, fullId, type);
		Assert.notNull(org, "获取系统，分总体,总体负责人失败未找到对应组织:" + type);
		String adminManageType = SystemCache.getParameter("adminMR", String.class);
		return orgFun.findNearestManagers(org.getFullId(), adminManageType);
	}

	private List<OrgUnit> queryHxBudgetManagerByType(List<String> fullIds, String type) {
		String sql = this.getSqlByname("queryHxOrgByFullIdAndType");
		if (fullIds == null || fullIds.size() == 0) {
			return null;
		}
		// 默认获取行政管理权限
		String adminManageType = SystemCache.getParameter("adminMR", String.class);
		Map<String, String> persons = new HashMap<>();
		List<OrgUnit> orgUnits = new ArrayList<>();
		String orgFullId = null, personId = null;
		for (String fullId : fullIds) {
			orgFullId = fullId;
			if (!type.equalsIgnoreCase("xt")) {
				// 按类型
				Org org = this.sqlExecutorDao.queryOneToObject(sql, Org.class, fullId, type);
				if (org != null) {
					orgFullId = org.getFullId();
				} else {
					orgFullId = fullId;
				}
			}
			List<OrgUnit> tmps = orgFun.findNearestManagers(orgFullId, adminManageType);
			if (tmps != null && tmps.size() > 0) {
				for (OrgUnit o : tmps) {
					personId = OpmUtil.getPersonIdFromFullId(o.getFullId());
					if (!persons.containsKey(personId)) {
						persons.put(personId, "1");
						orgUnits.add(o);
					}
				}
			}
		}
		return orgUnits;
	}

	/**
	 * 根据采购申请单据ID获取预算管理者
	 * 
	 * @param bizId
	 * @param type
	 * @return
	 */
	public List<OrgUnit> findHxBudgetManagerByType(String bizId, String type) {
		// 判断是否为建安类采购
		String sql = this.getSqlByname("queryPurchaseApprovalInfo");
		Map<String, Object> map = this.sqlExecutorDao.queryToMap(sql, bizId);
		Assert.notEmpty(map, "未找到采购申请信息");
		String purchaseKind = ClassHelper.convert(map.get("purchaseKind"), String.class, "0");
		if (isBuildPurchaseKind(purchaseKind)) {// 建安类采购
			String systemFullId = ClassHelper.convert(map.get("systemFullId"), String.class);
			// 获取系统，分总体,总体负责人
			return this.findHxOrgManagerByType(systemFullId, type);
		}
		if (type.equalsIgnoreCase("xt")) {// 系统负责人对应查询使用预算的责任人
			sql = this.getSqlByname("queryPurchaseApprovalBudgetPerson");
			List<OrgUnit> orgUnits = this.sqlExecutorDao.queryToList(sql, OrgUnit.class, bizId);
			if (orgUnits != null && orgUnits.size() > 0) {
				return orgUnits;
			}
		}
		// 查询采购申请中包含的系统
		sql = this.getSqlByname("queryPurchaseApprovalBudgetOrg");
		List<String> fullIds = this.sqlExecutorDao.queryToList(sql, String.class, bizId);
		Assert.notEmpty(fullIds, "未找到填写的预算信息!");
		return this.queryHxBudgetManagerByType(fullIds, type);

	}

	/**
	 * 根据用款审批单ID查询使用预算对应管理者
	 * 
	 * @param bizId
	 * @param type
	 * @return
	 */
	public List<OrgUnit> findHxMoneyUsedManagerByType(String bizId, String type) {
		// 查询是否建安类采购
		String sql = this.getSqlByname("queryMoneyUsedApprovalInfo");
		Map<String, Object> map = this.sqlExecutorDao.queryToMap(sql, bizId);
		Assert.notEmpty(map, "未找到采购申请信息");
		String purchaseKind = ClassHelper.convert(map.get("purchaseKind"), String.class, "0");
		if (isBuildPurchaseKind(purchaseKind)) {// 建安类采购
			String systemFullId = ClassHelper.convert(map.get("systemFullId"), String.class);
			// 获取系统，分总体,总体负责人
			return this.findHxOrgManagerByType(systemFullId, type);
		}
		if (type.equalsIgnoreCase("xt")) {// 系统负责人对应查询使用预算的责任人
			sql = this.getSqlByname("queryMoneyUsedBudgetPerson");
			List<OrgUnit> orgUnits = this.sqlExecutorDao.queryToList(sql, OrgUnit.class, bizId);
			if (orgUnits != null && orgUnits.size() > 0) {
				return orgUnits;
			}
		}
		// 查询采购申请中包含的系统
		sql = this.getSqlByname("queryMoneyUsedBudgetOrg");
		List<String> fullIds = this.sqlExecutorDao.queryToList(sql, String.class, bizId);
		Assert.notEmpty(fullIds, "未找到填写的预算信息!");
		return this.queryHxBudgetManagerByType(fullIds, type);
	}

	/**
	 * 根据基础管理权限查询对应的数据管理权限
	 * 
	 * @param cs
	 * @return
	 */
	public List<String> queryBizManagementTypeByCode(List<String> cs) {
		Assert.notEmpty(cs);
		String sql = this.getSqlByname("queryBizManagementTypeByCode");
		StringBuffer sb = new StringBuffer();
		sb.append(sql);
		sb.append(" and t.code in (");
		int l = cs.size();
		for (int i = 0; i < l; i++) {
			sb.append("'").append(cs.get(i)).append("'");
			if (i < l - 1) {
				sb.append(",");
			}
		}
		sb.append(")");
		return this.sqlExecutorDao.queryToList(sb.toString(), String.class);
	}

	/**
	 * 根据预算信息中的系统编码获取线站负责人
	 * @param bizId
	 * @return
	 */
	public List<OrgUnit> findStationLeaders(String bizId) {
		Assert.hasText(bizId, "参数id不能为空。");
		String sql = this.getSqlByname("queryStationLeaders");
		return this.sqlExecutorDao.queryToList(sql, OrgUnit.class, bizId);
	}
}
