package datasync.client;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import datasync.common.ResultJavaEntity;
import datasync.model.GradeJavaModel;
import datasync.model.GroupMapJavaModel;
import datasync.model.OuInfoJavaModel;
import datasync.model.PositionJavaModel;
import datasync.model.UserInfoJavaModel;
import datasync.service.SyncOrgJavaService;
import datasync.service.SyncPositionJavaService;
import datasync.service.SyncUserJavaService;

public class JavaDemoTest implements JavaConfig {
	static String connectionUrl = "jdbc:sqlserver://120.79.0.56:6004;database=ZTHR;user=sa;password=Essen999;";
	/**
	 * Development
	 */
	static String apikey = "b596e7ed-7f23-4387-8d00-18a16f05ed56";
	static String secretkey = "a9433f89-37ff-43c8-84c2-fd855dc0106e";
	static String baseUrl = "http://api-udp-adel.yunxuetang.com.cn/v1/";

	public static void main(String[] args) throws IOException {
		if (args.length > 0) {
			System.out.println(args.length);
			connectionUrl = args[0];
			if (args.length > 2 && "official".equals(args[1])) {
				/**
				 * Official
				 */
				apikey = "bf3552c7-a0af-497d-8c11-6005dfb299ee";
				secretkey = "2db4a86a-0a5e-44e4-8402-978e16274356";
				baseUrl = "https://api-qidac1.yunxuetang.cn/v1/";

			}

		}
		System.out.println("----- Environment -----");
		System.out.println("connectionUrl :: " + connectionUrl);
		System.out.println("baseUrl :: " + baseUrl);
		System.out.println("apikey :: " + apikey);
		System.out.println("secretkey :: " + secretkey);

		new JavaDemoTest();
	}

