/**
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.sifang.modules.sys.dao;

import com.jfinal.plugin.activerecord.Db;


import java.util.List;
import java.util.Map;

import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Page;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.util.SqlBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.jfinal.plugin.activerecord.Record;


/**
 * 用户DAO接口
 * @version 2019-11-15
 */
@Repository(value="userDao")
public class UserDao extends BaseDao<User> {
	
	public List<User> findAllList() {
		return find("from User where status=:p1 order by id", new Parameter(User.DEL_FLAG_NORMAL));
	}
	
	public User findByLoginName(String loginName){
		return getByHql("from User where loginName = :p1 and status = :p2", new Parameter(loginName, User.DEL_FLAG_NORMAL));
	}

	public User findByMobile(String mobile) {
		return getByHql("from User where mobile = :p1 and status = :p2", new Parameter(mobile, User.DEL_FLAG_NORMAL));
	}

	public User findByMail(String mail) {
		return getByHql("from User where email = :p1 and status = :p2", new Parameter(mail, User.DEL_FLAG_NORMAL));
	}

	/**
	 * 通过唯一邮箱验证码和邮箱来找用户
	 */
	public User findByToken(String mail, String token) {
		Record userRecord = Db.findFirst("select * from sys_user where email=? and reset_pwd_token=? and status=?", mail, token, User.DEL_FLAG_NORMAL);
		User user = new User();
		if (userRecord != null) {
			user.setId(userRecord.getStr("id"));
			user.setLoginName(userRecord.getStr("login_name"));
			user.setMobile(userRecord.getStr("mobile"));
		}
		return userRecord == null ? null : user;
	}

	public int updatePasswordById(String newPassword, String id){
		return update("update User set password=:p1 where id = :p2", new Parameter(newPassword, id));
	}
	
	/**
	 * 将record中的Long类型属性的值取出来.
	 *
	 * @param record the record
	 * @param attr 属性名称
	 * @return 默认为long类型的最小值
	 */
	public long getRecordLongValue(Record record, String attr)
	{
		long value = Long.MIN_VALUE;
		if(record != null && attr != null && !attr.isEmpty())
		{
			Long valueL = record.getLong(attr);
			if(valueL != null)
				value = valueL.longValue();
		}
		return value;
	}

	
	//根据登录名和id两个条件查询User
	public User findByLoginNameId(String loginName, String userId) {
		return getByHql("from User where loginName = :p1 and status = :p2 and id!=:p3 ", new Parameter(loginName, User.DEL_FLAG_NORMAL,userId));
	}


	//获取区域人员列表
	public List<Record> getAllDistrict(Page<Record> page, Map<String, Object> map) {
		StringBuffer sb = new StringBuffer();
		sb.append("select a.*,b.name,b.share_code,b.share_count,b.region from sys_user a ");
		sb.append(" left join crm_serviceman b on a.id=b.user_id ");
		sb.append(" where a.status='0' and a.user_type='4' and b.status='0' ");
		sb.append(querySource(map));
		sb.append(" order by a.create_date desc ");
		sb.append(" limit " + page.getPageSize() + " offset " + (page.getPageNo() - 1) * page.getPageSize());
		return Db.find(sb.toString());
	}
	public long getAllDistrictCount(Map<String, Object> map) {
		StringBuffer sb = new StringBuffer();
		sb.append("select count(*) from sys_user a ");
		sb.append(" left join crm_serviceman b on a.id=b.user_id ");
		sb.append(" where a.status='0' and a.user_type='4' and b.status='0' ");
		return Db.queryLong(sb.toString());
	}


	public String querySource(Map<String, Object> map) {
		if (map == null) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		if (StringUtils.isNotBlank((CharSequence) map.get("name"))) {
			sb.append(" and b.name='" + map.get("name") + "' ");
		}
		if(StringUtils.isNotBlank((CharSequence) map.get("mobile"))){
			sb.append(" and a.mobile='" + map.get("mobile") + "' ");
		}
		if(StringUtils.isNotBlank((CharSequence) map.get("region"))){
			sb.append(" and b.region like '%" + map.get("region") + "%' ");
		}

		return sb.toString();
	}

	public User getById(String id){
		return getByHql(" from User where id = :p1 and status = :p2 ", new Parameter(id, User.DEL_FLAG_NORMAL));
	}

	/*public User getUserVsDetail(){}*/

	public boolean isDefaultRole(String userId){
		SqlBuilder builder = new SqlBuilder();
		builder.line("select e.id")
				.line("from crm_platform_employee e")
				.line("inner join crm_platform_employee_role_rel er on e.id=er.employee_id")
				.line("and exists(select 1 from crm_platform_employee_role r where r.type in ('1', '2','c','b','d') and find_in_set(r.id, er.role_ids))")
				.line("and e.user_id=?", userId)
				.line("limit 1");
		return Db.findFirst(builder.build(), builder.params()) != null;
	}

	public long isDefaultPlatRole(String userId){
		SqlBuilder builder = new SqlBuilder();
		builder.line("select count(*) ")
				.line("from crm_platform_employee e")
				.line("inner join crm_platform_employee_role_rel er on e.id=er.employee_id")
				.line("and exists(select 1 from crm_platform_employee_role r where find_in_set(r.id, er.role_ids))")
				.line("and e.user_id=?", userId);
		return Db.queryLong(builder.build(), builder.params());
	}


	public boolean isProjectEmp(String userId){
		SqlBuilder builder = new SqlBuilder();
		builder.line("select e.id")
				.line("from crm_platform_employee e")
				.line("inner join crm_platform_employee_role_rel er on e.id=er.employee_id")
				.line("and exists(select 1 from crm_platform_employee_role r where r.type = '2' and find_in_set(r.id, er.role_ids))")
				.line("and e.user_id=?", userId)
				.line("limit 1");
		return Db.findFirst(builder.build(), builder.params()) != null;
	}

	//查找平台用户角色类型
	public String findPlatUserRoleType(String userId) {
		User user = get(userId);
		if (!"4".equals(user.getUserType())) {
			throw new IllegalArgumentException("非平台员工用户");
		}
		SqlBuilder builder = new SqlBuilder();
		builder.line("select r.role_ids")
				.line("from crm_platform_employee e")
				.line("inner join crm_platform_employee_role_rel r on e.id=r.employee_id")
				.line("where e.status='0' and e.user_id=?", userId);
		String roleIds = Db.queryStr(builder.build(), builder.params());

		builder = new SqlBuilder();
		builder.line("select r.type")
				.line("from crm_platform_employee_role r")
				.inst("where r.status='0' and r.id in", roleIds.split(","))
				.line("limit 1");
		return Db.queryStr(builder.build(), builder.params());
	}

	/**
	 * 启用/禁用二级代理商员工账号
	 */
	public void updateStatusByIds(List<String> ids, String oldStatus, String status) {
		update("update User set status = :p1 where id in :p2 and status = :p3 ", new Parameter(status, ids, oldStatus));
	}
}
