package com.cool.store.http;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.CommonConstants;
import com.cool.store.dto.calendar.*;
import com.cool.store.dto.enterprise.AuthInfoDTO;
import com.cool.store.dto.enterprise.AuthScopeDTO;
import com.cool.store.dto.enterprise.EnterpriseUserDTO;
import com.cool.store.dto.enterprise.SysDepartmentDTO;
import com.cool.store.dto.login.UserIdInfoDTO;
import com.cool.store.dto.message.SendCardMessageDTO;
import com.cool.store.dto.response.ResultDTO;
import com.cool.store.entity.EnterpriseUserDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.exception.ApiException;
import com.cool.store.exception.ServiceException;
import com.cool.store.mq.util.HttpRestTemplateService;
import com.cool.store.request.EnterpriseUserRequest;
import com.cool.store.utils.RestTemplateUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @author zhangchenbiao
 * @FileName: ISVHttpRequest
 * @Description:
 * @date 2023-05-23 16:03
 */
@Service
@Slf4j
public class ISVHttpRequest {

    @Value("${isv.domain:null}")
    private String isvDomain;
    @Resource
    private HttpRestTemplateService httpRestTemplateService;

    public UserIdInfoDTO getUserIdByCode(String paramStr){
        String url = isvDomain + "/user/getUserIdByCode?" + paramStr;
        ResponseEntity<ResultDTO> responseEntity = null;
        try {
            responseEntity = RestTemplateUtil.loadGet(url, ResultDTO.class);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getBody()) && responseEntity.getBody().isSuccess()){
                return JSONObject.parseObject(JSONObject.toJSONString(responseEntity.getBody().getData()), UserIdInfoDTO.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ServiceException(e.getMessage());
        }
        return null;
    }

    public EnterpriseUserDTO getUserDetailByUserId(String userId){
        String url = isvDomain + "/user/getUserDetail";
        HashMap requestMap = new HashMap();
        requestMap.put("userId", userId);
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.getForObject(url, ResultDTO.class, requestMap);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return JSONObject.parseObject(JSONObject.toJSONString(responseEntity.getData()), EnterpriseUserDTO.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ServiceException(e.getMessage());
        }
        return null;
    }

    public List<String> getAdminUserList(){
        String url = isvDomain + "/corp/getAdminUserList";
        HashMap requestMap = new HashMap();
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.getForObject(url, ResultDTO.class, requestMap);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return JSONObject.parseArray(JSONObject.toJSONString(responseEntity.getData()), String.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ServiceException(e.getMessage());
        }
        return null;
    }

    public AuthInfoDTO getAuthInfo(){
        String url = isvDomain + "/corp/getAuthInfo";
        HashMap requestMap = new HashMap();
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.getForObject(url, ResultDTO.class, requestMap);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return JSONObject.parseObject(JSONObject.toJSONString(responseEntity.getData()), AuthInfoDTO.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ServiceException(e.getMessage());
        }
        return null;
    }

    public List<SysDepartmentDTO> getDepartments(String parentId){
        String url = isvDomain + "/corp/getDepartments";
        HashMap requestMap = new HashMap();
        requestMap.put("parentId", parentId);
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.getForObject(url, ResultDTO.class, requestMap);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return JSONObject.parseArray(JSONObject.toJSONString(responseEntity.getData()), SysDepartmentDTO.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ServiceException(e.getMessage());
        }
        return null;
    }

    /**
     * 获取部门详情
     * @param deptId
     * @return
     */
    public SysDepartmentDTO getDepartmentDetail(String deptId){
        String url = isvDomain + "/corp/getDepartmentDetail";
        HashMap requestMap = new HashMap();
        requestMap.put("deptId", deptId);
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.getForObject(url, ResultDTO.class, requestMap);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return JSONObject.parseObject(JSONObject.toJSONString(responseEntity.getData()), SysDepartmentDTO.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ServiceException(e.getMessage());
        }
        return null;
    }

    public AuthScopeDTO getAuthScope(){
        String url = isvDomain + "/corp/getAuthScope";
        HashMap requestMap = new HashMap();
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.getForObject(url, ResultDTO.class, requestMap);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return JSONObject.parseObject(JSONObject.toJSONString(responseEntity.getData()), AuthScopeDTO.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ServiceException(e.getMessage());
        }
        return null;
    }

    public List<EnterpriseUserDTO> getDepartmentUsers(String deptId){
        String url = isvDomain + "/corp/getDepartmentUsers";
        HashMap requestMap = new HashMap();
        requestMap.put("deptId", deptId);
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.getForObject(url, ResultDTO.class, requestMap);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return JSONObject.parseArray(JSONObject.toJSONString(responseEntity.getData()), EnterpriseUserDTO.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ServiceException(e.getMessage());
        }
        return null;
    }

    public List<EnterpriseUserDTO> getUserDetailByUserIds(List<String> userIdList) {
        String url = isvDomain + "/corp/getUserDetailByUserIds";
        HashMap requestMap = new HashMap();
        requestMap.put("userIds", String.join(CommonConstants.COMMA, userIdList));
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.getForObject(url, ResultDTO.class, requestMap);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return JSONObject.parseArray(JSONObject.toJSONString(responseEntity.getData()), EnterpriseUserDTO.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ServiceException(e.getMessage());
        }
        return null;
    }

