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

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.SpringUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * 控制器支持类
 * @version 2019-11-15
 */
public abstract class BaseController {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected Map<String, String> getParams(HttpServletRequest request){
		// 参数Map
	    Map properties = request.getParameterMap();
	    // 返回值Map
		Map<String, String> returnMap = new HashMap();
	    Iterator entries = properties.entrySet().iterator();
	    Map.Entry entry;
	    String name = "";
	    String value = "";
	    while (entries.hasNext()) {
	        entry = (Map.Entry) entries.next();
	        name = (String) entry.getKey();
	        Object valueObj = entry.getValue();
	        if(null == valueObj){
	            value = "";
	        }else if(valueObj instanceof String[]){
	        	StringBuilder tmpVal = new StringBuilder();
	            String[] values = (String[])valueObj;
	            for(int i=0;i<values.length;i++){
	                //value = values[i] + ",";
	                tmpVal.append(",").append(values[i]);
	            }
	            if(name.indexOf("[]") != -1){
	            	name = name.replaceAll("\\[\\]", "");
	            }
	            //value = value.substring(0, value.length()-1);
	            if(StringUtils.isNotBlank(tmpVal.toString())){
	            	value = tmpVal.substring(1);
	            }else{
	            	value = "";
	            }
	        }else{
	            value = valueObj.toString();
	        }
	        returnMap.put(name, value);
	    }
	    return returnMap;
	}

	protected User getUserBy(HttpServletRequest request) {
		String userId = request.getParameter("userId");
		return getUserBy(userId);
	}

	protected User getUserBy(String userId) {
		UserDao userDao = SpringUtils.getBean(UserDao.class);
		if (StrKit.isBlank(userId)) {
			throw new BusinessException("userId不能为空");
		}
		User user = userDao.get(userId);
		if (user == null) {
			user = userDao.getById(userId);
		}
		if (user == null) {
			throw new BusinessException("用户不存在");
		}
		if (!"0".equals(user.getStatus())) {
			throw new BusinessException("当前账号已禁用或已删除，不可操作！");
		}
		return user;
	}

	protected Operator getOperatorBy(HttpServletRequest request) {
		String userId = request.getParameter("userId");
		return getOperatorByTwo(userId);
	}

	protected Operator getOperatorByTwo(String userId) {
		User user = getUserBy(userId);
		if(User.USER_TYPE_ADVISOR.equals(user.getUserType())){  //代理商人员
			Record r= Db.findFirst("SELECT name,role_name FROM `crm_trader_employe` WHERE user_id=?",user.getId());
			return Operator.of(user.getId(), r.getStr("name"), user.getUserType(),r.getStr("role_name"));
		}
		if (User.USER_TYPE_WXG.equals(user.getUserType())){  //平台人员
			Record emp = Db.findFirst("SELECT name, id FROM `crm_platform_employee` WHERE user_id=?",user.getId());
			String roleName = Db.queryStr(
					"SELECT GROUP_CONCAT(er.name) as role_name " +
							" FROM crm_platform_employee_role er, crm_platform_employee_role_rel r" +
							" WHERE r.`employee_id` = ? AND FIND_IN_SET(er.id, r.role_ids)", emp.getStr("id"));
			return Operator.of(user.getId(), emp.getStr("name"), user.getUserType(), roleName);
		}
		return Operator.of(user.getId(), CrmUtils.getUserXM(user), user.getUserType(),"");
	}

	protected Object renderJson(Object o){
		return JsonKit.toJson(o);
	}
}