	public JavaDemoTest() throws IOException {

		ResultSet resultSet = null;

		try (Connection connection = DriverManager.getConnection(connectionUrl);
				Statement statement = connection.createStatement();) {
			System.out.println("----- Sync Orgs -----");
			List<OuInfoJavaModel> orgs = new ArrayList<OuInfoJavaModel>();
			OuInfoJavaModel org = new OuInfoJavaModel();

			String selectSql = "select Depcode,Title,'0' as AdminCode\r\n" + "from oDepartment\r\n"
					+ "where AdminId is null and isDisabled  is  null\r\n" + "UNION\r\n"
					+ "select a.Depcode,a.Title,b.depcode as AdminCode\r\n" + "from \r\n"
					+ "(select DepCode,Title,AdminID\r\n" + "from oDepartment\r\n"
					+ "where AdminId is not null and isDisabled  is  null) a \r\n"
					+ "left join oDepartment b on a.adminid=b.depId";
//			System.out.println("selectSql : "+selectSql);
			resultSet = statement.executeQuery(selectSql);

			// Print results from select statement
			while (resultSet.next()) {
//				System.out.println(resultSet.getString(1)+" , "+resultSet.getString(2)+" , "+resultSet.getString(3));
				org = new OuInfoJavaModel();
				org.setId(resultSet.getString(1));
				org.setOuName(resultSet.getString(2));
				if ("0".equals(resultSet.getString(3)) || null == resultSet.getString(3))
					org.setParentId("");
				else
					org.setParentId(resultSet.getString(3));
				orgs.add(org);
			}
			syncOUs(orgs);
			System.out.println("----- Sync User -----");
			// Create and execute a SELECT SQL statement.
			selectSql = "select c.badge,SUBSTRING(email,1, CHARINDEX('@', email) - 1) username,c.name,c.Depcode\r\n"
					+ "from\r\n" + "(select a.*,b.DepAbbr,b.Depcode\r\n" + "from eemployee a , oDepartment b\r\n"
					+ "where  \r\n" + "a.depid = b.depid and a.empstatus=1 and a.email is not null) c ";
			resultSet = statement.executeQuery(selectSql);
			List<UserInfoJavaModel> users = new ArrayList<UserInfoJavaModel>();
			List<String> usernames = new ArrayList<String>();
			UserInfoJavaModel user = new UserInfoJavaModel();
			// Print results from select statement
			while (resultSet.next()) {
//				System.out.println(resultSet.getString(1)+" , "+resultSet.getString(2)+" , "+resultSet.getString(3)+" , "+resultSet.getString(4));
				// 根据id改username可以，根据username改id不可以（id为空时可以）
				user = new UserInfoJavaModel();
				user.setId(resultSet.getString(1));
				user.setUserName(resultSet.getString(2));
				user.setCnName(resultSet.getString(3));
				user.setOrgOuCode(resultSet.getString(4));
				users.add(user);
				usernames.add(resultSet.getString(2));
			}
			int size = users.size();
			System.out.println("Size: " + size);
			for (int i = 0; i < size / 100 + 1; i++) {
				int from = i * 100, to = (i + 1) * 100;
				if (i == size / 100)
					to = size;
				List<UserInfoJavaModel> partUsers = users.subList(from, to);
				List<String> partUN = usernames.subList(from, to);
				System.out.println("Synced from " + from + " to " + to);
				syncUsers(partUsers);
				syncEnableUsers(partUN);
				System.out.println("================");
			}

			System.out.println("----- Sync Deleted User -----");
			// Create and execute a SELECT SQL statement.
			selectSql = "select c.badge,SUBSTRING(email,1, CHARINDEX('@', email) - 1) username,c.name,c.Depcode\r\n"
					+ "from\r\n" + "(select a.*,b.DepAbbr,b.Depcode\r\n" + "from eemployee a , oDepartment b\r\n"
					+ "where  \r\n" + "a.depid = b.depid and a.empstatus=2 and a.email is not null) c ";
			resultSet = statement.executeQuery(selectSql);
			usernames = new ArrayList<String>();
			// Print results from select statement
			while (resultSet.next()) {
//				System.out.println(resultSet.getString(2) + " , " + resultSet.getString(3));
				usernames.add(resultSet.getString(2));
			}
			syncDeletedUsers(usernames);
			System.out.println("----- Sync Deleted Orgs -----");
			List<String> ouCodes = new ArrayList<String>();

			selectSql = "select Depcode,Title,'0' as AdminCode\r\n" + "from oDepartment\r\n"
					+ "where AdminId is null and isDisabled  is not null\r\n" + "UNION\r\n"
					+ "select a.Depcode,a.Title,b.depcode as AdminCode\r\n" + "from \r\n"
					+ "(select DepCode,Title,AdminID\r\n" + "from oDepartment\r\n"
					+ "where AdminId is null and isDisabled  is not null) a \r\n"
					+ "left join oDepartment b on a.adminid=b.depId";
			resultSet = statement.executeQuery(selectSql);

			// Print results from select statement
			while (resultSet.next()) {
				ouCodes.add(resultSet.getString(1));

			}
			for (String model : ouCodes) {
				System.out.println(model);
			}
			syncDeletedOUs(ouCodes);

		} catch (SQLException e) {
			e.printStackTrace();
		}

		// 同步组织单位:
//        ousTest();

		// 同步删除组织单位:
//        deleteousTest();

		// 将用户从组织单位中移除
//        removeusersfromouTest();

		// 将一批用户移动至新部门
//        batchchangeorgouTest();

		// 同步设置部门主管
//        setmanagerTest();

		// 同步用户
//        usersTest();

		// 同步禁用用户
//        disabledusersTest();

		// 同步启用用户
//        enabledusersTest();

		// 同步校验用户是否存在
//        checkusersTest();

		// 同步角色删除人员
//        roledeleteuserTest();

		// 同步角色增加人员
//        roleadduserTest();

		// 自动建用户组
//        groupaddTest();

		// 用户组添加人员
//        groupMapAddTest();

		// 用户组删除人员
//        groupMapDelTest();

		// 同步增加直属经理
//        addmgrTest();

		// 同步更新直属经理
//        updmgrTest();

		// 同步删除直属经理
//        delmgrTest();

		// 同步岗位
//        positionTest();

		// 同步职级
//        updategradeTest();

		// 同步更改岗位名称
//        updatePositionInfoTest();

		// 更新用户Job名称
//        updateUserJobTest();

		// 查询岗位编号
//        getPnoByPnameTest();
	}

