package com.gxwebsoft.oa.service.impl;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.net.url.UrlQuery;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.oa.entity.CompanyUser;
import com.gxwebsoft.oa.mapper.CompanyUserMapper;
import com.gxwebsoft.oa.param.CompanyUserParam;
import com.gxwebsoft.oa.service.CompanyUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 成员管理Service实现
 *
 * @author 科技小王子
 * @since 2024-02-04 14:44:42
 */
@Service
public class CompanyUserServiceImpl extends ServiceImpl<CompanyUserMapper, CompanyUser> implements CompanyUserService {

    @Override
    public PageResult<CompanyUser> pageRel(CompanyUserParam param) {
        PageParam<CompanyUser, CompanyUserParam> page = new PageParam<>(param);
        //page.setDefaultOrder("create_time desc");
        List<CompanyUser> list = baseMapper.selectPageRel(page, param);
      PageResult<CompanyUser> result = new PageResult<>(list, page.getTotal());
      final List<CompanyUser> companyUserList = result.getList();
      final Set<Integer> userIds = companyUserList.stream().map(CompanyUser::getUserId).collect(Collectors.toSet());
      // 请求主服务器获取用户信息
      HashMap<String, Object> map = new HashMap<>();
      map.put("userIds", userIds);
      System.out.println("map = " + map);
      // 链式构建GET请求
      final String build = UrlBuilder.of("https://server.gxwebsoft.com/api/system/user/page").setQuery(new UrlQuery(map)).build();
      String response = HttpRequest.get(build)
        .header("Authorization", param.getToken())
        .header("Tenantid", param.getTenantId().toString())
        .body(JSONObject.toJSONString(map))//表单内容
        .timeout(20000)//超时，毫秒
        .execute().body();

      System.out.println("response = " + response);

      final ApiResult<PageResult<User>> userResult = JSONObject.parseObject(response, new TypeReference<ApiResult<PageResult<User>>>() {
      });
      final PageResult<User> data = userResult.getData();
      final List<User> userList = data.getList();
      if (!CollectionUtils.isEmpty(userList)) {
        final Map<Integer, List<User>> collect = userList.stream().collect(Collectors.groupingBy(User::getUserId));
        companyUserList.forEach(item -> {
          final List<User> users = collect.get(item.getUserId());
          if (!CollectionUtils.isEmpty(users)) {
            final User user = users.get(0);
            item.setNickname(user.getNickname());
            item.setAvatar(user.getAvatar());
            item.setPhone(user.getPhone());
            item.setEmail(user.getEmail());
          }
        });
        result.setList(companyUserList);
      }

      return result;
    }

    @Override
    public List<CompanyUser> listRel(CompanyUserParam param) {
        List<CompanyUser> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<CompanyUser, CompanyUserParam> page = new PageParam<>();
        //page.setDefaultOrder("create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public CompanyUser getByIdRel(Integer companyUserId) {
        CompanyUserParam param = new CompanyUserParam();
        param.setCompanyUserId(companyUserId);
        return param.getOne(baseMapper.selectListRel(param));
    }

}
