/**
 * 请勿将俱乐部专享资源复制给任何人，保护知识产权即是保护我们所在的行业，进而保护我们自己的利益
 * 即便是公司的同事，也请尊重 JFinal 作者的努力与付出，不要复制给同事
 * 
 * 如果你尚未加入俱乐部，请立即删除该项目，或者现在加入俱乐部：http://jfinal.com/club
 * 
 * 俱乐部将提供 jfinal-club 项目源码、直播视频、专用 QQ 群，以及作者在俱乐部定期的分享与答疑，
 * 价值远比仅仅拥有 jfinal club 项目源代码要大得多，俱乐部福利资源是不断增加的，以下是俱乐部
 * 新福利计划：
 * https://jfinal.com/club/1-2
 * 
 * JFinal 俱乐部是七年以来首次寻求外部资源的尝试，以便于创建更加高品质的产品与服务，为你带来
 * 更多、更大的价值
 * 
 * JFinal 项目的可持续性发展需要你的支持！！！
 */

package com.jfinal.club._admin.account;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.club._admin.role.RoleAdminService;
import com.jfinal.club.common.account.AccountService;
import com.jfinal.club.common.model.Role;
import com.jfinal.club.common.model.Users;
import com.jfinal.club.my.setting.MySettingService;
import com.jfinal.club.util.Cons;
import com.jfinal.kit.HashKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.club.common.controller.BaseController;
import com.jfinal.kit.Ret;
import com.jfinal.club.common.model.Account;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Random;

/**
 * 账户管理控制器
 */
public class AccountAdminController extends BaseController {

	@Inject
	AccountAdminService srv;
	
	@Inject
	MySettingService mySettingSrv;
	
	@Inject
	RoleAdminService roleAdminSrv;
	
	@Inject
	AccountService accountSrv;

	public void index() {
		//搜索条件
		String sname = get("sname");
		Integer spay = getInt("spay");
		setAttr("sname",sname);
		setAttr("spay",spay);
		if(spay != null && spay== -1){
			spay = null;
		}
		if(StringUtils.isBlank(sname) && spay == null){
			Page< Users > paginate = new Users( ).dao( ).paginate(getInt("p", 1), Cons.ADMIN_PAGE_SIZE, "select * ", "from (select a.*,b.pay from (select * from users order by addtime desc) a left join (select * from download where pay != 0) b on a.id = b.usersid group by a.id) a ");
			setAttr("usersPage", paginate);
		}else{

			if(StringUtils.isNotBlank(sname) && spay != null){
				String name = "%"+sname.trim()+"%";
				String phone = sname.trim();
				if(spay == 1){
					Page< Users > paginate = new Users( ).dao( ).paginate(getInt("p", 1), Cons.ADMIN_PAGE_SIZE, "select * ", "from (select a.*,b.pay from (select * from users order by addtime desc) a left join (select * from download where pay != 0) b on a.id = b.usersid group by a.id) a where nickname like ? or phone = ? and pay = ? ",name,phone,spay);
					setAttr("usersPage", paginate);
				}else{
					Page< Users > paginate = new Users( ).dao( ).paginate(getInt("p", 1), Cons.ADMIN_PAGE_SIZE, "select * ", "from (select a.*,b.pay from (select * from users order by addtime desc) a left join (select * from download where pay != 0) b on a.id = b.usersid group by a.id) a where nickname like ? or phone = ? and pay is null ",name,phone,spay);
					setAttr("usersPage", paginate);
				}
			}

			if(spay == null && StringUtils.isNotBlank(sname)){
				String name = "%"+sname.trim()+"%";
				String phone = sname.trim();
				Page< Users > paginate = new Users( ).dao( ).paginate(getInt("p", 1), Cons.ADMIN_PAGE_SIZE, "select * ", "from (select a.*,b.pay from (select * from users order by addtime desc) a left join (select * from download where pay != 0) b on a.id = b.usersid group by a.id) a where nickname like ? or phone = ? ",name,phone);
				setAttr("usersPage", paginate);
			}

			if(StringUtils.isBlank(sname) && spay != null){
				if(spay == 1){
					Page< Users > paginate = new Users( ).dao( ).paginate(getInt("p", 1), Cons.ADMIN_PAGE_SIZE, "select * ", "from (select a.*,b.pay from (select * from users order by addtime desc) a left join (select * from download where pay != 0) b on a.id = b.usersid group by a.id) a where pay = ? ",spay);
					setAttr("usersPage", paginate);
				}else{
					Page< Users > paginate = new Users( ).dao( ).paginate(getInt("p", 1), Cons.ADMIN_PAGE_SIZE, "select * ", "from (select a.*,b.pay from (select * from users order by addtime desc) a left join (select * from download where pay != 0) b on a.id = b.usersid group by a.id) a where pay is null ");
					setAttr("usersPage", paginate);
				}
			}

		}

		render("index.html");
	}

