package net.wicp.tams.duckula.ops.pages.cas;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.util.TextStreamResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import cn.hutool.crypto.digest.BCrypt;
import net.wicp.tams.app.duckula.controller.bean.models.SysOrg;
import net.wicp.tams.app.duckula.controller.bean.models.SysUser;
import net.wicp.tams.app.duckula.controller.dao.SysUserMapper;
import net.wicp.tams.app.duckula.controller.service.cas.impl.OrgService;
import net.wicp.tams.cas.bean.constant.ColsSysOrg;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.CollectionUtil;
import net.wicp.tams.common.apiext.PwdUtil;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.apiext.json.EasyUiAssist;
import net.wicp.tams.common.callback.IConvertValue;
import net.wicp.tams.common.callback.impl.convertvalue.ConvertValueEnum;
import net.wicp.tams.common.constant.dic.Gender;
import net.wicp.tams.common.constant.dic.YesOrNo;
import net.wicp.tams.common.jdbc.convert.ConvertValueMysql;
import net.wicp.tams.component.tools.TapestryAssist;
import net.wicp.tams.duckula.ops.pages.ParentPageBean;

public class UserManager extends ParentPageBean<SysUser> {

	@Inject
	private SysUserMapper sysUserMapper;

	@SuppressWarnings("rawtypes")
	public TextStreamResponse onQuery() {
		org.apache.tapestry5.json.JSONObject params = TapestryAssist.packParams(request, true);
		String userName = params.getString("userName");
		org.apache.tapestry5.json.JSONArray orgIds = TapestryAssist.getParams(params, "orgId");
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>();
		if (StringUtils.isNotBlank(userName)) {
			queryWrapper.likeLeft("user_name", userName);
		}
		if (orgIds != null && orgIds.size() > 0) {
			List<Long> orglist = new ArrayList<Long>();
			for (int i = 0; i < orgIds.size(); i++) {
				orglist.add(Long.parseLong(orgIds.getString(i)));
			}
			queryWrapper.in("org_id", orglist);
		}
		List<SysUser> users = this.sysUserMapper.selectList(queryWrapper);
		ConvertValueMysql orgconv = new ConvertValueMysql(ColsSysOrg.tb, ColsSysOrg.orgName.getOriColName());
		Map<String, IConvertValue> map = new HashMap<String, IConvertValue>();
		map.put("orgId1", orgconv);
		map.put("status1", new ConvertValueEnum(YesOrNo.class));
		map.put("gender1", new ConvertValueEnum(Gender.class));
		String str = EasyUiAssist.getJsonForGridAlias2(users,
				new String[] { "orgId,orgId1", "status,status1", "gender,gender1" }, map, users.size());
		return retStream(str);
	}

	@Override
	public void packageQuery(SysUser t, QueryWrapper<SysUser> queryWrapper) {
		if (StringUtil.isNotNull(t.getUserName())) {
			queryWrapper.likeRight("user_name", t.getUserName());
		}

	}

	@Override
	protected Pair<String[], Map<String, IConvertValue>> packageConvert() {
		ConvertValueMysql orgCv = new ConvertValueMysql(ColsSysOrg.tb, ColsSysOrg.orgName.getOriColName());
		return Pair.of(new String[] { "orgId,orgId1", "status,status1", "gender,gender1" },
				CollectionUtil.newMap("orgId1", orgCv, "status1", new ConvertValueEnum(YesOrNo.class), "gender1",
						new ConvertValueEnum(Gender.class)));
	}

	public TextStreamResponse onSavePwd() {
		Long id = Long.parseLong(request.getParameter("id"));
		String pwdNew = request.getParameter("pwdNew");
		String pwdNew2 = request.getParameter("pwdNew2");

		if (!pwdNew.equals(pwdNew2)) {
			return TapestryAssist.getTextStreamResponse(Result.getError("密码2次需要一致"));
		}
		String pwdOld = request.getParameter("pwdOld");
		if (StringUtil.isNotNull(pwdOld)) {
			if (pwdOld.equals(pwdNew)) {
				return TapestryAssist.getTextStreamResponse(Result.getError("旧密码与新密码不能相同"));
			}
			SysUser sysUser = this.sysUserMapper.selectById(id);
			// 要不要检查旧密码
			boolean checkpw = BCrypt.checkpw(pwdOld, sysUser.getPassword());
			if (!checkpw) {
				return TapestryAssist.getTextStreamResponse(Result.getError("旧密码错误！"));
			}
		}
		SysUser user = new SysUser();
		user.setId(id);
		user.setPassword(PwdUtil.hashpw(pwdNew));
		this.sysUserMapper.updateByPrimaryKeySelective(user);
		return TapestryAssist.getTextStreamResponse(Result.getSuc());
	}

	public TextStreamResponse onResertPwd() {
		Long id = Long.parseLong(request.getParameter("id"));
		SysUser user = new SysUser();
		user.setId(id);
		user.setPassword(PwdUtil.hashpw("123456"));
		this.sysUserMapper.updateByPrimaryKeySelective(user);
		return TapestryAssist.getTextStreamResponse(Result.getSuc());
	}

	@Override
	public void doSave(SysUser t, boolean isInsert) {
		if (isInsert) {
			t.setPassword(PwdUtil.hashpw("123456"));// 初始化密码
			this.sysUserMapper.insert(t);
		} else {
			t.setPassword(null);// 不能修改密码
			this.sysUserMapper.updateByPrimaryKeySelective(t);
		}
	}

	@Override
	public void doDel(String id) {
		this.sysUserMapper.deleteById(id);
	}

	@Override
	public BaseMapper<SysUser> getBaseMapper() {
		return this.sysUserMapper;
	}

	@Property
	private String orgTree;

	@Property
	private String orgId;

	@Inject
	private OrgService orgService;

	@SetupRender
	void init() {
		orgTree = orgService.createOrgTree(new IConvertValue<Object>() {
			@Override
			public String getStr(Object obj) {
				SysOrg org = (SysOrg) obj;
				String key = org.getOrgName();
				if (StringUtil.isNull(key) || !messages.contains(key)) {
					return key;
				}
				return messages.get(key);
			}
		});
		orgId = request.getParameter("orgId");
		System.out.println("orgId=" + orgId);
	}

}
