package com.malk.jinlun.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.malk.jinlun.config.CloudpivotConfig;
import com.malk.jinlun.service.CpClient;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class CpClientImpl implements CpClient {
    @Autowired
    private CloudpivotConfig cloudpivotConfig;

    /**
     * 云枢获取token
     * @return
     */
    @Override
    public String getCpAccessToken(){
        String accessToken = UtilToken.get("invalid-token-cloudpivot");

        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        } else {
            Map<String,Object> params = new HashMap();
            params.put("grant_type",cloudpivotConfig.getGrantType());
            params.put("client_id",cloudpivotConfig.getClientId());
            params.put("client_secret",cloudpivotConfig.getClientSecret());

            String s = UtilHttp.doPost(cloudpivotConfig.getRedirectUri()+"oauth/token", null, params, new HashMap());

            Map result = (Map) JSONObject.parse(s);

            accessToken = "bearer" + UtilMap.getString(result, "access_token");

            long expiresIn = UtilMap.getLong(result, "expires_in") * 1000;

            UtilToken.put("invalid-token-cloudpivot", accessToken, expiresIn);

            return accessToken;
        }
    }

    /**
     * 云枢新增表单
     * @param schemaCode
     * @param data
     * @param userId
     * @return
     */
    @Override
    public Map createCpBo(String schemaCode, Map data, String userId){
        Map body = new HashMap();

        body.put("data",data);
        body.put("schemaCode",schemaCode);
        if (Strings.isNullOrEmpty(userId)){
            body.put("userId",cloudpivotConfig.getOperatorUserId());
        }else {
            body.put("userId",userId);
        }

        String s = UtilHttp.doPost(cloudpivotConfig.getRedirectUri() + "openapi/v3/bo/create", CloudpivotConfig.initTokenHeader(getCpAccessToken()), null, body);

        Map result = (Map) JSONObject.parse(s);

        return result;
    }

    /**
     * 云枢更新表单
     * @param schemaCode
     * @param data
     * @param userId
     * @return
     */
    @Override
    public Map updateCpBo(String schemaCode, Map data, String userId) {
        Map body = new HashMap();

        body.put("data", data);
        body.put("schemaCode", schemaCode);
        if (Strings.isNullOrEmpty(userId)) {
            body.put("userId", cloudpivotConfig.getOperatorUserId());
        } else {
            body.put("userId", userId);
        }

        String s = UtilHttp.doPost(cloudpivotConfig.getRedirectUri() + "openapi/v3/bo/update", CloudpivotConfig.initTokenHeader(getCpAccessToken()), null, body);

        Map result = (Map) JSONObject.parse(s);

        return result;
    }

    /**
     * 云枢获取表单详情
     * @param schemaCode
     * @param objectId
     * @param userId
     * @return
     */
    @Override
    public Map getCpBo(String schemaCode, String objectId, String userId){
        Map body = new HashMap();

        body.put("objectId",objectId);
        body.put("schemaCode",schemaCode);
        if (Strings.isNullOrEmpty(userId)){
            body.put("userId",cloudpivotConfig.getOperatorUserId());
        }else {
            body.put("userId",userId);
        }

        String s = UtilHttp.doPost(cloudpivotConfig.getRedirectUri() + "openapi/v3/bo/get", CloudpivotConfig.initTokenHeader(getCpAccessToken()), null, body);

        Map result = (Map) JSONObject.parse(s);

        isSuccess(result);

        return result;
    }

    /**
     * 云枢获取表单列表
     * @param schemaCode
     * @param queryCondition
     * @param page
     * @param size
     * @param userId
     * @return
     */
    @Override
    public Map getCpBoList(String schemaCode, Map queryCondition, Map options,int page, int size, String userId){
        Map body = new HashMap();

        body.put("queryCondition",queryCondition);
        body.put("schemaCode",schemaCode);
        body.put("options",options);
        body.put("page",page);
        body.put("size",size);
        body.put("showTotal",true);

        System.out.println("cloudpivotConfig"+cloudpivotConfig);
        if (Strings.isNullOrEmpty(userId)){
            body.put("userId",cloudpivotConfig.getOperatorUserId());
        }else {
            body.put("userId",userId);
        }

        String s = UtilHttp.doPost(cloudpivotConfig.getRedirectUri() + "openapi/v3/bo/list", CloudpivotConfig.initTokenHeader(getCpAccessToken()), null, body);

        Map result = (Map) JSONObject.parse(s);

        isSuccess(result);

        return result;
    }

    /**
     * 云枢分页查询用户详情
     * @param corpId
     * @param departmentIds
     * @param ids
     * @param mobile
     * @param name
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<Map> getCpUserInfo(String corpId, List<String> departmentIds, List<String> ids, String mobile, String name, int page, int size) {
        Map body = new HashMap();
        if (Objects.nonNull(corpId)) body.put("corpId",corpId);
        if (Objects.nonNull(departmentIds)) body.put("departmentIds",departmentIds);
        if (Objects.nonNull(ids)) body.put("ids",ids);
        if (Objects.nonNull(mobile)) body.put("mobile",mobile);
        if (Objects.nonNull(name)) body.put("name",name);

        body.put("page",page);
        body.put("size",size);

        String s = UtilHttp.doPost(cloudpivotConfig.getRedirectUri() + "openapi/v3/organization/user/detail/query", CloudpivotConfig.initTokenHeader(getCpAccessToken()), null, body);

        Map result = (Map) JSONObject.parse(s);

        isSuccess(result);

        Map data = UtilMap.getMap(result, "data");

        List<Map> content = UtilMap.getList(data, "content");

        return content;
    }

    @Override
    public List<Map> getCpDepartmentInfo() {
        String s = UtilHttp.doPost(cloudpivotConfig.getRedirectUri() + "openapi/v3/organization/department/query", CloudpivotConfig.initTokenHeader(getCpAccessToken()), null, new HashMap());

        Map result = (Map) JSONObject.parse(s);

        isSuccess(result);

        Map data = UtilMap.getMap(result, "data");

        List<Map> content = UtilMap.getList(data, "content");

        return content;
    }


    //获取云枢表单详情返回结果中单据字段值
    @Override
    public Map getCpBoResultData(Map result){
        Map data = UtilMap.getMap(result, "data");

        Map bizObject = UtilMap.getMap(data, "bizObject");

        Map resultData = UtilMap.getMap(bizObject, "data");

        return resultData;
    }

    @Override
    public void isSuccess(Map result){
        int errcode = UtilMap.getInt(result, "errcode");
        String errmsg = UtilMap.getString(result, "errmsg");

        if (errcode != 0){
            throw new RuntimeException("云枢接口调用失败：" + errmsg);
        }
    }

}
