package com.cloudcross.ssp.web.advertiser.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.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;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.Advertiser;
import com.cloudcross.ssp.model.Resources;
import com.cloudcross.ssp.model.UserLogin;
import com.cloudcross.ssp.service.IAccountService;
import com.cloudcross.ssp.service.IAdvertiserService;
import com.cloudcross.ssp.service.IOperatorService;
import com.cloudcross.ssp.service.IResourcesService;
import com.cloudcross.ssp.service.IUserLoginService;
/**
 * 
 * 
 * @author CloudCross
 * 2015-9-12
 * @author CloudCross
 *
 */


@Controller
@RequestMapping("/advertiser/main/authority")
public class AuthorityController extends SimpleController{
	
	@Autowired
	private FreemarkerTemplateProcessor templateProcessor;
	
	@Autowired
	protected IAccountService accountService;
	
	@Autowired
	protected IUserLoginService userLoginService;
	
	@Autowired
	protected IOperatorService operatorService;
	
	@Autowired
	protected IResourcesService ResourcesService;
	
	@Autowired
	protected IAdvertiserService advertiserService;
	
	@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.countByParamsAdvertiser(paramMap);
		System.out.println("黑喂狗"+totalRow);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		List<Account> accountList = accountService.findByParamsAdvertiser(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) {
				System.out.println("黑喂狗00"+accountList.get(i).toString());
				continue;
			}
			System.out.println("这里打印"+accountList.get(i));
			accountList.get(i).setCreateTime(login.getLoginTime());
			System.out.println("黑喂狗"+accountList.get(i).toString());
		}
		model.addAttribute("accountList",accountList);
		model.addAttribute("pager",pager);
		model.addAllAttributes(paramMap);
		return page("list");
	}
	/**
	 * 
	 * 广告主没有权限创建账号，进不到这一页面！
	 * 当前登录用户的agentId字段，advertiserId字段是否为零，如果agentId为零，
	 * 
	 * @author CloudCross
	 * @return 返回create页面
	 */
	@RequestMapping("/create")
	public String create(Model model){
	Account account = getLoginUser();
		model.addAttribute("agentId",account.getAgentId());//要传代理商的Id到页面上去！
		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){
		//得到当前登陆用户，因为我们这个系统，只是媒体方系统，所以不用考虑是广告主登录进来的问题，
		//但是这个地方要考虑是某个媒体账号进来创建的账号，所以要打上这个媒体的标签。
		//-------------------这个地方要注意保存和修改的时候要进行权限修正！因为项目中很多业务还没有做完，资源表中还有些记录没有插入，目前我们仅仅做测试！
		//业务逻辑上，账号的停用也不能登录系统，但是不能删除权限。所以只能在Login的时候判断欲登录用户是哪个系统的，状态是不是停用！
		//++++++++这地方要看有没有关联广告主账号
		String password = t.getPassword();
		if ((t.getId()) == 0) {
			Account account = getLoginUser();
			//如果创建的是广告主端的账号，此处应插入相应的agentId，并且在关联广告主的时候插入advertiserId
			//如果没有关联广告主,插入的就是代理商的小账号，但是代理商可以事后为这个编辑账号时分配广告主
			t.setAgentId(account.getAgentId());
			if (account.getOperatorId()!=0) {
				//创建小账号的时候operatorId标签要嵌入
				t.setOperatorId(account.getOperatorId());
			}else {
				t.setOperatorId(new Long(0));
			}
			t.setSysType(account.getSysType());
			t.setPassword(Md5Tool.getMd5(password));
			t.setDescription(account.getDescription()+"（小）");
			if(t.getAdvertiserId()==null){
				t.setAdvertiserId(new Long(0));
				accountService.addAccountAdvertiser(t);
			}else {
				accountService.addAccountAdvertiser(t);
				Advertiser advertiser = advertiserService.findById(t.getAdvertiserId());
				if (advertiser!=null) {
					advertiser.setAdminId(new Long(t.getId()));
					advertiserService.edit(advertiser);
				}
			}
			//还要保存对应的权限——这个地方要调用resourcesercice中的addAccountResource方法
			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]));
				}
//				Account newAccount = accountService.querySingleAccount(t.getAccountName());
				ResourcesService.addAccountResourcess(new Long(t.getId()),autList);
			}
		} else {
			if (StringUtils.isNotBlank(password)) {
				t.setPassword(Md5Tool.getMd5(password));
			}
			if(t.getAdvertiserId()==null){
				t.setAdvertiserId(new Long(0));
			}
			//还要保存对应权限的修改——同样也要调用addAccountResource方法
			accountService.editAccountAdvertiser(t);
			if (t.getAdvertiserId()!=null) {
				Advertiser advertiser = advertiserService.findById(t.getAdvertiserId());
				if (advertiser!=null) {
					advertiser.setAdminId(new Long(t.getId()));
					advertiserService.edit(advertiser);
				}
			}
			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(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);
		//这个地方还要将对应这个账户的权限加载到页面上。t_res_accounts表！model.addAttribute("authority",authority)
		List<Resources> resources = ResourcesService.findResourcesByAccount(new Long(accountId));
		String authority = "";
		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";
		}else{
			return "/advertiser/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();
		}
	}
}