	/**
	 * lc 2020.4.29
	 * 后台重置密码-生成随机密码
	 */
	public void resetPassword(){
		//生成随机密码
		String password = randomPassword(6);
		Integer id = getInt("id");
		Users users = new Users( ).dao( ).findById(id);
		users.setPwds(password);
		users.removeNullValueAttrs().update();
		renderJson(Ret.ok("data",password));
	}

	/**
	 * lc 2020.4.29
	 * 上锁
	 */
	public void lock_t(){
		new Users( ).dao( ).findById(getInt("id")).set("lock",1).removeNullValueAttrs().update();
		index();
	}

	/**
	 * lc2020.4.29
	 * 解锁
	 */
	public void lock_f(){
		new Users( ).dao( ).findById(getInt("id")).set("lock",0).removeNullValueAttrs().update();
		index();
	}

	/**
	 * 生成n位随机密码
	 * @param countNumber
	 * @return
	 */
	private static String randomPassword(int countNumber){
		String str = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9";
		String[] s = str.split(",");
		StringBuilder password= new StringBuilder();
		try {
			Random random = new Random( );
			for (int i = 0; i < countNumber; i++) {
				int r = random.nextInt(s.length);
				String v = s[r];
				password.append(v);
			}
			return password.toString();
		} catch (Exception e) {
			//报错就生成6个零
			return "000000";
		}
	}

	public void edit() {
		keepPara("p");	// 保持住分页的页号，便于在 ajax 提交后跳转到当前数据所在的页
		Users users = new Users( ).dao( ).findById(getInt("id"));
		setAttr("users",users);
		render("edit.html");
	}

	/**
	 * 提交修改
	 */
	public void update() {
		getBean(Users.class).removeNullValueAttrs().update();
		renderJson(Ret.ok("msg","修改成功"));
	}

//	/**
//	 * 账户锁定
//	 */
//	public void lock() {
//		Ret ret = srv.lock(getLoginAccountId(), getParaToInt("id"));
//		renderJson(ret);
//	}

	/**
	 * 账户解锁
	 */
	public void unlock() {
		Ret ret = srv.unlock(getParaToInt("id"));
		renderJson(ret);
	}

	/**
	 * 分配角色
	 */
	public void assignRoles() {
		Account account = srv.findById(getParaToInt("id"));
		List<Role> roleList = roleAdminSrv.getAllRoles();
		srv.markAssignedRoles(account, roleList);

		setAttr("account", account);
		setAttr("roleList", roleList);
		render("assign_roles.html");
	}

	/**
	 * 添加角色
	 */
	public void addRole() {
		Ret ret = srv.addRole(getParaToInt("accountId"), getParaToInt("roleId"));
		renderJson(ret);
	}

	/**
	 * 删除角色
	 */
	public void deleteRole() {
		Ret ret = srv.deleteRole(getParaToInt("accountId"), getParaToInt("roleId"));
		renderJson(ret);
	}