	private void syncEnableUsers(List<String> usernames) throws IOException {
		usernames.remove(null);
		SyncUserJavaService service = new SyncUserJavaService();
		ResultJavaEntity result = service.enabledusers(usernames, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	private void syncDeletedUsers(List<String> usernames) throws IOException {
		SyncUserJavaService service = new SyncUserJavaService();
		ResultJavaEntity result = service.disabledusers(usernames, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	private void syncDeletedOUs(List<String> ouCodes) throws IOException {
		SyncOrgJavaService service = new SyncOrgJavaService();
		ResultJavaEntity result = service.deleteous(ouCodes, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	/**
	 * 組織同步
	 * 
	 * @param orgs
	 * @throws IOException
	 */
	void syncOUs(List<OuInfoJavaModel> orgs) throws IOException {
		SyncOrgJavaService service = new SyncOrgJavaService();
		ResultJavaEntity result = service.ous(1, orgs, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void ousTest() throws IOException {
		SyncOrgJavaService service = new SyncOrgJavaService();
		List<OuInfoJavaModel> orgs = new ArrayList<OuInfoJavaModel>();
		OuInfoJavaModel org = new OuInfoJavaModel();
		org = new OuInfoJavaModel();
		org.setId("000001");
		org.setOuName("公司领导");
		org.setParentId("");
		orgs.add(org);

		ResultJavaEntity result = service.ous(1, orgs, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void deleteousTest() throws IOException {
		SyncOrgJavaService service = new SyncOrgJavaService();
		List<String> ouCodes = new ArrayList<>();
		ouCodes.add("");
		ResultJavaEntity result = service.deleteous(ouCodes, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void removeusersfromouTest() throws IOException {
		SyncOrgJavaService service = new SyncOrgJavaService();
		List<String> userNames = new ArrayList<String>();
		userNames.add("");
		ResultJavaEntity result = service.removeusersfromou(userNames, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void batchchangeorgouTest() throws IOException {
		SyncOrgJavaService service = new SyncOrgJavaService();
		List<String> userNames = new ArrayList<String>();
		userNames.add("user01");
		String ouCode = "1111";
		ResultJavaEntity result = service.batchchangeorgou(userNames, ouCode, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void setmanagerTest() throws IOException {
		SyncOrgJavaService service = new SyncOrgJavaService();
		// id或username都可以
		String userName = "";
		String ouCode = "";
		int isCancelManager = 1;
		ResultJavaEntity result = service.setmanager(userName, ouCode, isCancelManager, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void createusersTest() throws IOException {
		// 只能新增不能更新
		SyncUserJavaService service = new SyncUserJavaService();
		List<UserInfoJavaModel> users = new ArrayList<UserInfoJavaModel>();
		UserInfoJavaModel user = new UserInfoJavaModel();
		user.setId("");
		user.setUserName("");
		user.setCnName("");
		users.add(user);
		ResultJavaEntity result = service.createusers(1, users, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	/**
	 * 同步用戶
	 * 
	 * @param users
	 * @throws IOException
	 */
	void syncUsers(List<UserInfoJavaModel> users) throws IOException {
		// 能新增能更新
		SyncUserJavaService service = new SyncUserJavaService();
		ResultJavaEntity result = service.users(1, users, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	// 根据id改username可以，根据username改id不可以（id为空时可以）
	void usersTest() throws IOException {
		// 能新增能更新
		SyncUserJavaService service = new SyncUserJavaService();
		List<UserInfoJavaModel> users = new ArrayList<UserInfoJavaModel>();
		UserInfoJavaModel user = new UserInfoJavaModel();
		// 根据id改username可以，根据username改id不可以（id为空时可以）
		user = new UserInfoJavaModel();
		user.setId("00321");
		user.setUserName("jasonchen");
		user.setCnName("陳俊宏");
		user.setOrgOuCode("000048");
		users.add(user);

		ResultJavaEntity result = service.users(1, users, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void disabledusersTest() throws IOException {
		SyncUserJavaService service = new SyncUserJavaService();
		List<String> userNames = new ArrayList<String>();
		// id或username都可以
		userNames.add("");
		ResultJavaEntity result = service.disabledusers(userNames, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void enabledusersTest() throws IOException {
		SyncUserJavaService service = new SyncUserJavaService();
		List<String> userNames = new ArrayList<String>();
		// id或username都可以
		userNames.add("shidong.fang");
		ResultJavaEntity result = service.enabledusers(userNames, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void checkusersTest() throws IOException {
		SyncUserJavaService service = new SyncUserJavaService();
		List<String> userNames = new ArrayList<String>();
		userNames.add("user01");
		ResultJavaEntity result = service.checkusers(userNames, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void roledeleteuserTest() throws IOException {
		SyncUserJavaService service = new SyncUserJavaService();
		List<String> userNames = new ArrayList<String>();
		// id或username都可以
		userNames.add("");
		String roleNo = "";
		ResultJavaEntity result = service.roledeleteuser(userNames, roleNo, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void roleadduserTest() throws IOException {
		SyncUserJavaService service = new SyncUserJavaService();
		List<String> userNames = new ArrayList<String>();
		// id或username都可以
		userNames.add("");
		String roleNo = "";
		ResultJavaEntity result = service.roleadduser(userNames, roleNo, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void groupaddTest() throws IOException {
		SyncUserJavaService service = new SyncUserJavaService();
		List<GroupMapJavaModel> groupMaps = new ArrayList<GroupMapJavaModel>();
		String groupName = "";
		String remark = "";
		GroupMapJavaModel groupMap = new GroupMapJavaModel();
		groupMap.setMasterNo("");
		groupMap.setMasterType("");
		groupMaps.add(groupMap);
		ResultJavaEntity result = service.groupadd(groupMaps, groupName, remark, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void groupMapAddTest() throws IOException {
		SyncUserJavaService service = new SyncUserJavaService();
		List<String> masterNos = new ArrayList<String>();
		// 人员传id，用户组id是主键id
		masterNos.add("");
		String groupId = "";
		String mapType = "";
		ResultJavaEntity result = service.groupMapAdd(masterNos, groupId, mapType, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void groupMapDelTest() throws IOException {
		SyncUserJavaService service = new SyncUserJavaService();
		List<String> masterNos = new ArrayList<String>();
		// 人员传id，用户组id是主键id
		masterNos.add("");
		String groupId = "";
		String mapType = "";
		ResultJavaEntity result = service.groupMapDel(masterNos, groupId, mapType, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void addmgrTest() throws IOException {
		SyncUserJavaService service = new SyncUserJavaService();
		List<UserInfoJavaModel> users = new ArrayList<UserInfoJavaModel>();
		UserInfoJavaModel user = new UserInfoJavaModel();
		// 员工和经理都传id
		user.setId("");
		user.setManagerNo("");
		users.add(user);
		ResultJavaEntity result = service.addmgr(users, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void updmgrTest() throws IOException {
		SyncUserJavaService service = new SyncUserJavaService();
		List<UserInfoJavaModel> users = new ArrayList<UserInfoJavaModel>();
		UserInfoJavaModel user = new UserInfoJavaModel();
		// 员工和经理都传id
		user.setId("");
		user.setManagerNo("");
		users.add(user);
		ResultJavaEntity result = service.updmgr(users, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void delmgrTest() throws IOException {
		SyncUserJavaService service = new SyncUserJavaService();
		List<String> users = new ArrayList<String>();
		// 员工传id
		users.add("");
		ResultJavaEntity result = service.delmgr(users, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void positionTest() throws IOException {
		SyncPositionJavaService service = new SyncPositionJavaService();
		List<PositionJavaModel> positions = new ArrayList<PositionJavaModel>();
		PositionJavaModel position = new PositionJavaModel();
		position.setpNo("");
		position.setpNames("");
		positions.add(position);
		ResultJavaEntity result = service.position(positions, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void updategradeTest() throws IOException {
		SyncPositionJavaService service = new SyncPositionJavaService();
		List<GradeJavaModel> grades = new ArrayList<GradeJavaModel>();
		GradeJavaModel grade = new GradeJavaModel();
		grade.setId("");
		grade.setName("");
		grades.add(grade);
		ResultJavaEntity result = service.updategrade(grades, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void updatePositionInfoTest() throws IOException {
		SyncPositionJavaService service = new SyncPositionJavaService();
		String positionNo = "";
		// 不带分类
		String positionName = "";
		ResultJavaEntity result = service.updatePositionInfo(positionNo, positionName, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

	void getPnoByPnameTest() throws IOException {
		SyncPositionJavaService service = new SyncPositionJavaService();
		// 需带分类
		String positionName = "";
		ResultJavaEntity result = service.getPnoByPname(positionName, apikey, secretkey, baseUrl);
		System.out.println(result);
	}

}
