package net.wicp.tams.duckula.ops.pages.devops;

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

import org.apache.commons.collections.CollectionUtils;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.util.TextStreamResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.app.duckula.controller.bean.constant.DorisRole;
import net.wicp.tams.app.duckula.controller.bean.models.DevopsDoris;
import net.wicp.tams.app.duckula.controller.bean.models.DevopsDorisExample;
import net.wicp.tams.app.duckula.controller.bean.models.DevopsDorisExample.Criteria;
import net.wicp.tams.app.duckula.controller.config.constant.DevOpsType;
import net.wicp.tams.app.duckula.controller.dao.DevopsDorisMapper;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.CollectionUtil;
import net.wicp.tams.common.apiext.IOUtil;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.constant.PathType;
import net.wicp.tams.common.constant.dic.YesOrNo;
import net.wicp.tams.common.os.SSHAssit;
import net.wicp.tams.common.os.pool.SSHConnection;
import net.wicp.tams.component.tools.TapestryAssist;
import net.wicp.tams.duckula.ops.pages.ParentPageBean;

@Slf4j
public class DorisConfig extends ParentPageBean<DevopsDoris> {

	@Inject
	private DevopsDorisMapper devopsDorisMapper;

	@Override
	public void doSave(DevopsDoris t, boolean isInsert) {
		// 由shell命令检查磁盘，程序不写
//		SSHConnection conn = SSHAssit.getConn(t.getIp(), "root", t.getRootPwd());
//		try {
//			List<DiskBean> list = conn.fdiskData();
//			Set<String> paths = CollectionUtil.getColSetFromObj(list, "path");
//			if (!paths.contains(t.getFs())) {
//				throw new ProjectExceptionRuntime(ExceptAll.param_error,
//						"存储磁盘不正确，只能填写：" + CollectionUtil.arrayJoin(paths.toArray(new String[paths.size()]), ","));
//			}
//		} finally {
//			SSHAssit.close(conn);
//		}
		if (isInsert) {
			t.setIsInit(YesOrNo.no.name());
			t.setIsInstall(YesOrNo.no.name());
			devopsDorisMapper.insert(t);
		} else {
			devopsDorisMapper.updateByPrimaryKeySelective(t);
		}
	}

	@Override
	public void doDel(String id) {
		this.devopsDorisMapper.deleteById(id);
	}

	@Override
	public BaseMapper<DevopsDoris> getBaseMapper() {
		return this.devopsDorisMapper;
	}

	@Override
	public void packageQuery(DevopsDoris t, QueryWrapper<DevopsDoris> queryWrapper) {
		if (StringUtil.isNotNull(t.getName())) {
			queryWrapper.eq("name", t.getName());
		}
		if (StringUtil.isNotNull(t.getIsInit())) {
			queryWrapper.eq("is_init", t.getIsInit());
		}
	}

	public TextStreamResponse onInstallHost() {
		final DevopsDoris devopsDoris = TapestryAssist.getBeanFromPage(DevopsDoris.class, requestGlobals);
		// List<DevopsDoris> list = queryHostByCluster(devopsDoris.getCluster());
		// 1、OSS下载
		String localPath = PathType.getPath(DevOpsType.doris.getInstallDownFile());
		// 1、登陆
		SSHConnection conn = SSHAssit.getConn(devopsDoris.getIp(), "root", devopsDoris.getRootPwd());
		try {
			String remoteDir = "~/doris/doris_setup";
			conn.executeCommand("mkdir -p " + remoteDir);
			Result result = conn.scpDir(localPath, remoteDir, "0744", new String[] {}, new String[] {});
			// 临时方案
			if (result.isSuc()) {
				devopsDoris.setIsInstall(YesOrNo.yes.name());
				devopsDorisMapper.updateByPrimaryKeySelective(devopsDoris);
				return TapestryAssist.getTextStreamResponse(
						Result.getError("由于doris需要很长下载时间 ，请移步到服务器执行：sh ~/doris/doris_setup/setup.sh 进行安装"));
			} else {
				return TapestryAssist.getTextStreamResponse(Result.getError(result.getMessage()));
			}
			// 执行
//			Result result = conn
//					.executeCommand(String.format("sh %s", IOUtil.mergeFolderAndFilePath(remoteDir, "setup.sh")));
//			log.info(result.getMessage());
//			if (result.isSuc()) {
//				devopsDoris.setIsInstall(YesOrNo.yes.name());
//				devopsDorisMapper.updateByPrimaryKeySelective(devopsDoris);
//				return TapestryAssist.getTextStreamResponse(Result.getSuc());
//			} else {
//				return TapestryAssist.getTextStreamResponse(Result.getError(result.getMessage()));
//			}
		} finally {
			SSHAssit.close(conn);
		}

	}

