package com.ssj.sys.controller;

import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.sys.organization.domain.Organization;
import com.ssj.bean.sys.role.domain.Admin;
import com.ssj.bean.sys.role.domain.AdminOrg;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.sales.domain.LibStaffing;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.service.sys.organization.service.OrganizationService;
import com.ssj.service.sys.role.service.AdminOrgService;
import com.ssj.service.sys.role.service.AdminService;
import com.ssj.service.sys.sort.service.SortService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import com.ssj.service.weixin.sales.service.LibStaffingService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.Now;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 java.util.*;

/** 
 * @author  ZhangCaibao 
 * @version 2017年4月14日 下午2:49:49 
 * 类说明 
 */
@RequestMapping("sys/org")
@Controller
public class OrganizationController  extends BaseController {
  @Autowired
	private OrganizationService organizationService;
    
  @Autowired
	 private LibStaffingService libStaffingService;
	 
  @Autowired
	 private SortService sortService;

  @Autowired
  private AdminOrgService adminOrgService;

  @Autowired
  private AdminService adminService;

  @Autowired
  private ILibJoinService joinService;
	 
    /**
     * 栏目主页面
     * @return
     */
    @RequestMapping("/main")
    public String main() {
        return "sys/org/main";
    }
    /**
     * 栏目树
     * @param
     * @return
     * @throws Exception 
     */
    @RequestMapping("/tree")
    @ResponseBody
    public List<Organization> tree(@RequestParam(required = false, value = "id") String pId) throws Exception {
    	if(pId ==null) {
    		pId="-1";
    	}
    	return organizationService.getPidAndCodes(pId,orgcodeList());
    }
    @RequestMapping("/maintree")
    @ResponseBody
    public List<Organization> maintree(@RequestParam(required = false, value = "id") String pId) throws Exception {
    	if(pId ==null) {
    		pId="-1";
    	}
    	return organizationService.findByPid(pId);
    }
    @RequestMapping("/query")
    @ResponseBody
    public List<Organization> query() throws Exception {
    	Admin admin = (Admin)request.getSession().getAttribute("admin");
    	if("admin".equals(admin.getLoginName())){
    		return organizationService.findAll();
    	}
    	return organizationService.getOrganizationByAdminOrg(admin.getId());
    }
    