    public List<SysDepartmentDTO> getSubDepartments(String parentId, Boolean fetchChild) {
        String url = isvDomain + "/corp/getSubDepartments";
        HashMap requestMap = new HashMap();
        requestMap.put("parentId", parentId);
        requestMap.put("fetchChild", fetchChild);
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.getForObject(url, ResultDTO.class, requestMap);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return JSONObject.parseArray(JSONObject.toJSONString(responseEntity.getData()), SysDepartmentDTO.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ServiceException(e.getMessage());
        }
        return null;
    }

    /**
     * 获取用户忙闲信息
     * @param userId
     * @param startTime 开始时间 毫秒时间戳
     * @param endTime 截止时间 毫秒时间戳
     * @return
     */
    public List<UserFreeBusyInfoDTO> getFreeBusyList(String userId, long startTime, long endTime) throws ApiException{
        String url = isvDomain + "/user/getFreeBusyList";
        HashMap requestMap = new HashMap();
        requestMap.put("userId", userId);
        requestMap.put("startTime", startTime);
        requestMap.put("endTime", endTime);
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.getForObject(url, ResultDTO.class, requestMap);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return JSONObject.parseArray(JSONObject.toJSONString(responseEntity.getData()), UserFreeBusyInfoDTO.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ApiException(e.getMessage());
        }
        return null;
    }

    /**
     * 创建飞书日程
     * @param param
     * @return
     * @throws ApiException
     */
    public UserCalendarsEventDTO createUserCalendarEvent(CreateCalendarEventDTO param) throws ApiException{
        String url = isvDomain + "/user/createUserCalendarEvent";
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.postForObject(url, param, ResultDTO.class);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return JSONObject.parseObject(JSONObject.toJSONString(responseEntity.getData()), UserCalendarsEventDTO.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ApiException(e.getMessage());
        }
        return null;
    }

    /**
     * 更新飞书日程
     * @param param
     * @return
     * @throws ApiException
     */
    public UserCalendarsEventDTO updateUserCalendarEvent(UpdateCalendarEventDTO param) throws ApiException{
        String url = isvDomain + "/user/updateUserCalendarEvent";
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.postForObject(url, param, ResultDTO.class);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return JSONObject.parseObject(JSONObject.toJSONString(responseEntity.getData()), UserCalendarsEventDTO.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ApiException(e.getMessage());
        }
        return null;
    }

    /**
     * 取消飞书日程
     * @param param
     * @return
     * @throws ApiException
     */
    public UserCalendarsEventDTO deleteUserCalendarEvent(DeleteCalendarEventDTO param) throws ApiException {
        String url = isvDomain + "/user/deleteUserCalendarEvent";
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.postForObject(url, param, ResultDTO.class);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return JSONObject.parseObject(JSONObject.toJSONString(responseEntity.getData()), UserCalendarsEventDTO.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ApiException(e.getMessage());
        }
        return null;
    }

    /**
     * 获取飞书日程
     * @param userId
     * @param startTime
     * @param endTime
     * @return
     * @throws ApiException
     */
    public List<UserCalendarsEventDTO> getUserCalendarsEvents(String userId, long startTime, long endTime)throws ApiException{
        String url = isvDomain + "/user/getUserCalendarsEvents";
        HashMap requestMap = new HashMap();
        requestMap.put("userId", userId);
        requestMap.put("startTime", startTime);
        requestMap.put("endTime", endTime);
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.getForObject(url, ResultDTO.class, requestMap);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return JSONObject.parseArray(JSONObject.toJSONString(responseEntity.getData()), UserCalendarsEventDTO.class);
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ApiException(e.getMessage());
        }
        return null;
    }

    /**
     * 发送飞书卡片消息
     * @param param
     */
    @Async
    public void sendFeiShuCardMessage(SendCardMessageDTO param) throws ApiException{
        if(CollectionUtils.isEmpty(param.getUserIds()) || StringUtils.isAnyBlank(param.getTitle(), param.getContent(), param.getMessageUrl()) || Objects.isNull(param.getMessageType())){
            return;
        }
        String url = isvDomain + "/sendFeiShuCardMessage";
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.postForObject(url, param, ResultDTO.class);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ApiException(e.getMessage());
        }
    }

    public String getWechatAccessToken(String appId, String appSecret)throws ApiException{
        String url = "https://isv-partner.hsay.com/isv/wechat/getWechatAccessToken";
        //String url = "https://abstore-isv.coolstore.cn/isv/wechat/getWechatAccessToken";
        HashMap requestMap = new HashMap();
        requestMap.put("appId", appId);
        requestMap.put("appSecret", appSecret);
        ResultDTO responseEntity = null;
        try {
            responseEntity = httpRestTemplateService.getForObject(url, ResultDTO.class, requestMap);
            log.info("url:{}, response:{}", url, JSONObject.toJSONString(responseEntity));
            if(Objects.nonNull(responseEntity.getData()) && responseEntity.isSuccess()){
                return (String) responseEntity.getData();
            }
        } catch (Exception e) {
            log.info("调用isv出错{}", e);
            throw new ApiException(e.getMessage());
        }
        return null;
    }
}
