package com.cim.idm.controller;

import com.alibaba.fastjson.JSON;
import com.cim.idm.exception.GlobalException;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.model.CommonObject;
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.QueryService;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.Constant;
import com.cim.idm.utils.SessionManager;
import com.cim.idm.utils.TokenManager;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@EnableAutoConfiguration
@RequestMapping("/login")
@Slf4j
@Api(tags = "登录接口", description = "登录接口")
public class LoginController {


	@Autowired
	private TokenManager tokenManager;

	@Autowired
	private UserProfileServiceUtil userProfileServiceUtil;

	@Autowired
	private UserProfileServiceImpl userProfileServiceImpl;

	@Autowired
	private QueryService queryService;

	@Autowired
	private SessionManager sessionService;

	@RequestMapping(value = "/LoginCheck", method = RequestMethod.POST)
	@ApiOperation(value = "用户登录", notes = "处理用户的登录请求并返回token")
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "成功响应", response = ApiResponse.class),
			@ApiResponse(code = 400, message = "请求参数错误"),
			@ApiResponse(code = 500, message = "服务器内部错误")
	})
	public ResponseEntity<BaseResponse<String>> loginCheck(HttpServletRequest request,
														   HttpServletResponse response,
														   @ApiParam(value = "登录参数", required = true) @RequestBody CommonObject param) {
		BaseResponse<String> apiResponse = new BaseResponse<>();
		try {
			log.info("开始处理登录请求, 参数: {}", param.getParams());
			String params = param.getParams();
			JSONObject jsonObject = new JSONObject(params);
			String userId = jsonObject.getString("userId");
			String password = jsonObject.getString("password");
			String uiName = jsonObject.getString("siteName");
			String orgNo = jsonObject.getString("orgNo");
			if (userId == null || password == null) {
				apiResponse.setStatus(Constant.RESPONSE_STATUS_FAIL);
				apiResponse.setMessage("用户名或密码为空");
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(apiResponse);
			}
			String username = userId; // 示例用户名
			String siteName = uiName;
			userProfileServiceImpl.login(username, password, siteName, siteName);
			String userInfo = userProfileServiceUtil.getUserInfo(username);
			if (userInfo == null || userInfo.equals("")) {
				apiResponse.setStatus(Constant.RESPONSE_STATUS_FAIL);
				apiResponse.setMessage("用户名或密码错误");
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(apiResponse);
			}
			//判断组织是否正确|拥有组织权限
			// 判断是否有组织权限
			if(!userProfileServiceImpl.orgPermission(userId, password, orgNo)) {
				BaseResponse returnError = RespGenerator.returnError("选择的组织没有权限!");
				log.error("选择的组织没有权限!");
				apiResponse.setStatus(Constant.RESPONSE_STATUS_FAIL);
				apiResponse.setMessage("选择的组织没有权限!");
				return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(apiResponse);
			}
			Map<String, Object> bindMap =  new HashMap<String, Object>() {{
				put("USERID", username);
			}};
//			List<Map<String, Object>> getMenuList = queryService.getQueryResult("GetPDAMenuList", "10001", bindMap);
			//获取菜单列表
			JSONArray menuList = new JSONArray();

			String token = tokenManager.generateToken();
			//获取session
			String session = sessionService.setSession(username, siteName, token);

			apiResponse.setStatus(Constant.RESPONSE_STATUS_SUCCESS);

			//添加session到返回报文
			apiResponse.setData(String.format("{\"SITENAME\":\"%s\",\"USERNAME\":\"%s\",\"token\":\"%s\",\"session\":\"%s\",\"menuList\":\"%s\"}", siteName, username, token,session,menuList));
			apiResponse.setMessage("登录成功");

			return ResponseEntity.ok(apiResponse);
		} catch (Exception e) {
			log.error("登录失败: {}", e.getMessage(), e);
			apiResponse.setStatus(Constant.RESPONSE_STATUS_FAIL);
			apiResponse.setMessage("登录失败");
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(apiResponse);
		}
	}


	@RequestMapping(value = "/getORG", method = RequestMethod.POST)
	@ApiOperation(value = "获取组织信息", notes = "获取组织信息")
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "成功响应", response = AjaxResult.class),
			@ApiResponse(code = 400, message = "请求参数错误"),
			@ApiResponse(code = 500, message = "服务器内部错误")
	})
	public AjaxResult getORG(@RequestBody com.alibaba.fastjson.JSONObject in ){
		log.info("获取组织信息 {}", in);
		String sql = "SELECT T.ORGNO ERPFACTORY,T.ORGNAME DESCRIPTION FROM ORG T   ORDER BY T.ORGNO";

		Map<String, Object> bindMap = new HashMap<String, Object>();
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);

		if(Objects.isNull(list) || list.isEmpty()) {
			throw new GlobalException("未找到组织信息！");
		}
		return AjaxResult.me().setResultObj(list);

	}
}
