package com.cloudcross.ssp.web.back.main;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.Resources;
import com.cloudcross.ssp.model.UserLogin;
import com.cloudcross.ssp.service.IAccountService;
import com.cloudcross.ssp.service.IResourcesService;
import com.cloudcross.ssp.service.IUserLoginService;
import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.consts.Status;
import com.cloudcross.ssp.common.utils.LangUtil;
//import com.cloudcross.ssp.common.utils.MD5;
import com.cloudcross.ssp.common.utils.Md5Tool;
import com.cloudcross.ssp.common.utils.Pager;

@Controller("back.authorityController")
@RequestMapping("/back/main/authority")
public class AuthorityController extends SimpleController{
	
	@Autowired
	private FreemarkerTemplateProcessor templateProcessor;
	
	@Autowired
	protected IAccountService accountService;
	
	@Autowired
	protected IUserLoginService userLoginService;
	@Autowired
	protected IResourcesService resourcesService;
	@RequestMapping
	public String index(){
		return redirect(page("list"));
	}
	//权限管理的列表页，显示当前登录用户所创建的所有账号！
	//如果是云联账号，则显示所有的运营商系统的账号！
	@RequestMapping("list")
	public String list(Model model,
			@RequestParam HashMap<String, Object> paramMap,
			@RequestParam(defaultValue="1") int page){
		//当前登录用户
		Account loginAccount = getLoginUser();
		//当前登录用户是云联的账号还是运营商账号！
		paramMap.put("loginAccount", loginAccount);
		int totalRow = accountService.countByParams(paramMap);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		List<Account> accountList = accountService.findByParams(paramMap, pager);
		//循环获取查询到账号的登录时间；保存到对象的creatTime字段中
		for (int i = 0; i < accountList.size(); i++) {
			UserLogin login = userLoginService.getById(new Integer(accountList.get(i).getId()).toString());
			//查询到的用户可能从未登录过系统，所以这里要判断一下，避免空指针异常！
			if (login == null) {
				continue;
			}
			accountList.get(i).setCreateTime(login.getLoginTime());
		}
		model.addAttribute("accountList",accountList);
		model.addAttribute("pager",pager);
		model.addAllAttributes(paramMap);
		return page("list");
	}
	/**
	 * @author CloudCross
	 * @return 返回create页面
	 */
	@RequestMapping("/create")
	public String create(){
		return page("create");
	}
	/**
	 * 
	 * @return
	 */
	@RequestMapping("/save")
	public String save(Model model,
					@ModelAttribute("form") Account t,
					@RequestParam(value = "authority", defaultValue = "") String authority,
					@RequestParam(value = "ensurePassword", defaultValue = "") String ensurePassword){
		//得到当前登陆用户，因为我们这个系统，只是媒体方系统，所以不用考虑是广告主登录进来的问题，
		//但是这个地方要考虑是某个媒体账号进来创建的账号，所以要打上这个媒体的标签。
		
		String password = t.getPassword();
		if ((t.getId()) == 0) {
			Account account = getLoginUser();
			t.setSysType(account.getSysType());
			t.setPassword(Md5Tool.getMd5(password));
			t.setDescription(account.getDescription());

			accountService.addAccount(t);
			
			if(authority!=null && !authority.equals("")){
				List<Long> autList = new ArrayList<Long>();
				String[] aut = authority.split(",");
				for(int i=0;i < aut.length;i++){
					autList.add(Long.parseLong(aut[i]));
				}
				resourcesService.addAccountResourcess(new Long(t.getId()),autList);
			}
		} else {
				if (StringUtils.isNotBlank(password)) {
					t.setPassword(Md5Tool.getMd5(password));
				}
				accountService.editAccount(t);
				if(authority!=null){
					if(authority.equals("")){
						resourcesService.deleteResourceByAccount(Long.parseLong(String.valueOf(t.getId())));
					}else {
						List<Long> autList = new ArrayList<Long>();
						String[] aut = authority.split(",");
						for(int i=0;i < aut.length;i++){
							autList.add(Long.parseLong(aut[i]));
						}
						resourcesService.addAccountResourcess(Long.parseLong(String.valueOf(t.getId())),autList);
					}
				}
			}
		// 跳转到管理页面。
		return redirect(page("list"));
	}
	@RequestMapping("/edit")
	public String edit(Model model, @RequestParam long accountId) {
		Account account = accountService.getById(String.valueOf(accountId));
		System.out.println("yuan"+account);
		String authority = ""; 
			List<Resources> resources = resourcesService.findResourcesByAccount(accountId);
		for (Resources r:resources){
				//循环取出resources中的id
				if(authority.equals("")){
					authority = authority + r.getId().toString();
				}
				else{
					authority = authority + ","+r.getId().toString();
				}
			}
		model.addAttribute("authority",authority);
		model.addAttribute("account", account);
		return page("edit");
	}
	
