package cn.hmsoft.frame.control;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hmsoft.application.AppHelper;
import cn.hmsoft.application.SpringHelper;
import cn.hmsoft.application.web.Ajax;
import cn.hmsoft.application.web.AjaxControl;
import cn.hmsoft.exception.web.MvcParamException;
import cn.hmsoft.exception.web.WebException;
import cn.hmsoft.frame.constants.FrameStatus;
import cn.hmsoft.frame.data.dao.FrameOptrDao;
import cn.hmsoft.frame.data.model.FrameOptr;
import cn.hmsoft.frame.data.model.FrameRes;
import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.frame.service.FrameLoginService;
import cn.hmsoft.frame.service.FrameOptrService;
import cn.hmsoft.frame.util.FrameAssertUtil;
import cn.hmsoft.frame.util.FrameParamUtil;
import cn.hmsoft.frame.util.FrameRandomCodeUtil;
import cn.hmsoft.helper.LocalDateHelper;
import cn.hmsoft.helper.StringHelper;

@RestController
public class FrameLoginControl extends AjaxControl {

	@Autowired
	private FrameLoginService frameLoginService;
	@Autowired
	private FrameOptrService frameOptrService;

	@Autowired
	private FrameOptrDao daoOptr;

	@RequestMapping("frame/info")
	public Ajax info() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("AppStartTime", LocalDateHelper.format(AppHelper.AppStartTime));
		map.put("LoadParamTime", LocalDateHelper.format(AppHelper.LoadParamTime));
		return new Ajax(map);
	}

	@RequestMapping("frame/optr/login")
	public Ajax login(String loginName, String loginPass, String loginCode, String login_url) {
		final Ajax ajax = new Ajax();
		try {
			if (StringHelper.isEmpty(loginName) || StringHelper.isEmpty(loginPass)) {
				throw new MvcParamException();
			}
			if (AppHelper.AppDebug || !FrameParamUtil.FrameLoginValidCode) {

			} else if (!FrameRandomCodeUtil.validRandomCode(this.getRequest(), loginCode)) {
				throw new BusinessException("验证码错误,请重试");
			}
			final FrameOptr optr = this.daoOptr.find("login_name", loginName);
			FrameAssertUtil.isNotNull(optr, "登录失败：不存在登录名称为[" + loginName + "]的操作员");

			FrameAssertUtil.isEqual(loginPass.toUpperCase(), optr.getLogin_pass(), "登录失败：该操作员登录密码错误");
			FrameAssertUtil.isEqual(optr.getOptr_status(), FrameStatus.Active.toString(), "登录失败：该操作员登录已经被禁用");
			// 获取该操作员所有权限
			List<FrameRes> resArray = this.frameOptrService.fetchOptrRes(optr.getOptr_id());

			if ((StringHelper.isEmpty(optr.getLogin_pass())) || resArray.size() < 1) {
				throw new BusinessException("登录失败：该操作员未初始化，请联系系统管理员");
			}

			optr.setResMap(new HashMap<Integer, Integer>());
			for (FrameRes res : resArray) {
				optr.getResMap().put(res.getRes_id(), res.getRes_id());
			}
			// log
			frameLoginService.optrLogin(optr, this.getRequest());
			this.getSession().setAttribute(FrameParamUtil.SessionName_FrameOptr, optr);
			ajax.setLogin(true);
			ajax.setSuccess(true);
		} catch (WebException e) {
			ajax.setLogin(false);
			ajax.setSuccess(false);
			ajax.setErrorCode(e.getErr_code());
			ajax.setErrorMsg(e.getMessage());
		}
		return ajax;
	}

	@RequestMapping("frame/optr/logout")
	public Ajax logout() {
		this.getSession().invalidate();
		return new Ajax();
	}

	@RequestMapping("frame/template/download")
	public void download(String file_name) {
		File file = new File(SpringHelper.WebServletContext.getRealPath("/") + "template" + File.separator + file_name);
		// LogHelper.info(file.getPath());
		if (file.exists())
			// this.writeAlert("未找到模版文件，请联系系统管理员");
			this.downloadFile(file, file_name);
		else
			this.writeAlert("未找到模版文件，请联系系统管理员");
	}

	@RequestMapping("frame/temporary/download")
	public void downloadTemp(String file_name, String real_name) {
		if (StringHelper.isEmpty(real_name))
			real_name = file_name;
		File file = new File(
				SpringHelper.WebServletContext.getRealPath("/") + "temporary" + File.separator + file_name);
		if (file.exists())
			// this.writeAlert("未找到模版文件，请联系系统管理员");
			this.downloadFile(file, real_name, true);
		else
			this.writeAlert("未找到指定文件，请联系系统管理员");
	}

}
