package com.fourdage.base.controller;

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

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fourdage.base.common.HttpHelper;
import com.fourdage.dingding.entity.Department;
import com.fourdage.dingding.service.IDepartmentService;
import com.fourdage.dingding.util.DingDingUtil;
import com.fourdage.system.entity.User;

@Controller
public class LoginController extends BaseController {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private DingDingUtil dingDingUtil;
	@Autowired
	private IDepartmentService departmentService;
	
    @RequestMapping(value = {"/admin/login"}, method = RequestMethod.GET)
    public String login() {
        return "admin/login";
    }

    @RequestMapping(value = {"/admin/login"}, method = RequestMethod.POST)
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        ModelMap model) {
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
            
            logger.info("获取钉钉部门和用户信息");
            try {
            	String region = dingDingUtil.getRegion();
    			Map<String, Object> param = new HashMap<String, Object>();
    			param.put("access_token", dingDingUtil.getAccessToken());
    			
    			String resultStr = HttpHelper.sendGetByUrlConnection("https://oapi.dingtalk.com/department/list", param, "UTF-8");
    			JSONObject resultStrObject = JSON.parseObject(resultStr);
    			JSONArray arr = resultStrObject.getJSONArray("department");
    			if (arr != null && arr.size() > 0){
    				for (Object object : arr){
    					JSONObject jobj = (JSONObject)object;
    					
    					List<Department> depts = departmentService.findByDeptId(jobj.getString("id"));
    					if (depts != null && depts.size() > 0){
    						Department update = depts.get(0);
    						update.setDeptName(jobj.getString("name"));
    						update.setParentId(jobj.getString("parentid"));
    						departmentService.update(update);
    					}else{
    						Department insert = new Department();
    						insert.setDeptId(jobj.getString("id"));
    						insert.setDeptName(jobj.getString("name"));
    						insert.setRegion(region);
    						insert.setParentId(jobj.getString("parentid"));
    						insert.setRecStatus("A");
    						departmentService.save(insert);
    					}
    				}
    			}
            } catch (Exception e) {
            	logger.error("系统异常：", e);
            }
            return redirect("/admin/index");
        } catch (AuthenticationException e) {
            model.put("message", e.getMessage());
        }
        return "admin/login";
    }

    @RequestMapping(value = {"/admin/logout"}, method = RequestMethod.GET)
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return redirect("admin/login");
    }

}
