package com.yd.csf.api.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yd.common.result.Result;
import com.yd.csf.api.service.ApiApprovalService;
import com.yd.csf.feign.request.approval.ApiApprovalClientUserPageRequest;
import com.yd.csf.feign.response.approval.ApiApprovalClientUserPageResponse;
import com.yd.csf.service.dto.AgentReferralRelationDto;
import com.yd.csf.service.model.AgentReferralRelation;
import com.yd.csf.service.service.IAgentReferralRelationService;
import com.yd.user.feign.client.clientuser.ApiClientUserFeignClient;
import com.yd.user.feign.request.clientuser.ApiClientUserPageRequest;
import com.yd.user.feign.response.clientuser.ApiClientUserPageResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ApiApprovalServiceImpl implements ApiApprovalService {

    @Autowired
    private ApiClientUserFeignClient apiClientUserFeignClient;

    @Autowired
    private IAgentReferralRelationService iAgentReferralRelationService;

    /**
     * 审批列表-客户端用户信息
     * @param request
     * @return
     */
    @Override
    public Result<IPage<ApiApprovalClientUserPageResponse>> approvalClientUserPage(ApiApprovalClientUserPageRequest request) {
        IPage<ApiApprovalClientUserPageResponse> iPage = new Page<ApiApprovalClientUserPageResponse>();
        ApiClientUserPageRequest pageRequest = new ApiClientUserPageRequest();
        BeanUtils.copyProperties(request,pageRequest);
        //远程调用user服务查询客户端分页列表信息
        Result<IPage<ApiClientUserPageResponse>> iPageResult = apiClientUserFeignClient.page(pageRequest);
        if (!Objects.isNull(iPageResult.getData())
                && !CollectionUtils.isEmpty(iPageResult.getData().getRecords())) {
            IPage<ApiClientUserPageResponse> clientUserPageResponseIPage = iPageResult.getData();
            List<ApiClientUserPageResponse> responses = clientUserPageResponseIPage.getRecords();
            List<ApiApprovalClientUserPageResponse> pageResponses = responses
                    .stream()
                    .map(dto -> {
                        ApiApprovalClientUserPageResponse response = new ApiApprovalClientUserPageResponse();
                        BeanUtils.copyProperties(dto,response);
                        return response;
                    }).collect(Collectors.toList());

            //clientUserBizIdList -> 被推荐的客户端用户ID列表
            List<String> clientUserBizIdList = responses.stream()
                    .map(ApiClientUserPageResponse::getClientUserBizId)
                    .collect(Collectors.toList());
            //查询推荐关系列表数据
            List<AgentReferralRelation> relations = iAgentReferralRelationService.queryList(AgentReferralRelationDto.builder()
                    .agentIdList(clientUserBizIdList)
                    .tenantBizId(request.getTenantBizId())
                    .projectBizId(request.getProjectBizId())
                    .build());
            if (!CollectionUtils.isEmpty(relations)) {
                pageResponses.stream().map(dto -> {
                    AgentReferralRelation relation = relations.stream()
                            .filter(rel -> rel.getAgentId().equals(dto.getClientUserBizId()))
                            .findFirst().get();
                    if (!Objects.isNull(relation)) {
                        //推荐人账号（客户端用户表手机号，如果是PC，这里就是sys_user的用户名）
                        dto.setReferrerAccount(relation.getReferrerAccount());
                        //推荐人ID（客户端用户表唯一业务ID，如果是PC，这里就是sys_user的用户ID）
                        dto.setReferrerId(relation.getReferrerId());
                        //注册来源（PC、小程序等）默认小程序 - MINI_PROGRAM
                        dto.setRegisterSource(relation.getSource());
                    }
                    return dto;
                }).collect(Collectors.toList());
            }

            iPage.setRecords(pageResponses);
            iPage.setCurrent(clientUserPageResponseIPage.getCurrent());
            iPage.setPages(clientUserPageResponseIPage.getPages());
            iPage.setSize(clientUserPageResponseIPage.getSize());
            iPage.setTotal(clientUserPageResponseIPage.getTotal());
        }
        return Result.success(iPage);
    }

}