	//这个地方要注意，因为我们表示1开启，0表示停止
	@RequestMapping("enable")
	public @ResponseBody String enable(Long[] id){
		if (ArrayUtils.isNotEmpty(id)) {
			accountService.updateState(LangUtil.array2List(id),Status.disable.value);
		}
		return OK;
	}
	@RequestMapping("disable")
	public @ResponseBody String disable(Long[] id){
		if (ArrayUtils.isNotEmpty(id)) {
			accountService.updateState(LangUtil.array2List(id),Status.enable.value);
		}
		return OK;
	}
	
	/**
	 * 跳转到个人信息修改页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/loginperson")
	public String personInfEdit(Model model){
		/**
		 * ————————————————这个地方要注意，还要将当前登录用户的对应表的一些信息读取出来：
		 *	例如：媒体系统的就要去t_operater表中读取数据；
		 *  广告主系统的：运营商登录系统，去t_adv_agent;广告主登录系统，去t_advertiser。
		 *  要判断当前登录用户是不是超管账号。admin_id字段等于当前登录用户的id就表示是超管,是超管就要将operator中的信息传到页面上去；
		 *  否则就表示不是！
		 */
		Account account = getLoginUser();
		model.addAttribute("account",account);
		return page("loginperson");
	}
	/**
	 * 个人信息修改的保存操作！！
	 * @param model
	 * @param t
	 * @param ensurePassword
	 * @return 保存操作成功要跳转回login页面，重新输入密码后才能再次进入系统
	 */
	@RequestMapping("/saveloginperson")
	public String saveloginperson(Model model,
					@ModelAttribute("form") Account t,
					@RequestParam(value = "ensurePassword", defaultValue = "") String ensurePassword){
		Account loginAccount = getLoginUser();
		String password = t.getPassword();
		if (StringUtils.isNotBlank(password)) {
			t.setPassword(Md5Tool.getMd5(password));
		}
		accountService.editAccount(t);
		if(!loginAccount.getPassword().equals(t.getPassword())){
			return "/login";//修改密码跳转login界面重新登陆
		}else{
			return "/back/main/dashboard";//并未修改密码，则跳转主页！
		}
	}
	
	@RequestMapping("isExist")
	public @ResponseBody String isExist(Model model,
			@RequestParam(defaultValue = "") String accountName
			) {
		String success = "";
		Account account = accountService.querySingleAccount(accountName);
//		System.err.println(account);
		if(account!=null){
			model.addAttribute("isExist", new Long(1));
			success = "YES";
//			System.out.println("yuanzhiq11111111");
		}else {
			model.addAttribute("isExist", new Long(0));
			success = "NO";
//			System.out.println("yuanzhiq0000000");
		}
		return success;
	}
	
	@RequestMapping("/exportDataReportExcel")
	public void exportDataReportExcel(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam HashMap<String, Object> paramMap) {
		/**
		 * 参数和list里要一样
		 */
		Account loginAccount = getLoginUser();
		paramMap.put("loginAccount", loginAccount);
		List<Account> accountList = accountService.findExcelAccounts(paramMap);
		for (int i = 0; i < accountList.size(); i++) {
			UserLogin login = userLoginService.getById(new Integer(accountList.get(i).getId()).toString());
			//查询到的用户可能从未登录过系统，所以这里要判断一下，避免空指针异常！
			if (login == null) {
				continue;
			}
			accountList.get(i).setCreateTime(login.getLoginTime());
		}
		System.out.println("yuanzzzz"+accountList);
		paramMap.put("dataList", accountList);
		
		response.reset();
		// Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
		response.setContentType("application/vnd.ms-excel;charset=utf8");
		// 设置excel文件名称
		SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "account" + df2.format(new Date());
		response.setHeader("Content-Disposition", "attachment;filename="
				+ fileName + ".xls");
		// 需要对excel的列和行的总数进行指定
		int column = 6;
		paramMap.put("dataSize", accountList.size());
		paramMap.put("column", column);
	
		paramMap.put("accountList", "账号列表");
		String excelTemplate = templateProcessor.processTemplate(
				"excel/dataAccount.ftl", paramMap);
		try {
			PrintWriter out = response.getWriter();
			out.write(excelTemplate);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

