package com.bcxin.ars.rest;

import com.alibaba.fastjson.JSONArray;
import com.bcxin.ars.dto.AjaxResult;
import com.bcxin.ars.dto.OrganizationSAASDTO;
import com.bcxin.ars.dto.Tree;
import com.bcxin.ars.model.Organization;
import com.bcxin.ars.model.SecurityCompany;
import com.bcxin.ars.model.User;
import com.bcxin.ars.rest.util.ArsRestUtil;
import com.bcxin.ars.service.OrganizationService;
import com.bcxin.ars.service.SecurityCompanyService;
import com.bcxin.ars.service.SecurityPersonService;
import com.bcxin.ars.service.UserService;
import com.bcxin.ars.util.Constants;
import com.bcxin.ars.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("org")
public class OrganizationController {

	private Logger logger = LoggerFactory.getLogger(OrganizationController.class);

	@Autowired
	private OrganizationService orgService;

	@Autowired
	private SecurityCompanyService companyService;

	@Autowired
	private SecurityPersonService personService;

	@Autowired
	private UserService userService;

	@Autowired
	private ArsRestUtil arsUtil;

	/**
	 * 根据ID获取组织架构明细
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("detail")
	public @ResponseBody AjaxResult detail(Long id, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			Organization org = orgService.findById(id);
			result.setSuccessful(true);
			result.setData(org);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 获取当前登录安保公司的组织架构列表
	 * @param request
	 * @return
	 */
	@RequestMapping("getOrgList")
	public @ResponseBody AjaxResult getOrgList(HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User user = arsUtil.getCurrentUser();
			Long userid = user.getId();
			SecurityCompany company = null;
			if(user.getPlatform() == 1){
				String useridString = request.getParameter("userid");
				if(StringUtil.isNotEmpty(useridString)){
					userid = Long.parseLong(useridString);
					company = companyService.findByUserid(Long.parseLong(useridString));
				}
			}else if(user.getPlatform() == 2){
				company = companyService.findByUserid(userid);
			}

			if(company == null){
				result.setSuccessful(false);
			}else{
				List<Organization> orgList = orgService.findByCompany(company.getId());
//				if(orgList != null && orgList.size() > 0){
				List<Tree> trees = new ArrayList<Tree>();
				Tree tree = new Tree();
				tree.setExpanded(true);
				Integer count = 0 ;
				List<Tree> childrens = new ArrayList<Tree>();
				for (Organization organization : orgList) {
					organization.setCompanyId(company.getId());
					childrens.add(getTreeFormOrg(organization,count));
				}
				tree.setText(company.getName()+"("+(company.getSecurityAmount() == null ? 0:company.getSecurityAmount()) +")");
				tree.setChildren(childrens);
				trees.add(tree);
				result.setSuccessful(true);
				result.setData(trees);
				if(orgList != null && orgList.size() > 0){
					result.setSuccessful(true);
				}else{
					result.setSuccessful(false);
				}
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 创建或更新组织架构
	 * @param org	基本信息
	 * @param parentId	父机构ID
	 * @param request
	 * @return
	 */
	@RequestMapping(value="update", method=RequestMethod.POST)
	public @ResponseBody AjaxResult update(@NotNull Organization org, @RequestParam(value="parentId",required=false)Long parentId, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User user = arsUtil.getCurrentUser();
			SecurityCompany company = companyService.findByUserid(user.getId());
			if(company != null) {
				org.setCompany(company);
				if(parentId != null) {
					Organization parent = new Organization();
					parent.setId(parentId);
					org.setParent(parent);
				}
				orgService.saveOrUpdate(org);
				result.setSuccessful(true);
				result.setData(org.getId());
			} else {
				result.setSuccessful(false);
				result.setMsg("当前安保公司信息错误，Userid:" + user.getId());
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 批量创建或更新组织架构
	 * @param orgs	基本信息List
	 * @param orgs	父机构ID
	 * @param request
	 * @return
	 */
	@RequestMapping(value="updateBatch", method=RequestMethod.POST)
	public @ResponseBody AjaxResult updateBatch(String  orgs,  HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User user = arsUtil.getCurrentUser();
			SecurityCompany company = companyService.findByUserid(user.getId());
			if(company != null) {
			List<OrganizationSAASDTO> organizationSAASDTOList =JSONArray.parseArray(orgs,OrganizationSAASDTO.class);
				if (organizationSAASDTOList.size()>0) {
					orgService.saveOrUpdateBatch(organizationSAASDTOList, company);
				}else {
					result.setMsg("部门list为空" );
				}
				result.setSuccessful(true);
				result.setData(organizationSAASDTOList);
			} else {
				result.setSuccessful(false);
				result.setMsg("当前安保公司信息错误，Userid:" + user.getId());
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 删除组织架构
	 * @param org	基本信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="delete", method=RequestMethod.POST)
	public @ResponseBody AjaxResult delete(Organization org, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User user = arsUtil.getCurrentUser();
			if(user != null){
				orgService.delete(org);
				result.setSuccessful(true);
				result.setData(org.getId());
			} else {
				result.setSuccessful(false);
				result.setMsg("当前用户信息错误");
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	private Tree getTreeFormOrg(Organization org,Integer count){
		Tree tree = new Tree();
		tree.setId(org.getId()+"");
		List<Long> ids = getChildrenIds(org);
		ids.add(org.getId());
		org.setIds(ids);
		org.setNumber(orgService.queryCount(org).intValue());
		count += org.getNumber();
		tree.setText(org.getName()+"("+org.getNumber()+")");
		if(org.getChildren() != null && org.getChildren().size() > 0){
			List<Tree> childTrees = new ArrayList<Tree>();
			for(Organization childOrg:org.getChildren()){
				childOrg.setCompanyId(org.getCompanyId());
				childTrees.add(getTreeFormOrg(childOrg,count));
			}
			tree.setChildren(childTrees);
		}
		return tree;
	}

	/***
	 * 获取子节点的所有ID值
	 * @param org
	 * @return
	 */
	public static List<Long> getChildrenIds(Organization org){
		List<Long> result = new ArrayList<Long>();
		for (Organization temp :
				org.getChildren()) {
			result.add(temp.getId());
			if(temp.getChildren()!=null && temp.getChildren().size()>0){
				List<Long> ids = getChildrenIds(temp);

				for (Long id :
						ids) {
					result.add(id);
				}
			}
		}
		return result;
	}
	@RequestMapping("updateInitstep")
	public @ResponseBody AjaxResult updateInitstep() throws Exception{
		AjaxResult result = new AjaxResult();
		try {

			User currentUser = arsUtil.getCurrentUser();
			currentUser.setInitstep(Constants.INTISTEP_ORG);
			userService.updateInitstep(currentUser);
			result.setSuccessful(true);
		} catch(Exception e) {
			throw e;
		}
		return result;
	}

}
