package com.bocloud.ims.service.internal;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.common.enums.BoCloudMethod;
import com.bocloud.common.enums.BoCloudService;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.BocloudToken;
import com.bocloud.common.model.Pager;
import com.bocloud.common.model.Param;
import com.bocloud.common.model.Sign;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.entity.common.User;
import com.bocloud.ims.entity.common.UserProject;
import com.bocloud.service.core.CurrentService;
import com.bocloud.service.core.Service;
import com.bocloud.service.http.core.ServiceFactory;
import com.bocloud.service.http.model.RemoteService;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * SOC用户内部访问
 *
 * @author wangyu
 * @version 1.0
 * @since 2020年2月5日
 */
@Component
public class SmsUserService implements InitializingBean {

    private Logger logger = LoggerFactory.getLogger(SmsUserService.class);
    @Autowired
    private ServiceFactory serviceFactory;
    @Autowired
    private CurrentService currentService;
    private static Service service = Service.create(BoCloudService.SMS);
    private Map<String, Object> headers = new HashMap<>(4);


    public BocloudResult<User> detail(Long id) {
        RemoteService remoteService = serviceFactory.build(service, "/v1/users/" + id, BoCloudMethod.GET, headers,
                null);
        BocloudResult result = remoteService.invoke();
        if (result.isFailed()) {
            return new BocloudResult<>(false, result.getMessage());
        }
        String data = JSONObject.toJSONString(result.getData());
        return new BocloudResult<>(true, JSONObject.parseObject(data, User.class), "success");
    }

    /**
     * 查询角色下用户
     */
    public BocloudResult listUsers(Long roleId, Pager pager) {
        String url = "/v1/roles/" + roleId + "/users";
        RemoteService remoteService = serviceFactory.build(service, url, BoCloudMethod.GET, headers, pager.toMap());
        BocloudResult result = remoteService.invoke();
        return result;
    }

    public List<User> listUsersByIds(List<Long> ids) {
        ArrayList<Param> params = null;
        if (null != ids && !ids.isEmpty()) {
            String idString = JSONArray.toJSONString(ids);
            params = Lists.newArrayList(new Param(MapTools.simpleMap("id", idString.substring(1, idString.length() - 1)), Sign.IN));
        }
        Map<String, Object> paramMap = MapTools.simpleMap("simple", false);
        paramMap.put("page", 1);
        paramMap.put("rows", Integer.MAX_VALUE);
        paramMap.put(Common.PARAMS, JSONArray.toJSONString(params));
        RemoteService remoteService = serviceFactory.build(service, "/v1/users", BoCloudMethod.GET, headers, paramMap);
        BocloudResult result = remoteService.invoke();
        if (result.isFailed()) {
            return new ArrayList<>();
        }
        String data = JSONObject.toJSONString(result.getData());
        return JSONObject.parseObject(data).getJSONArray("rows").toJavaList(User.class);
    }

    /**
     * 这个接口现在有可能不返回数据了，因为id=1的管理员在此接口被过滤掉了
     *
     * @return
     */
    public BocloudResult<List<User>> listAdminManager() {
        List<Param> params = Lists.newArrayList();
        Map<String, Object> paramMap = MapTools.simpleMap("simple", false);
        paramMap.put("page", 1);
        paramMap.put("rows", Integer.MAX_VALUE);
        paramMap.put(Common.PARAMS, JSONArray.toJSONString(params));
        RemoteService remoteService = serviceFactory.build(service, "/v1/users", BoCloudMethod.GET, headers,
                paramMap);
        BocloudResult result = remoteService.invoke();
        if (result.isFailed()) {
            return new BocloudResult<>(false, result.getMessage());
        }
        String data = JSONObject.toJSONString(result.getData());
        List<User> users = JSONObject.parseObject(data).getJSONArray("rows").toJavaList(User.class);
        return new BocloudResult<>(true, users, "success");
    }


    /**
     * 查询当前用户下授权的平台列表
     *
     * @param target
     * @return
     */
    public List<Long> listUserVendorIds(Long target) {
        JSONObject object = new JSONObject();
        object.put(Common.CONDITION, "listUserVendorIds");
        object.put("userId", target);
        RemoteService remote = serviceFactory.build(service, "/v1/vendor/group", BoCloudMethod.GET, headers,
                MapTools.simpleMap(Common.CONDITION, object.toJSONString()));
        BocloudResult result = remote.invoke();
        if (result.isFailed()) {
            return Lists.newArrayList();
        }
        String data = JSONObject.toJSONString(result.getData());
        if (StringUtils.isEmpty(data)) {
            return Lists.newArrayList();
        }
        return JSONArray.parseArray(data, Long.class);
    }

    public BocloudResult<UserProject> getUserProject(Long userId, Long projectId, Long tenantId) {
        JSONObject object = new JSONObject();
        object.put(Common.CONDITION, "getUserProject");
        object.put("userId", userId);
        object.put("projectId", projectId);
        object.put("tenantId", tenantId);
        RemoteService remote = serviceFactory.build(service, "/v1/users", BoCloudMethod.GET, headers,
                MapTools.simpleMap(Common.CONDITION, object.toJSONString()));
        BocloudResult result = remote.invoke();
        if (result.isFailed()) {
            return new BocloudResult<>(false, result.getMessage());
        }
        String data = JSONObject.toJSONString(result.getData());
        return new BocloudResult<>(true, JSONObject.parseObject(data, UserProject.class), "success");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.headers.put(BocloudToken.INTERNAL_TOKEN, currentService.getToken());
    }

}