	/**
	 * 显示 "后台账户/管理员" 列表，在 account_role 表中存在的账户(被分配过角色的账户)
	 * 被定义为 "后台账户/管理员"
	 *
	 * 该功能便于查看后台都有哪些账户被分配了角色，在对账户误操作分配了角色时，也便于取消角色分配
	 */
	public void showAdminList() {
		List<Record> adminList = srv.getAdminList();
		setAttr("adminList", adminList);
		render("admin_list.html");
	}

	public void avatar() {
		keepPara("p");	// 保持住分页的页号，便于在 ajax 提交后跳转到当前数据所在的页
		Users users = new Users( ).dao( ).findById(getParaToInt("id"));
		setAttr("users", users);
		render("avatar.html");
	}

	/**
	 * 进入admin修改密码界面
	 */
	public void editPassword(){
		Account account = srv.findById(getParaToInt("id"));
		setAttr("account",account);
		render("editPassword.html");
	}

	/**
	 * 修改密码
	 */
	public void updateAdmin(){
		Account account = srv.findById(getParaToInt("id"));
		String pwd = get("pwd");

		String salt = account.getSalt( );
		if(StringUtils.isBlank(salt)){
			salt = HashKit.generateSaltForSha256();
			account.setSalt(salt);
		}
		String password = HashKit.sha256(salt + pwd);
		account.setPassword(password);
		boolean update = account.update( );
		if(update){
			renderJson(Ret.ok("msg","密码修改成功"));
		}else{
			renderJson(Ret.fail("msg","密码修改失败"));
		}
	}

	/**
	 * 交易记录列表
	 */
	public void jylist(){
		Integer id = getInt("id");
		List< Record > records = Db.find("select a.*,b.docname docName, b.docmoney from download a,doc b where a.docid = b.id and pay = 1 and a.usersid = ? ",id);
		setAttr("doc",records);
		render("jylist.html");
	}

	/**
	 * 上传用户图片，为裁切头像做准备
	 */
	public void uploadAvatar() {
		UploadFile uf = null;
		try {
			uf = getFile("avatar", mySettingSrv.getAvatarTempDir(), mySettingSrv.getAvatarMaxSize());
			if (uf == null) {
				renderJson(Ret.fail("msg", "请先选择上传文件"));
				return;
			}
		} catch (Exception e) {
			if (e instanceof com.jfinal.upload.ExceededSizeException) {
				renderJson(Ret.fail("msg", "文件大小超出范围"));
			} else {
				if (uf != null) {
					// 只有出现异常时才能删除，不能在 finally 中删，因为后面需要用到上传文件
					uf.getFile().delete();
				}
				renderJson(Ret.fail("msg", e.getMessage()));
			}
			return ;
		}

		// 注意这里可以更换任意用户的头像，所以并非 getLoginAccountId()
		int usersId = getParaToInt("usersId");
		Ret ret = mySettingSrv.uploadAvatar(usersId, uf);
		if (ret.isOk()) {   // 上传成功则将文件 url 径暂存起来，供下个环节进行裁切
			setSessionAttr("avatarUrl", ret.get("avatarUrl"));
		}
		renderJson(ret);
	}

	/**
	 * 保存 jcrop 裁切区域为用户头像
	 */
	public void saveAvatar() {
		// 注意这里可以更换任意用户的头像，所以并非 getLoginAccountId()
		int usersId = getParaToInt("usersId");
		Users users = new Users( ).dao( ).findById(usersId);

		String avatarUrl = getSessionAttr("avatarUrl");
		int x = getParaToInt("x");
		int y = getParaToInt("y");
		int width = getParaToInt("width");
		int height = getParaToInt("height");
		Ret ret = mySettingSrv.saveAvatar(users, avatarUrl, x, y, width, height);
		renderJson(ret);
	}
}
