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.core.conditions.query.LambdaQueryWrapper;
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.common.system.service.UserRoleService;
import com.gxwebsoft.oa.entity.TaskCount;
import com.gxwebsoft.oa.mapper.TaskCountMapper;
import com.gxwebsoft.oa.param.TaskCountParam;
import com.gxwebsoft.oa.service.TaskCountService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据统计Service实现
 *
 * @author 科技小王子
 * @since 2023-10-30 14:25:30
 */
@Service
public class TaskCountServiceImpl extends ServiceImpl<TaskCountMapper, TaskCount> implements TaskCountService {
    @Resource
    private UserRoleService userRoleService;

    @Override
    public PageResult<TaskCount> pageRel(TaskCountParam param) {

        PageParam<TaskCount, TaskCountParam> page = new PageParam<>(param);
        page.setDefaultOrder("month desc");
        List<TaskCount> list = baseMapper.selectPageRel(page, param);
        final PageResult<TaskCount> result = new PageResult<>(list, page.getTotal());
        // 请求主服务器获取用户信息
        final List<TaskCount> taskCountList = result.getList();
        System.out.println("taskCountList = " + taskCountList);
        final Set<Integer> userIds = taskCountList.stream().map(TaskCount::getUserId).collect(Collectors.toSet());
        HashMap<String, Object> map = new HashMap<>();
//        map.put("roleCode","commander");
        map.put("userIds", userIds);
        if (!userIds.isEmpty()) {
            // 链式构建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();

            final ApiResult<PageResult<User>> userResult = JSONObject.parseObject(response, new TypeReference<ApiResult<PageResult<User>>>() {
            });
            final Map<Integer, List<User>> collect = userResult.getData().getList().stream().collect(Collectors.groupingBy(User::getUserId));

            if (!CollectionUtils.isEmpty(collect)) {
                taskCountList.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());
                    }
                });
            }
            result.setList(taskCountList);
        }
        return result;
    }

    // 远程同步用户数据
    private void updateServerUser(TaskCountParam param){
      // 请求主服务器获取用户信息
      HashMap<String, Object> map = new HashMap<>();
      map.put("isStaff", "1");
      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();

      final ApiResult<PageResult<User>> userResult = JSONObject.parseObject(response, new TypeReference<ApiResult<PageResult<User>>>() {
      });
      final Map<Integer, List<User>> collect = userResult.getData().getList().stream().collect(Collectors.groupingBy(User::getUserId));

      final List<User> userList = userResult.getData().getList();
      TaskCount taskCount = new TaskCount();
      userList.forEach(user -> {
        if (count(new LambdaQueryWrapper<TaskCount>().eq(TaskCount::getUserId, user.getUserId())) == 0) {
          taskCount.setUserId(user.getUserId());
          taskCount.setOrganizationId(user.getOrganizationId());
          taskCount.setTenantId(user.getTenantId());
          user.getRoles().forEach(role -> {
            if(role.getRoleCode().equals("staff") || role.getRoleCode().equals("commander")){
              taskCount.setRoleCode("commander");
              taskCount.setRoleId(role.getRoleId());
            }
            if(role.getRoleCode().equals("admin")){
              taskCount.setRoleId(role.getRoleId());
              taskCount.setRoleCode(role.getRoleCode());
            }
          });
          save(taskCount);
        }
      });
    }

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

    @Override
    public TaskCount getByIdRel(Integer taskCountId) {
        TaskCountParam param = new TaskCountParam();
        param.setTaskCountId(taskCountId);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public TaskCount getByUserId(Integer userId) {
      TaskCountParam param = new TaskCountParam();
      param.setUserId(userId);
      return param.getOne(baseMapper.selectListRel(param));
    }

}
