package com.jeelowcode.service.system.controller;

import com.jeelowcode.service.system.controller.vo.user.sync.MasterRespResult;
import com.jeelowcode.service.system.controller.vo.user.sync.MasterSystemReqVO;
import com.jeelowcode.service.system.controller.vo.user.sync.MasterUserResultVO;
import com.jeelowcode.service.system.service.IUserSyncService;
import com.jeelowcode.tool.framework.tenant.core.util.TenantUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;

/**
 * 从主数据用户同步接口
 *
 * @author yangchenjj
 */
@Validated
@RestController
@Tag(name = "从主数据用户同步接口")
@RequestMapping("/system/user-sync")
public class UserSyncController {

    /**
     * 用户同步服务
     */
    @Resource
    private IUserSyncService userSyncService;

    /**
     * 从主数据同步用户
     *
     * @param reqVO 请求参数
     * @return 响应结果
     */
    @PostMapping
    @Operation(tags = "从主数据用户同步接口", summary = "同步用户")
    public MasterRespResult syncUser(@Validated MasterSystemReqVO reqVO) {
        try {
            // 调用服务,返回数据消费成功结果
            Callable<MasterRespResult> callable = () -> userSyncService.syncUser(reqVO);
            // 在租户环境下执行
            return TenantUtils.execute(1L, callable);
        } catch (Exception e) {
            List<MasterUserResultVO> mdMappings = reqVO.getMasterData()
                    .stream().map(md -> MasterUserResultVO.buildFail(md.getMdmCode(), reqVO.getMdType(), null))
                    .collect(Collectors.toList());
            // 调用服务失败,返回数据消费失败结果
            return MasterRespResult.buildFail(e.getMessage(), mdMappings);
        }
    }

}
