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.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.AdvAgent;
import com.cloudcross.ssp.model.ClientAccount;
import com.cloudcross.ssp.model.Correlation;
import com.cloudcross.ssp.model.Operator;
import com.cloudcross.ssp.model.RoleAccount;
import com.cloudcross.ssp.model.UserLogin;
import com.cloudcross.ssp.service.IAccountService;
import com.cloudcross.ssp.service.IAdvAgentService;
import com.cloudcross.ssp.service.IClientAccountService;
import com.cloudcross.ssp.service.ICorrelationService;
import com.cloudcross.ssp.service.IOperatorService;
import com.cloudcross.ssp.service.IRolesService;
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.Md5Tool;
import com.cloudcross.ssp.common.utils.Pager;
@Controller
@RequestMapping("/back/main/client-account")
public class ClientAccountController extends SimpleController{
	
	@Autowired
	protected IClientAccountService clientAccountService;
	@Autowired
	protected IAccountService accountService;
	@Autowired
	protected IUserLoginService userLogin;
	@Autowired
	protected IOperatorService operatorService;
	@Autowired
	protected IAdvAgentService advAgentService;
	@Autowired
	private FreemarkerTemplateProcessor templateProcessor;
	@Autowired
	protected IRolesService roleService;
	@Autowired
	protected ICorrelationService correlationService;
	@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,
				@RequestParam(defaultValue="0") Long sysType){
		
		if (sysType!=null && sysType!=0) {
			paramMap.put("sysType", sysType);
		}
		int totalRow = clientAccountService.countByParams(paramMap);
//		System.out.println("黑喂狗"+totalRow);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		List<ClientAccount> clientAccountsList = clientAccountService.findByParams(paramMap, pager);
		//循环得到每个客户账号的最后登录时间！
		for (ClientAccount ca : clientAccountsList)
		{
			 Long userId = ca.getId();
			 UserLogin ul = userLogin.getById(userId.toString());
			 if (ul == null) {//要防止创建的账号从未登录过系统
				 Account account = accountService.getById(userId.toString());
				 ca.setLoginTime(account.getCreateTime());
				 continue;
			}
			 ca.setLoginTime(ul.getLoginTime());
		}
		model.addAttribute("pager",pager);
		model.addAttribute("sysType",sysType);
		model.addAllAttributes(paramMap);
		model.addAttribute("clientAccountsList", clientAccountsList);
		return page("list");
	}
	
	@RequestMapping("/create")
	public String create(){
		
		return page("create");
	}
	
	@RequestMapping("/edit")
	public String edit(Model model,
				@RequestParam Long accountId){
		ClientAccount clientAccount = null;
		Account account = accountService.getById(accountId.toString());
		if(account.getAgentId()!=0 && account.getSysType()==3){
			//是代理商账号的编辑
			AdvAgent advAgent = advAgentService.findById(account.getAgentId());
			//把accout 和 advAgent封装成clientAccount对象
			clientAccount = new ClientAccount();
			clientAccount.setId(new Long(account.getId()));
			clientAccount.setAccountName(account.getAccountName());
			clientAccount.setPassword(account.getPassword());
			clientAccount.setLinkMan(advAgent.getContacts());
			clientAccount.setMobilePhone(advAgent.getMobile());
			clientAccount.setTel(advAgent.getTel());
			clientAccount.setCompanyName(advAgent.getName());
			clientAccount.setHomePage(advAgent.getHomePage());
			clientAccount.setAddress(advAgent.getAddress());
			clientAccount.setZip(advAgent.getZip());
			clientAccount.setEmail(advAgent.getEmail());
			clientAccount.setTitle(advAgent.getTitle());
			clientAccount.setStatus(Integer.parseInt(account.getState()));
			clientAccount.setSysType(account.getSysType());
			clientAccount.setBank("");
			clientAccount.setBankAccount("");
			clientAccount.setBankAccountName("");
			clientAccount.setAgentId(account.getAgentId());
			clientAccount.setOperatorId(account.getOperatorId());
		}
		if(account.getOperatorId()!=0 && account.getSysType()==2){
			//是媒体账号的编辑
			Operator operator = operatorService.findById(account.getOperatorId());
			//把accout 和 operator封装成clientAccount对象
			clientAccount = new ClientAccount();
			clientAccount.setId(new Long(account.getId()));
			clientAccount.setAccountName(account.getAccountName());
			clientAccount.setPassword(account.getPassword());
			clientAccount.setLinkMan(operator.getLinkMan());
			clientAccount.setMobilePhone(operator.getMobile());
			clientAccount.setTel(operator.getTel());
			clientAccount.setCompanyName(operator.getCompanyName());
			clientAccount.setHomePage(operator.getHomePage());
			clientAccount.setAddress(operator.getAddress());
			clientAccount.setEmail(operator.getEmail());
			clientAccount.setZip(operator.getZip());
			clientAccount.setBank(operator.getBank());
			clientAccount.setBankAccount(operator.getAccount());
			clientAccount.setBankAccountName(operator.getAccountName());
			clientAccount.setStatus(Integer.parseInt(account.getState()));
			clientAccount.setSysType(account.getSysType());
			clientAccount.setTitle("");
			clientAccount.setAgentId(account.getAgentId());
			clientAccount.setOperatorId(account.getOperatorId());
		}
		System.out.println("ggggg"+clientAccount);
		model.addAttribute("clientAccount",clientAccount);
		return page("edit");
	}
	/**
	 * 
	 * @param ca
	 * @param ensueensurePassword
	 * @return
	 */
	@RequestMapping("/save")
	public String save(@ModelAttribute("form") ClientAccount ca,
			@RequestParam(value = "ensurePassword", defaultValue = "") String ensueensurePassword){
		String password = ca.getPassword();
		if(ca.getId()==null){//新增客户账号
			//要先判断一下是插入的是operator还是agent
			//要分两部分来做，一部分是t_account账号的插入，另一部分的插入是operator或者是agent的插入
			//一个先插入，然后在插入另一个，查好了后还要编辑先插好的那个~~~~~好麻烦~！！
			ca.setPassword(Md5Tool.getMd5(password));
			//clientAccountService.add(ca);
			if (ca.getSysType()==2) {
				//2表示是媒体，3表示是代理商。
				Operator o = new Operator();
				o.setAccount(ca.getBankAccount());
				o.setBank(ca.getBank());
				o.setAccountName(ca.getBankAccountName());
				o.setCompanyName(ca.getCompanyName());
				o.setLinkMan(ca.getLinkMan());
				o.setStatus(new Integer(0));
				o.setTel(ca.getTel());
				o.setMobile(ca.getMobilePhone());
				o.setZip(ca.getZip());
				o.setEmail(ca.getEmail());
				o.setHomePage(ca.getHomePage());
				o.setAddress(ca.getAddress());
				
				Account account = new Account();
				account.setAccountName(ca.getAccountName());
				account.setPassword(ca.getPassword());
				account.setSysType(ca.getSysType());
				account.setTel(ca.getTel());
				account.setCreateTime(new Date());
				account.setState(ca.getStatus().toString());
				account.setRealName(ca.getLinkMan());
				account.setType(new Integer(2));
				account.setDescription(ca.getCompanyName());
				accountService.addAccount(account);
				Account account2 = accountService.querySingleAccount(account.getAccountName());
				RoleAccount ra = new RoleAccount();//给客户账号分配媒体角色  角色ID=9
				ra.setAccountId(account2.getId());
				ra.setRoleId(9);
				roleService.addAccRole(ra);
				
				o.setAdminId(new Long(account2.getId()));
				operatorService.add(o);
				Operator operatorNew = operatorService.getNew(o);
				account2.setOperatorId(operatorNew.getId());
				accountService.editAccount(account2);
			}
			if (ca.getSysType()==3) {
				//插入的是代理商账号。
				AdvAgent advAgent = new AdvAgent();
				advAgent.setAddress(ca.getAddress());
				advAgent.setContacts(ca.getLinkMan());
				advAgent.setEmail(ca.getEmail());
				advAgent.setHomePage(ca.getHomePage());
				advAgent.setMobile(ca.getMobilePhone());
				advAgent.setName(ca.getCompanyName());
				advAgent.setStatus(new Integer(0));
				advAgent.setTel(ca.getTel());
				advAgent.setTitle(ca.getTitle());
				advAgent.setZip(ca.getZip());
				advAgent.setUpdated(new Date());
				
				Account account = new Account();
				account.setAccountName(ca.getAccountName());
				account.setPassword(ca.getPassword());
				account.setSysType(ca.getSysType());
				account.setTel(ca.getTel());
				account.setCreateTime(new Date());
				account.setState(ca.getStatus().toString());
				account.setRealName(ca.getLinkMan());
				account.setType(new Integer(2));
				account.setDescription(ca.getCompanyName());
				accountService.addAccount(account);
				Account account2 = accountService.querySingleAccount(account.getAccountName());
				RoleAccount ra = new RoleAccount();//给客户账号分配代理商角色 角色ID=7
				ra.setAccountId(account2.getId());
				ra.setRoleId(7);
				roleService.addAccRole(ra);
				
				advAgent.setAdminId(new Long(account2.getId()));
				advAgentService.add(advAgent);
				AdvAgent advAgentNew = advAgentService.getNew(advAgent);
				account2.setAgentId(advAgentNew.getId());
				accountService.editAccount(account2);
			}
		}else{//x修改信息
			//要先判断一下是插入的是operator还是agent
			//要分两部分来做，一部分是t_account账号的插入，另一部分的插入是operator或者是agent的插入
			//一个先插入，然后在插入另一个，查好了后还要编辑先插好的那个~~~~~好麻烦~！！
			if(password != null){
				ca.setPassword(Md5Tool.getMd5(password));
			}
			//clientAccountService.add(ca);
			if (ca.getSysType()==2) {
				//2表示是媒体，3表示是代理商。
				Operator o = new Operator();
				o.setId(ca.getOperatorId());
				o.setAccount(ca.getBankAccount());
				o.setBank(ca.getBank());
				o.setAccountName(ca.getBankAccountName());
				o.setCompanyName(ca.getCompanyName());
				o.setLinkMan(ca.getLinkMan());
				o.setStatus(new Integer(0));
				o.setTel(ca.getTel());
				o.setMobile(ca.getMobilePhone());
				o.setZip(ca.getZip());
				o.setEmail(ca.getEmail());
				o.setHomePage(ca.getHomePage());
				o.setAddress(ca.getAddress());
				o.setAdminId(ca.getId());
				
				Account account = new Account();
				account.setId(ca.getId().intValue());
				account.setAccountName(ca.getAccountName());
				if(password != null){
					account.setPassword(ca.getPassword());
				}
//				account.setSysType(ca.getSysType());
//				account.setTel(ca.getTel());
//				account.setCreateTime(new Date());
				account.setState(ca.getStatus().toString());
//				account.setRealName(ca.getLinkMan());
//				account.setType(new Integer(2));
//				account.setOperatorId(ca.getOperatorId());
				accountService.editAccount(account);
				operatorService.edit(o);
			}
			if (ca.getSysType()==3) {
				//插入的是代理商账号。
				AdvAgent advAgent = new AdvAgent();
				advAgent.setId(ca.getAgentId());
				advAgent.setAddress(ca.getAddress());
				advAgent.setContacts(ca.getLinkMan());
				advAgent.setEmail(ca.getEmail());
				advAgent.setHomePage(ca.getHomePage());
				advAgent.setMobile(ca.getMobilePhone());
				advAgent.setName(ca.getCompanyName());
				advAgent.setStatus(ca.getStatus());
				advAgent.setTel(ca.getTel());
				advAgent.setTitle(ca.getTitle());
				advAgent.setZip(ca.getZip());
				advAgent.setUpdated(new Date());
				advAgent.setAdminId(ca.getId());
				Account account = new Account();
				account.setId(ca.getId().intValue());
				account.setAccountName(ca.getAccountName());
				if(password != null){
					account.setPassword(ca.getPassword());
				}
//				account.setSysType(ca.getSysType());
//				account.setTel(ca.getTel());
//				account.setCreateTime(new Date());
				account.setState(ca.getStatus().toString());
//				account.setRealName(ca.getLinkMan());
//				account.setType(new Integer(2));
//				account.setAgentId(ca.getAgentId());
				accountService.editAccount(account);
				advAgentService.edit(advAgent);
			}
		}
		return redirect(page("list"));
	}
	
	/**
	 * 单个或者批量启用功能。
	 * 后面要做登录检验的，如果是主账号登录直接检查是否被停用。
	 * 
	 * @return 成功则返回"ok"
	 */
	@RequestMapping("enable")
	public @ResponseBody String enable(Long[] id) {
//		LOG.debug("Args's value: id=" + Arrays.toString(id));
		if (ArrayUtils.isNotEmpty(id)) {
			for(int i = 0;i < id.length;i++){//依次找到对应客户端账号的更改对应的agent或者operator的状态！
				Account account = accountService.getById(id[i].toString());
				if(account.getAgentId()!=0 && account.getSysType()==3){
					List<Long> l = new ArrayList<Long>();
					l.add(account.getAgentId());
					advAgentService.updateStatus(l, Status.enable.value);
				}
				if (account.getOperatorId()!=0 && account.getSysType()==2) {
					List<Long> l = new ArrayList<Long>();
					l.add(account.getOperatorId());
					operatorService.updateStatusBack(l, Status.enable.value);
				}
			}
		}
		if (ArrayUtils.isNotEmpty(id)) {
			accountService.updateState(LangUtil.array2List(id),
					Status.disable.value);
		}
		return OK;
	}

	/**
	 * 单个或者批量禁用功能。 
	 * 
	 * @return 成功则返回"ok"
	 */
	@RequestMapping("disable")
	public @ResponseBody String disable(Long[] id) {
//		LOG.debug("Args's value: id=" + Arrays.toString(id));\
		if (ArrayUtils.isNotEmpty(id)) {
			for(int i = 0;i < id.length;i++){//依次找到对应客户端账号的更改对应的agent或者operator的状态！
				Account account = accountService.getById(id[i].toString());
				if(account.getAgentId()!=0 && account.getSysType()==3){
					List<Long> l = new ArrayList<Long>();
					l.add(account.getAgentId());
					advAgentService.updateStatus(l, Status.disable.value);
				}
				if (account.getOperatorId()!=0 && account.getSysType()==2) {
					List<Long> l = new ArrayList<Long>();
					l.add(account.getOperatorId());
					operatorService.updateStatusBack(l, Status.disable.value);
				}
			}
		}
		if (ArrayUtils.isNotEmpty(id)) {
			accountService.updateState(LangUtil.array2List(id),
					Status.enable.value);
		}
		// 将来会被改updateState
		return OK;
	}
	
	@RequestMapping("isExist")
	public @ResponseBody String isExist(Model model,
			@RequestParam(defaultValue = "") String clientAccountName
			) {
		String success = "";
		Account account = accountService.querySingleAccount(clientAccountName);
//		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;
	}
	/**
	 * 打开关联列表页
	 * @param model
	 * @return
	 */
	@RequestMapping("/correlation")
	public String correlation(Model model,
			@RequestParam(defaultValue="1") int page){
		int totalRow = correlationService.countAllCorrelation();
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		List<Correlation> correlations = correlationService.findAllCorrelation(pager);
		model.addAttribute("pager",pager);
		model.addAttribute("correlations",correlations);
		return page("correlation");
	}
	/**
	 * 创建关联
	 * @return
	 */
	@RequestMapping("createcorrelation")
	public String createCorrelation(){
		return page("createcorrelation");
	}
	/**
	 * 取消关联
	 * @return
	 */
	@RequestMapping("cancelcorrelation")
	public String cancelCorrelation(@RequestParam Long agentId,
			@RequestParam Long operatorId){
		Correlation ca = new Correlation();
		ca.setAgentId(agentId);
		ca.setOperatorId(operatorId);
		correlationService.deleteCorrelation(ca);
		return redirect(page("correlation"));
	}
	/**
	 * 保存关联
	 * @return
	 */
	@RequestMapping("savecorrelation")
	public String saveCorrelation(@ModelAttribute("form")Correlation ca){
		correlationService.addCorrelation(ca);
		return redirect(page("correlation"));
	}
	/**
	 * 
	 * 查询是否 存在关联
	 * 
	 * @author CloudCross
	 */
	@RequestMapping("is_exit")
	public @ResponseBody String isExitCorrelation(@RequestParam Long operatorId){
		List<Correlation>  co = correlationService.findCorrelationByOperatorId(operatorId);
		if(co.size()>0){
			return "YES";
		}else {
			return "NO";
		}
	}
	
	@RequestMapping("/exportDataReportExcel")
	public void exportDataReportExcel(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam HashMap<String, Object> paramMap) {
		/**
		 * 参数和list里要一样
		 */
		if(paramMap.get("sysType")!=null){
			Long sysType = Long.parseLong((String)paramMap.get("sysType"));
			if (sysType!=0) {
				paramMap.put("sysType", sysType);
			}else {
				paramMap.put("sysType",new Long(0));
			}
		}
		Account loginAccount = getLoginUser();
		paramMap.put("loginAccount", loginAccount);
		List<ClientAccount> accountList = clientAccountService.findExcelAccounts(paramMap);
		for (ClientAccount ca : accountList)
		{
			 Long userId = ca.getId();
			 UserLogin ul = userLogin.getById(userId.toString());
			 if (ul == null) {//要防止创建的账号从未登录过系统
				 Account account = accountService.getById(userId.toString());
				 ca.setLoginTime(account.getCreateTime());
				 continue;
			}
			 ca.setLoginTime(ul.getLoginTime());
		}
		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 = 9;
		paramMap.put("dataSize", accountList.size());
		paramMap.put("column", column);
	
		paramMap.put("accountList", "客户账号列表");
		String excelTemplate = templateProcessor.processTemplate(
				"excel/dataClientAccount.ftl", paramMap);
		try {
			PrintWriter out = response.getWriter();
			out.write(excelTemplate);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