	/***
	 * <r:combobox id="groupIsEdit" name="isEdit" textField="name1" valueField=
	 * "name" url="/sys/OptionItemManager:list/YesOrNo" panelHeight="50" value=
	 * "literal:yes"/> 得到centos的磁盘。
	 * 
	 * @return
	 */
//	public TextStreamResponse onListFs() {
//		final DevopsDoris devopsDoris = TapestryAssist.getBeanFromPage(DevopsDoris.class, requestGlobals);
//		
//	}

	/***
	 * 测试用后端调用
	 * 
	 * @return
	 */
	public TextStreamResponse onCheckHost() {
		final DevopsDoris devopsDoris = TapestryAssist.getBeanFromPage(DevopsDoris.class, requestGlobals);
		List<DevopsDoris> list = queryHostByCluster(devopsDoris.getCluster());

		Map<DorisRole, Boolean> exit = DorisRole.isExit();
		for (DevopsDoris devopsDoris2 : list) {
			if (StringUtil.isNotNull(devopsDoris2.getRoles())) {
				String[] splits = devopsDoris2.getRoles().split(",");
				for (String split : splits) {
					if (exit.containsKey(DorisRole.valueOf(split))) {
						exit.put(DorisRole.valueOf(split), true);
					}
				}
			}
		}
		StringBuffer buff = new StringBuffer();
		for (DorisRole dorisRole : exit.keySet()) {
			if (!exit.get(dorisRole)) {
				buff.append("," + dorisRole.name());
			}
		}
		if (buff.length() > 0) {
			return TapestryAssist.getTextStreamResponse(Result.getError("下列角色需要配置：" + buff.substring(1)));
		}

		// 1、OSS下载
		String localPath = PathType.getPath(DevOpsType.doris.getCheckurl());
		// 1、登陆
		SSHConnection conn = SSHAssit.getConn(devopsDoris.getIp(), "root", devopsDoris.getRootPwd());
		try {
			String remoteDir = DevOpsType.doris.getRemoteDirCheckDir();
			conn.executeCommand("mkdir -p " + remoteDir);
			conn.scpToDir(localPath, remoteDir);
			// conn.scp(localPath, DevOpsType.doris.getRelaPathCheck(), "~", "0744");
			// echo 11441 > test 覆盖，echo 1234567 >> test追加 touch test 创建一个空文件
			String context = configContext(devopsDoris.getCluster());
			conn.executeCommand("echo -e \"" + context + "\" > "
					+ IOUtil.mergeFolderAndFilePath(DevOpsType.doris.getRemoteDirCheckDir(), "DorisIP.conf"));
			// 执行
			Result result = conn.executeCommand(
					String.format("sh %s", IOUtil.mergeFolderAndFilePath("~/", DevOpsType.doris.getRelaPathCheck())));
			log.info(result.getMessage());
			if (result.isSuc()) {
				// 检查完成，符合条件，可以开始安装部署Doris
				// 检查完成，当前环境不符合条件，无法安装Doirs需联络客户或者运维解决上述问
				if (result.getMessage().contains("检查完成，符合条件，可以开始安装部署Doris")) {
					devopsDoris.setIsInit(YesOrNo.yes.name());
					devopsDorisMapper.updateByPrimaryKeySelective(devopsDoris);
				}
				return TapestryAssist.getTextStreamResponse(Result.getError(result.getMessage()));

			} else {
				return TapestryAssist.getTextStreamResponse(Result.getError(result.getMessage()));
			}
		} finally {
			SSHAssit.close(conn);
		}
	}

	public String configContext(String cluster) {
		List<DevopsDoris> list = queryHostByCluster(cluster);
		Map<DorisRole, List<String>> retmap = new HashMap<DorisRole, List<String>>();
		for (DevopsDoris ele : list) {
			String[] rolesStr = ele.getRoles().split(",", 0);
			for (String roleStr : rolesStr) {
				DorisRole temp = DorisRole.valueOf(roleStr);
				List<String> list2 = retmap.get(temp);
				if (CollectionUtils.isEmpty(list2)) {
					list2 = new ArrayList<String>();
				}
				list2.add(ele.getIp());
				retmap.put(temp, list2);
			}
		}
		// 添加不设置的角色
		for (DorisRole dorisRole : DorisRole.values()) {
			if (!retmap.containsKey(dorisRole)) {
				retmap.put(dorisRole, new ArrayList<String>());
			}
		}
		StringBuffer buff = new StringBuffer();
		for (DorisRole dorisRole : retmap.keySet()) {
			buff.append(String.format("\n%s,%s", dorisRole.name(),
					StringUtil.hasNull(CollectionUtil.listJoin(retmap.get(dorisRole), ","), "")));
		}
		return buff.substring(1);
	}

	// 不排序是以id顺序
	private List<DevopsDoris> queryHostByCluster(String cluster) {
		DevopsDorisExample example = new DevopsDorisExample();
		Criteria criteria = example.createCriteria();
		criteria.andClusterEqualTo(cluster);
		List<DevopsDoris> list = devopsDorisMapper.selectByExample(example);
		return list;
	}

}
