package com.ruoyi.adsdesk.business.user;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.adsdesk.domain.AdsUser;
import com.ruoyi.adsdesk.param.UserListParam;
import com.ruoyi.adsdesk.vo.AdsUserVo;
import com.ruoyi.adsdesk.vo.ExpandFieldsVo;
import com.ruoyi.adsdesk.vo.UserResponseDto;
import com.ruoyi.common.constant.StrConstants;
import org.apache.commons.compress.utils.Lists;
import org.apache.logging.log4j.util.Strings;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import javax.annotation.Resource;
import java.net.URI;
import java.util.List;


/**
 * Ads登录用户
 *
 * @author Xingbz
 */
@Service
public class AdsUserBusiness {

    public IPage<AdsUserVo> list(UserListParam param) {
        UserResponseDto responseDto = getUserPageList(param.getPageSize(),param.getPageNum(),param);

        if(null == responseDto){
            return new Page<>(param.getPageNum(), param.getPageSize());
        }

        List<AdsUserVo> list = responseDto.getRecords();
        Integer total = responseDto.getTotal();
        Page result = new Page<>(param.getPageNum(), param.getPageSize(), total);
        result.setRecords(list);
        return result;
    }


    private UserResponseDto getUserPageList(int size,int page,UserListParam userListParam){

        RestTemplate restTemplate = new RestTemplate();

        JSONObject param = new JSONObject();
        param.put("secret","20230000");
        param.put("current",page);
        param.put("size",size);
        param.put("userId",userListParam.getUserId());
        param.put("userName",userListParam.getUserName());
        param.put("userNick",userListParam.getUserNick());


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<?> requestEntity = new HttpEntity<>(param, headers);

        String url = "http://test-api2.adsdesk.cn/adsdesk/api/open_api/system/user/list";
        String responseStr = restTemplate.exchange(URI.create(url), HttpMethod.POST, requestEntity, String.class).getBody();
        responseStr = clearResponseStr(responseStr);

        if(Strings.isEmpty(responseStr)){
            return null;
        }

        UserResponseDto dto = new UserResponseDto();

        JSONObject jsonObject = JSON.parseObject(responseStr);
        int code = (int) jsonObject.get("code");

        JSONObject data = (JSONObject) jsonObject.get("data");

        List<AdsUserVo> records = (List<AdsUserVo>) data.get("records");
        List<ExpandFieldsVo> expandFields = (List<ExpandFieldsVo>) data.get("expandFields");
        Integer current = (Integer) data.get("current");
        Integer pages = (Integer) data.get("pages");
        Integer pageSize = (Integer) data.get("size");
        Integer total = (Integer) data.get("total");

        dto.setRecords(records);
        dto.setExpandFields(expandFields);
        dto.setCurrent(current);
        dto.setTotal(total);

        return dto;
    }

    private String clearResponseStr(String responseStr) {
        if (ObjectUtil.isNull(responseStr)) {
            return null;
        }

        // 双引号包括的字符串
        if (StrUtil.startWith(responseStr, StrConstants.DOUBLE_QUOTES) && StrUtil.endWith(responseStr, StrConstants.DOUBLE_QUOTES)) {
            int placeholderCount = StrUtil.count(responseStr, "\\\"");
            //  类似于"{\"en\":\"zhangsan\",\"cn\":\"张三\"}"转义之后的json字符串
            if (placeholderCount > 0 && placeholderCount % 2 == 0) {
                return StrUtil.replace(StrUtil.removeSuffix(StrUtil.removePrefix(responseStr, StrConstants.DOUBLE_QUOTES), StrConstants.DOUBLE_QUOTES), "\\\"", StrConstants.DOUBLE_QUOTES);
            }
        }

        return responseStr;
    }

}