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.beans.system.Page;
import com.house365.beans.system.QueryParams;
import com.house365.beans.vo.WechatUserVo;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.beans.request.UserListRequest;
import com.house365.ws.beans.response.DepartmentResponse;
import com.house365.ws.beans.response.UserListResponse;
import com.house365.ws.interfaces.server.IDepartment;
import com.house365.ws.interfaces.server.IUser;
import com.house365.ws.service.interfaces.IUserService;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.util.Constant;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>Title: 客户-微信企业号接口</p>
 * <p>Description: </p>
 * <p>Date: 2017/2/4</p>
 *
 * @author XN
 * @version 1.0
 */
@Service("wechatUser")
public class UserWechat implements IUserWechat {

    private static final Logger LOGGER = LoggerFactory.getLogger("sysLog");

    @Autowired
    private IUserService<UserEntity> userService;

    @Autowired
    private IDepartment department;

    @Autowired
    private IUser iUer;

    @Override
    public Object getUserInfo(Map<String, Object> map) throws ServiceRunException {
        House365RestResponse<UserEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<UserEntity> data = doGetMyProject(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        return result;
    }

    /**
     * 获取置业顾问 派工用
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object getManagers(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<UserEntity> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {
            House365RestObject<UserEntity> data = doGetAssignManager(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        return result;
    }

    /**
     * 业务层统逻辑处理
     */
    private House365RestObject doGetMyProject(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        UserEntity userEntity = new UserEntity();

        String userId = getMapValueByKey(Constant.USER_ID, map, "");
        if (!Strings.isNullOrEmpty(userId)) {
            userEntity = userService.getById(Integer.valueOf(userId));
        }

        object.setEntity(userEntity);
        return object;
    }

    /**
     * 获取置业顾问
     * 业务层统逻辑处理
     */
    private House365RestObject<UserEntity> doGetAssignManager(Map<String, Object> map) throws Exception {

        House365RestObject object = new House365RestObject();
        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");

        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);
            //当前部门 所在城市ID
            String cityId = DepartmentEntity.getCityID(user.getDeptUrlPath());
            DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
            DepartmentEntity city = departmentResponse.getEntity();
            Map<String, Object> searchParams = new HashMap<String, Object>();
            String urlPath = "";
            //是总部员工，选择南京和下属所有部门员工 ， 非管理员，选登录用户下属所有部门员工
            if (user.getDeptId() == 1) {
                urlPath = "/1/2";
            } else {
                urlPath = user.getDeptUrlPath() + "/";
            }

            searchParams.put("LIKE_deptUrlPath", urlPath);
            Page page = new Page(Integer.MAX_VALUE);
            UserListRequest listRequest = new UserListRequest();
            listRequest.setPaging(page);
            listRequest.setOrderColumn("name");
            listRequest.setOrderMode("asc");
            listRequest.setSearchParams(searchParams);
            UserListResponse response = iUer.getUserList(listRequest);
            List<UserEntity> userList = response.getObjectList();
            userList.add(0, user);

            List<WechatUserVo> wechatUsers = new ArrayList<>();
            for (UserEntity userInfo : userList) {
                wechatUsers.add(
                        new WechatUserVo(userInfo.getId(), userInfo.getName(), userInfo.getRealName(), userInfo.getMobile(),
                                userInfo.getDeptId(), userInfo.getDeptName(), userInfo.getGender(),
                                userInfo.getStatus(), userInfo.getEnabled()));
            }

            object.setList(wechatUsers);
        }

        return object;
    }

    @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() {

    }

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        return null;
    }

    /**
     * 获取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;
    }

    /**
     * 业务层统校验自己所需参数是否存在
     * 所有参数都要存在
     *
     * @author hqc
     */
    protected void checkInterfaceParameter(
            Map<String, Object> map, String[] checkParams
    ) throws IllegalServiceParameterException {
        // 方法所需参数
        for (String str : checkParams) {
            // 如果不存在跳出 同时抛出相应异常
            if (!map.containsKey(str)) {
                throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
            }
        }
    }

    private UserEntity getUserEntity(String phone) {
        UserEntity user = null;
        Map<String, Object> qm = new HashMap<>();
        qm.put("EQ_mobile", phone);
        QueryParams queryParams = new QueryParams(qm);
        List<UserEntity> userEntities = userService.queryAll(queryParams);
        if (userEntities != null && !userEntities.isEmpty()) {
            user = userEntities.get(0);
        }
        return user;
    }

}
