package easydo.technology.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import easydo.technology.enums.RedisKeyEnum;
import easydo.technology.exception.BizException;
import easydo.technology.model.GldDept;
import easydo.technology.model.GldMember;
import easydo.technology.model.GldProject;
import easydo.technology.model.GldTenant;
import easydo.technology.util.HttpClientUtil;
import easydo.technology.utils.RedisUtils;
import easydo.technology.utils.StringUtil;
import lombok.extern.java.Log;

@Log
@Component
public class GLDMasterService {
    @Value("${GLD.host}")
    private String masterHost;
    @Value("${GLD.MASTER.getToken}")
    private String masterGetToken;
    @Value("${GLD.MASTER.getDept}")
    private String masterGetDept;
    @Value("${GLD.MASTER.getMember}")
    private String masterGetMember;
    @Value("${GLD.MASTER.getProject}")
    private String masterGetProject;
    @Value("${GLD.MASTER.getTenant}")
    private String masterGetTenant;
    @Value("${GLD.MASTER.authorization}")
    private String masterAuthorization;
    @Value("${tenantId_gld_master}")
    private String tenantId;
    @Resource
    RedisUtils redisUtils;

    public String getGetToken() {
        if (redisUtils.hasKey(RedisKeyEnum.KEY_CF_GLD_MASTER_GET_TOKEN.getValue())) {
            return redisUtils.get(RedisKeyEnum.KEY_CF_GLD_MASTER_GET_TOKEN.getValue()).toString();
        } else {
            String url = masterHost + masterGetToken;
            Map<String, String> header = new HashMap<>();
            header.put("Authorization", masterAuthorization);
            JSONObject object = HttpClientUtil.sendPOSTWithHeader(url, new JSONObject().toJSONString(), header);
            log.info("查询广联达主数据token的res======>" + object.toJSONString());
            String accessToken = object.getString("access_token");
            Integer expiresIn = object.getInteger("expires_in");
            if (StringUtil.isNotEmpty(accessToken) && StringUtil.isNotEmpty(expiresIn)) {
                redisUtils.set(RedisKeyEnum.KEY_CF_GLD_MASTER_GET_TOKEN.getValue(), accessToken, expiresIn - 600, TimeUnit.SECONDS);
                return accessToken;
            }
        }
        return null;
    }

    public void removeToken() {
        redisUtils.del(RedisKeyEnum.KEY_CF_GLD_MASTER_GET_TOKEN.getValue());
    }

    public List<GldDept> getGetDept() throws Exception {
        String token = getGetToken();
        if (StringUtil.isEmpty(token)) {
            throw new BizException("获取gld_token异常");
        }
        String url = masterHost + masterGetDept;
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", "Bearer " + token);
        header.put("X-CORAL-TENANT", tenantId);
        JSONArray array = HttpClientUtil.sendGETWithHeader_Arr(url, header);
        log.info("查询广联达主数据组织的res======>" + array.toJSONString());
        List<GldDept> list = new ArrayList<>();
        for (Object obj : array) {
            JSONObject object = (JSONObject) obj;
            formatTime(object);

            GldDept dept = JSONObject.parseObject(object.toJSONString(), GldDept.class);
            list.add(dept);
        }
        return list;
    }

    public List<GldMember> getGetMember() throws Exception {
        String token = getGetToken();
        if (StringUtil.isEmpty(token)) {
            throw new BizException("获取gld_token异常");
        }
        String url = masterHost + masterGetMember;
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", "Bearer " + token);
        header.put("X-CORAL-TENANT", tenantId);
        JSONArray array = HttpClientUtil.sendGETWithHeader_Arr(url, header);
        log.info("查询广联达主数据用户的res======>" + array.toJSONString());
        List<GldMember> list = new ArrayList<>();
        for (Object obj : array) {
            JSONObject object = (JSONObject) obj;
            formatTime(object);

            GldMember member = JSONObject.parseObject(object.toJSONString(), GldMember.class);
            list.add(member);
        }
        return list;
    }

    public List<GldProject> getGetProject() throws Exception {
        String token = getGetToken();
        if (StringUtil.isEmpty(token)) {
            throw new BizException("获取gld_token异常");
        }
        String url = masterHost + masterGetProject;
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", "Bearer " + token);
        header.put("X-CORAL-TENANT", tenantId);
        JSONArray array = HttpClientUtil.sendGETWithHeader_Arr(url, header);
        log.info("查询广联达主数据项目的res======>" + array.toJSONString());
        List<GldProject> list = new ArrayList<>();
        for (Object obj : array) {
            JSONObject object = (JSONObject) obj;
            formatTime(object);

            GldProject project = JSONObject.parseObject(object.toJSONString(), GldProject.class);
            list.add(project);
        }
        return list;
    }

    public List<GldTenant> getGetTenant() throws Exception {
        String token = getGetToken();
        if (StringUtil.isEmpty(token)) {
            throw new BizException("获取gld_token异常");
        }
        String url = masterHost + masterGetTenant;
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", "Bearer " + token);
        JSONObject resObject = HttpClientUtil.sendGETWithHeader_Obj(url, header);
        log.info("查询广联达主数据租户的res======>" + resObject.toJSONString());
        JSONArray array = resObject.getJSONArray("content");
        List<GldTenant> list = new ArrayList<>();
        for (Object obj : array) {
            JSONObject object = (JSONObject) obj;
            formatTime(object);

            GldTenant project = JSONObject.parseObject(object.toJSONString(), GldTenant.class);
            list.add(project);
        }
        return list;
    }


    private void formatTime(JSONObject object) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (object.containsKey("createTime")) {
            long createTimeSeconds = object.getLongValue("createTime");
            Date date = new Date(createTimeSeconds);
            String createTime = sdf.format(date);
            object.put("createTime", createTime);
        }
        if (object.containsKey("updateTime")) {
            long updateTimeSeconds = object.getLongValue("updateTime");
            Date date = new Date(updateTimeSeconds);
            String updateTime = sdf.format(date);
            object.put("updateTime", updateTime);
        }
    }
}
