package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.beans.response.DepartmentResponse;
import com.house365.ws.dao.interfaces.IUserDao;
import com.house365.ws.interfaces.server.IDepartment;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.util.PathUtil;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author
 * Created by Administrator on 2018/9/27.
 */
@Service("getUsersByName")
public class GetUsersByNameImpl implements IGetUsersByName {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetUsersByNameImpl.class);

    @Autowired
    private IUserDao userDao;

    @Autowired
    private IDepartment department;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<UserEntity> response = new House365RestResponse<>();
        // 业务层统一处理
        try {
            House365RestObject<UserEntity> restObject = new House365RestObject<>();
            String realName = getMapValueByKey("realName", map, "");
            String city = getMapValueByKey("city", map, "");
            Map<String,Object> map1 = new HashMap<>();
            map1.put("realName",realName);
            List<UserEntity> list = userDao.queryByName(map1);

            if(CollectionUtils.isNotEmpty(list)) {
                for (UserEntity u : list) {
                    //获取城市
                    DepartmentResponse departmentResponse = department.getDepartmentById(u.getDeptId());
                    DepartmentEntity dept = departmentResponse.getEntity();
                    Integer realDept = PathUtil.extractDept(dept.getUrlPath());
                    if (!u.getDeptId().equals(realDept)) {
                        dept = department.getDepartmentById(realDept).getEntity();
                    }
                    String cityId = dept.getCityID();
                    DepartmentResponse departmentResponse2 = department.getDepartmentById(Integer.valueOf(cityId));
                    String cityCode = departmentResponse2.getEntity().getDescripition();
                    u.setCity(cityCode);
                }
            }

            if(CollectionUtils.isNotEmpty(list) && StringUtils.isNotBlank(city)){
                Iterator<UserEntity> iterator = list.iterator();
                while(iterator.hasNext()){
                    UserEntity u = iterator.next();
                    if(StringUtils.isBlank(u.getCity()) || (StringUtils.isNotBlank(u.getCity()) && !u.getCity().equals(city))){
                        iterator.remove();
                    }
                }
            }
            restObject.setList(list);
            response.setData(restObject);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        return JSONObject.fromObject(response).toString();
    }

    @Override
    public boolean isControlService() {
        return false;
    }

    @Override
    public boolean isLogService() {
        return false;
    }

    @Override
    public boolean isMonitorService() {
        return false;
    }

    @Override
    public Object rollback() {
        return null;
    }

    @Override
    public void commit() {

    }

    /**
     * 获取map中的值
     *
     * @param key          key
     * @param map          map
     * @param defaultValue 默认值
     * @return value
     */
    private String getMapValueByKey(String key, Map<String, Object> map, String defaultValue) {
        String value = "";
        if (map.containsKey(key) && map.get(key) != null && !Strings.isNullOrEmpty(((String[]) map.get(key))[0])) {
            value = ((String[]) map.get(key))[0];
        }

        if (Strings.isNullOrEmpty(value)) {
            value = defaultValue;
        }
        return value;
    }
}