    /**
     * 查询列表
     * @param
     * @return
     * @throws Exception 
     */
    @RequestMapping("/list")
    public String list( Model model,@RequestParam(required = false, defaultValue = "-1") String EQ_pId,
			@RequestParam(required = false, defaultValue = "10") int pageSize,
			@RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception {
    	Map<String, Object> params = new HashMap<String, Object>();
        params.put("EQ_pId", EQ_pId);
        params.put("LIKE_name",request.getParameter("LIKE_name")==null?"":request.getParameter("LIKE_name"));
		SplitPage sp = new SplitPage();
	        sp.setAction(request.getRequestURI().toString());
	        sp.setPageNo(pageNo);
	        sp.setPageSize(pageSize);
	        sp.setParams(params);
	    Page<Organization> page= organizationService.findByPage(params, initPage(pageNo,pageSize,Direction.DESC, new String[] { "sortNo" }));
		sp.setRowCnt((int) page.getTotalElements());
		model.addAttribute("list", page.getContent());
		model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
		model.addAttribute("page", sp);
		model.addAttribute("search", params);
        return "sys/org/list";
    }
    
    @RequestMapping(value = "/updateSortNo", method = RequestMethod.POST)
    @ResponseBody
    public Response updateSortNo(String id, Integer sortNo){
    	Response response = new  Response();
    	organizationService.updateSortNo(id, sortNo);
    	response.success();
        return response;
    }
    @RequestMapping(value = "/edit")
    public String edit(HttpServletRequest request, Model model, String id,String pId) throws Exception {
    	Organization org = organizationService.getById(id);
    	if(org ==null){
    		org = new Organization();
    		org.setpId(pId);
    		org.setStatus(1);
    	}
    	 model.addAttribute("org", org);
    	 return "sys/org/edit";
    }
    @RequestMapping(value = "/batchEdit")
    public String batchEdit(HttpServletRequest request, Model model, String id,String pId) throws Exception {
		Organization org = organizationService.getById(pId);
    	 model.addAttribute("org", org);
    	 return "sys/org/batchEdit";
    }
    
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Response  save(Organization org){
    	Response response = new  Response();
    	Boolean isAdd = StringUtils.isEmpty(org.getId())?true:false;
    	org.setCreateTime(new Date());
    	org.setOrgLevel(organizationService.getById(org.getpId()).getOrgLevel()+1);
    	org=organizationService.save(org);
    	organizationService.changeSubCount(org.getpId(), true);
    	if(isAdd){
			addAdminOrg(org);
		}

    	response.success(org);
        return response;
    }
    @RequestMapping(value = "/batchSave", method = RequestMethod.POST)
    @ResponseBody
    public Response  batchSave(String beginIndex,String pId,String totalNum){
    	Response response = new  Response();
		Organization org = organizationService.getById(pId);
		int addNum = Integer.parseInt(totalNum);
		int beginNum = Integer.parseInt(beginIndex);
		for(int i=0;i<addNum;i++){
			Organization addOrg = new Organization();
			addOrg.setCreateTime(new Date());
			addOrg.setpId(pId);
			addOrg.setStatus(1);
			addOrg.setArea(org.getName());
			addOrg.setName(org.getName()+(beginNum+i));
			addOrg.setCode(org.getCode()+"-"+(beginNum+i));
			addOrg.setSortNo(beginNum+i);
			addOrg.setOrgLevel(org.getOrgLevel()+1);
			addOrg=organizationService.save(addOrg);
			organizationService.changeSubCount(pId, true);
			addAdminOrg(addOrg);
			//创建图书馆
            addJoin(addOrg);
		}
    	response.success(org);
        return response;
    }

    private void addJoin(Organization org ){
		//给当前账号插入权限
		//String adminId = adminId();
        TbLibJoin join = new TbLibJoin();
        join.setLeagueCode(org.getCode());
        join.setLeagueName(org.getName());
        join.setLibtype(2);
        join.setType(1);
        join.setOrgCode(org.getCode());
        join.setCreateTime(new Date());
        join.setLeagueAddress("乌鲁木齐市新市区新医路393号");
        join.setLeagueLat("43.83503");
        join.setLeagueLng("87.58042");
        join.setLeagueCity(org.getArea());
        joinService.save(join);
	}
	private void addAdminOrg(Organization org ){
		//给当前账号插入权限
		//String adminId = adminId();
		List<String> list = new ArrayList<>();
		list.add("admin");
		list.add("sishujia");
		list.add("xsxb");
		for(String str:list){
			Admin admin = adminService.getByLoginName(str);
			if(admin == null){continue;}
			AdminOrg adminOrg = new AdminOrg();
			adminOrg.setAdminId(admin.getId());
			adminOrg.setCreateTime(new Date());
			adminOrg.setOrgCode(org.getCode());
			adminOrg.setOrgId(org.getId());
			adminOrgService.save(adminOrg);
		}
	}

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Response  delete(String id,String pId){
    	Response response = new  Response();
    	organizationService.delete(id);
    	organizationService.changeSubCount(pId, false);
    	response.success();
        return response;
    }
    
    
    /**
     * 组织架构关联人员
     * @return
     */
    @RequestMapping("/staffing")
    public String staffing( Model model) {
        return "sys/org/staffing";
    }
    
    @RequestMapping("/staffinglist")
    public String staffinglist( Model model,
			@RequestParam(required = false, defaultValue = "10") int pageSize,
			@RequestParam(required = false, defaultValue = "1") int pageNo
			,@RequestParam(required = false, defaultValue = "SSJ") String EQ_orgCode
			,@RequestParam(required = false, defaultValue = "1") Integer orgLevel) throws Exception {

    	Map<String, Object> params = new HashMap<String, Object>();
		params.put("EQ_orgCode", EQ_orgCode);
		params.put("EQ_stat","1");
		params.put("LIKE_name",request.getParameter("LIKE_name")==null?"":request.getParameter("LIKE_name"));
		SplitPage sp = new SplitPage();
	        sp.setAction(request.getRequestURI().toString());
	        sp.setPageNo(pageNo);
	        sp.setPageSize(pageSize);
	        sp.setParams(params);
	    Page<LibStaffing> page= libStaffingService.findByPage(params, initPage(pageNo,pageSize,Direction.DESC, new String[] { "createTime" }));
		sp.setRowCnt((int) page.getTotalElements());
		String  libId =libStaffingService.getLibJoinId(EQ_orgCode);
		params.put("orgLevel", orgLevel);
		params.put("libId", libId !=null ? libId : EQ_orgCode);
		model.addAttribute("list", page.getContent());
		model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
		model.addAttribute("page", sp);
		model.addAttribute("search", params);
		model.addAttribute("sortlist", sortService.getParamValByCode("staffing"));
        return "sys/org/staffinglist";
    }
	
}
