package com.hotent.base.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import com.google.common.base.Joiner;
import com.hotent.base.constants.TenantConstant;
import com.hotent.base.context.BaseContext;

/**
 * <pre>
 *
 * 租户相关工具类
 * </pre>
 * @author jason
 * @Date 2020-04-23
 */
public class TenantUtil {

	private static Log logger = LogFactory.getLog(TenantUtil.class);
	

	/**
	 * <pre>
	 * 初始化租户数据
	 * </pre>
	 * @param tenantId
	 * @param tableNames
	 */
	public static void initData(String tenantId, List<String> tableNames) {
		JdbcTemplate jdbcTemplate = AppUtil.getBean(JdbcTemplate.class);
		logger.debug("开始初始化租户的数据");
		for (String tableName : tableNames) {
			String sql = String.format("select * from %s where tenant_id_ = '%s'", tableName,TenantConstant.PLATFORM_TENANT_ID);
			if("portal_sys_type".equals(tableName)){
				sql = sql + String.format(" and type_key_ = '%s'", "default");
			}else if("uc_demension".equals(tableName)){
				sql = sql + String.format(" and is_default_ = %s", 1);
			} else if ("portal_news_tree_".equals(tableName)) {
				// 新闻公告树
				sql = sql + String.format(" and parent_id_ = '%s'", "0");
			}
			List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
			List<String> updateSqls = new ArrayList<String>();
 			for (Map<String,Object> map : queryForList) {

 				Iterator<Entry<String,Object>> iter = map.entrySet().iterator();
 				List<String> fields = new ArrayList<String>();
 				List<Object> params = new ArrayList<Object>();
 				Object id = null;
 				int longtextIndex = -1;
 				while(iter.hasNext()){
 				   Entry<String,Object> entry = iter.next();
 				   String key = entry.getKey();

 				   Object value = entry.getValue();
 				   String lowerCase = key.toLowerCase();
 				   switch (lowerCase) {
					case "id_":
						value = UniqueIdUtil.getSuid();
						id = value;
						break;
					case "id":
						value = UniqueIdUtil.getSuid();
						break;
					case "tenant_id_":
						value = tenantId;
						break;
					case "path_":
						if(tableName.equals("portal_sys_type")) {
							value = String.valueOf(value).split("\\.")[0]+"."+id+".";
						}
						break;
					}
 				  if(BeanUtils.isNotEmpty(value) && !(value instanceof Date)) {//暂屏蔽拷贝日期字段的值
 					 fields.add(key);
 	 				 if(value instanceof String) {
 	 					 value = "\'"+value + "\'";
 	 				 }
 					 params.add(value);
 					 if(value.toString().length()>4000) {
 						longtextIndex = params.size()-1;
 					 }
 				  }
				}
				String updateSql = "";
				// 处理布局数据 design_html 长度超过4000情况 使用 update 语句拼接
				if ("portal_sys_layout_manage".equals(tableName)) {
					// design_html 分割长度
                    Boolean outOfLimit = false;
					for(int i =0;i<params.size();i++){
						if(params.get(i).toString().length()>4000 && fields.get(i).equalsIgnoreCase("DESIGN_HTML")){
						    outOfLimit = true;
							int subNum = 3000;
							String design_html = "";
							design_html = params.get(i).toString();
							params.set(i, params.get(i).toString().substring(0, subNum) + "'");
							updateSql = String.format("insert into %s(%s) values(%s)", tableName, Joiner.on(",").join(fields), Joiner.on(",").join(params));
							updateSqls.add(updateSql);
							int subIndex = ((design_html.length() - subNum) / subNum) + 1;
							for (int j = 1; j <= subIndex; j++) {
								int subLength = subNum * (j + 1);
								if (j == subIndex) {
									subLength = design_html.length() - 1;
								}
								String dhUpdateSql = String.format("update portal_sys_layout_manage set DESIGN_HTML = concat(DESIGN_HTML,%s) where ID = %s",
										"'" + design_html.substring(subNum * j, subLength) + "'",
										params.get(0));
								updateSqls.add(dhUpdateSql);
							}
							break;
						}
					}
					if(!outOfLimit){
                        updateSql = String.format("insert into %s(%s) values(%s)", tableName, Joiner.on(",").join(fields), Joiner.on(",").join(params));
                        updateSqls.add(updateSql);
                    }
				}else if ("portal_sys_column".equals(tableName) && longtextIndex>-1) {
					// design_html 分割长度
					int subNum = 3000;
					String template_html = params.get(longtextIndex).toString();
					params.set(longtextIndex, params.get(longtextIndex).toString().substring(0, subNum) + "'");
					updateSql = String.format("insert into %s(%s) values(%s)", tableName, Joiner.on(",").join(fields), Joiner.on(",").join(params));
					updateSqls.add(updateSql);
					int subIndex = ((template_html.length() - subNum) / subNum) + 1;
					for (int i = 1; i <= subIndex; i++) {
						int subLength = subNum * (i + 1);
						if (i == subIndex) {
							subLength = template_html.length() - 1;
						}
						String dhUpdateSql = String.format("update portal_sys_column set TEMPLATE_HTML = concat(TEMPLATE_HTML,%s) where ID = %s",
								"'" + template_html.substring(subNum * i, subLength) + "'",
								params.get(0));
						updateSqls.add(dhUpdateSql);
					}
				} else {
					updateSql = String.format("insert into %s(%s) values(%s)", tableName, Joiner.on(",").join(fields), Joiner.on(",").join(params));
					updateSqls.add(updateSql);
					if("portal_sys_column".equals(tableName)){//如果是首页栏目  设置默认权限
						String addAuthSql="INSERT INTO portal_sys_auth_user (id_, obj_type_, authorize_id_, right_type_, tenant_id_) VALUES ('"+UniqueIdUtil.getSuid()+"', 'indexColumn', "+params.get(0).toString()+", 'everyone', '"+tenantId+"')";
						updateSqls.add(addAuthSql);
					}
				}

			}
 			if(BeanUtils.isNotEmpty(updateSqls)&& updateSqls.size()>0){
 				// 分布式事务不支持多sql执行  ONLY SUPPORT SAME TYPE (UPDATE OR DELETE) MULTI SQL
 				for (String insertSql : updateSqls) {
 					jdbcTemplate.update(insertSql);
				}
// 				jdbcTemplate.batchUpdate(updateSqls.toArray(new String[updateSqls.size()]));
 			}
		}

	}

	
	public static String getCurrentTenantId(){
		BaseContext baseContext = AppUtil.getBean(BaseContext.class);
		return baseContext.getCurrentTenantId();
	}
	
	public static void clearTempTenantId(){
		BaseContext baseContext = AppUtil.getBean(BaseContext.class);
		baseContext.clearTempTenantId();
	}

}
