package com.cim.idm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cim.idm.framework.IDMFrameServiceProxy;

import com.cim.idm.mwmsextend.userprofile.service.UserProfileServiceImpl;
import com.cim.idm.mwmsextend.userprofile.service.UserProfileServiceUtil;
import com.cim.idm.response.BaseResponse;
import com.cim.idm.response.RespGenerator;
import com.cim.idm.service.Impl.QueryServiceImpl;
import com.cim.idm.utils.PageResult;
import com.cim.idm.wmspackage.user.management.data.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {


	@Autowired
	private UserProfileServiceImpl userProfileServiceImpl;

	@Autowired
	private QueryServiceImpl queryServiceImpl;

    
	@RequestMapping(value = "/getUser", method = RequestMethod.POST)
	public BaseResponse<Map<String, Object>> getUser(@RequestBody Map<String,Object> param)
	{
		PageResult<Map<String,Object>> mapList = new PageResult<Map<String,Object>>();
		String queryId = param.get("queryId").toString();
		String version = param.get("version").toString();
		int pageNum = (int) param.get("pageNum");
		int pageSize = (int) param.get("pageSize");
		Map bindMap = (Map) param.get("params");
		JSONObject head = new JSONObject(true);
		try {
			mapList = queryServiceImpl.getQueryResultPage(queryId, version, bindMap, pageNum, pageSize);
			head.put("userList", mapList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		BaseResponse returnOK = RespGenerator.returnOK(head);
        return returnOK;
	}
	
	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	public BaseResponse<Map<String, Object>> addUser(@RequestBody Map<String,Object> param){
		
		String userId = (String)param.get("userId");
		String username = (String)param.get("username");
		String password = (String)param.get("password");
		String siteName = (String)param.get("siteName");
		String userGroupName = (String)param.get("userGroupName");
		String localeName = (String)param.get("localeName");
		String email = (String)param.get("email");
		String defaultFactoryName = (String)param.get("defaultFactoryName");
		String defaultAreaName = (String)param.get("defaultAreaName");
		String department = (String)param.get("department");
		String remark = (String)param.get("remark");
		String phoneNumber = (String)param.get("phoneNumber");
		String accessFactory = (String)param.get("accessFactory");
		String receiveFlag = (String)param.get("receiveFlag");
		
		String checkDuplicateSql = "SELECT COUNT(*) FROM USERINFO WHERE USERID = ?";
		Long count = IDMFrameServiceProxy.getSqlTemplate().queryForObject(checkDuplicateSql, Long.class, userId);
		if(count > 0) {
			BaseResponse returnError = RespGenerator.returnError("该账号已存在!");
			return returnError;
		}
		//密码加密
		password = userProfileServiceImpl.encryptPassword(password);
		String sql = "INSERT INTO USERINFO (USERID, USERNAME, PASSWORD, SITENAME, USERGROUPNAME, LOCALENAME, " +  
                "EMAIL, DEFAULTFACTORYNAME, DEFAULTAREANAME, DEPARTMENT, REMARK, PHONENUMBER, ACCESSFACTORY, RECEIVEFLAG) " +  
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";  

		Object[] args = new Object[]{userId, username, password, siteName, userGroupName, localeName, email,   
				defaultFactoryName, defaultAreaName, department, remark, phoneNumber,accessFactory,receiveFlag};  

		IDMFrameServiceProxy.getSqlTemplate().update(sql, args);
		BaseResponse returnOK = RespGenerator.returnOK(param);
        return returnOK;

	}
	
	@RequestMapping(value = "/saveUserRole", method = RequestMethod.POST)
	public BaseResponse<Map<String, Object>> saveRoleMenu(@RequestBody Map<String,Object> param){
				
		String userId = (String)param.get("userId");
		String userGroupNames = (String)param.get("userGroupNames");
		
		String sql1 = "UPDATE USERINFO SET USERGROUPNAME = ? WHERE USERID = ?";  
		Object[] args1 = new Object[]{userGroupNames, userId};  
		IDMFrameServiceProxy.getSqlTemplate().update(sql1, args1);
		
		
		List<String> usergroupList = Arrays.asList(userGroupNames.split(","));
		String deleteSql = "DELETE FROM USERGROUPLINK WHERE USERID = ?";
		IDMFrameServiceProxy.getSqlTemplate().update(deleteSql, userId);
		
		for(Object userGroupName : usergroupList) {
			String sql2 = "INSERT INTO USERGROUPLINK (USERGROUPNAME, USERID) " +  "VALUES (?, ?)";  
			Object[] args2 = new Object[]{userGroupName, userId};  
			IDMFrameServiceProxy.getSqlTemplate().update(sql2, args2);
		}


		BaseResponse returnOK = RespGenerator.returnOK(param);
        return returnOK;

	}
	
	@RequestMapping(value = "/editUser", method = RequestMethod.POST)
	public BaseResponse<Map<String, Object>> editUser(@RequestBody Map<String,Object> param){
		
		String userId = (String)param.get("userId");
		String username = (String)param.get("username");
		String password = (String)param.get("password");
		String siteName = (String)param.get("siteName");
		String userGroupName = (String)param.get("userGroupName");
		String localeName = (String)param.get("localeName");
		String email = (String)param.get("email");
		String defaultFactoryName = (String)param.get("defaultFactoryName");
		String defaultAreaName = (String)param.get("defaultAreaName");
		String department = (String)param.get("department");
		String remark = (String)param.get("remark");
		String phoneNumber = (String)param.get("phoneNumber");
		String accessFactory = (String)param.get("accessFactory");
		String receiveFlag = (String)param.get("receiveFlag");
		//密码加密
		password = userProfileServiceImpl.encryptPassword(password);
		String sql = "UPDATE USERINFO " +  
	             "SET USERNAME = ?, PASSWORD = ?, SITENAME = ?, USERGROUPNAME = ?, LOCALENAME = ?, " +  
	             "EMAIL = ?, DEFAULTFACTORYNAME = ?, DEFAULTAREANAME = ?, DEPARTMENT = ?, " +  
	             "REMARK = ?, PHONENUMBER = ?, ACCESSFACTORY = ?, RECEIVEFLAG = ? " +  
	             "WHERE USERID = ?";  
	  
		Object[] args = new Object[]{  
		    username, password, siteName, userGroupName, localeName, email,  
		    defaultFactoryName, defaultAreaName, department, remark,  
		    phoneNumber, accessFactory, receiveFlag, userId  
		};
		
		IDMFrameServiceProxy.getSqlTemplate().update(sql, args);
		BaseResponse returnOK = RespGenerator.returnOK(param);
        return returnOK;
        
	}
	
	@RequestMapping(value = "/changePassword", method = RequestMethod.POST)
	public BaseResponse<Map<String, Object>> changePassword(@RequestBody Map<String,Object> param){
		
		String userId = (String)param.get("userId");
		String oldPassword = (String)param.get("oldPassword");
		String newPassword = (String)param.get("newPassword");
	
		String verifyPasswordSql = "SELECT COUNT(*) FROM USERINFO WHERE USERID = ? AND PASSWORD = ?";
		Long count = IDMFrameServiceProxy.getSqlTemplate().queryForObject(verifyPasswordSql, Long.class, userId, oldPassword);
		
		if(count == 0) {
			BaseResponse returnError = RespGenerator.returnError("原密码输入错误!");
			return returnError;
		}
		
		String sql = "UPDATE USERINFO SET PASSWORD = ? WHERE USERID = ?";
		Object[] args = new Object[]{ newPassword, userId };
		IDMFrameServiceProxy.getSqlTemplate().update(sql, args);
		BaseResponse returnOK = RespGenerator.returnOK(param);
        return returnOK;
	}

	
	@RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
	public BaseResponse<Map<String, Object>> deleteUser(@RequestBody Map<String,Object> param)
	{
		IDMFrameServiceProxy.getTransactionManager().beginTransaction();
		try {
			String userId = (String)param.get("userId");
			String sql1 = "DELETE FROM USERINFO WHERE USERID = ?";
			IDMFrameServiceProxy.getSqlTemplate().update(sql1, userId);

			String sql2 = "DELETE FROM USERGROUPLINK WHERE USERID = ?";
			IDMFrameServiceProxy.getSqlTemplate().update(sql2, userId);
			IDMFrameServiceProxy.getTransactionManager().commitTransaction();
		}catch(Exception e) {
			IDMFrameServiceProxy.getTransactionManager().rollbackTransaction();
		}
		
		
		BaseResponse returnOK = RespGenerator.returnOK(param);
        return returnOK;
	}

}
