package com.ensign.crm.module.crm.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ensign.crm.framework.common.enums.CommonStatusEnum;
import com.ensign.crm.framework.common.enums.CrmUserTypeEnum;
import com.ensign.crm.framework.quartz.core.handler.JobHandler;
import com.ensign.crm.framework.tenant.core.aop.TenantIgnore;
import com.ensign.crm.module.crm.job.service.TaskHandler;
import com.ensign.crm.module.system.dal.dataobject.user.AdminUserDO;
import com.ensign.crm.module.system.dal.mysql.user.AdminUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Date: 2024/9/26 14:06
 * @Created: by ZZSLL
 */

@Slf4j
@Component
public class UserSyncKingdeeTask implements JobHandler {


    @Autowired
    private AdminUserMapper userMapper;

    @Autowired
    private TaskHandler taskHandler;

    @Override
    @TenantIgnore
    public String execute(String param) throws Exception {
        LambdaQueryWrapper<AdminUserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminUserDO::getStatus, CommonStatusEnum.ENABLE.getStatus())
                .eq(AdminUserDO::getIsSyncKingdee, CommonStatusEnum.DISABLE.getStatus())
                .eq(AdminUserDO::getCrmUserType, CrmUserTypeEnum.DEALER.getValue());
        List<AdminUserDO> users = userMapper.selectList(queryWrapper);

        List<AdminUserDO> errors = new ArrayList<>();
        for (AdminUserDO user : users) {
            taskHandler.syncUser(user, errors);
        }

        List<Long> errorIds = errors.stream()
                .map(AdminUserDO::getId)
                .collect(Collectors.toList());

        List<AdminUserDO> success = users.stream()
                .filter(user -> !errorIds.contains(user.getId()))
                .collect(Collectors.toList());


        if (!errors.isEmpty()) {
            return errors.stream()
                    .map(user -> user.getUsername() + "_" + user.getNickname())
                    .collect(Collectors.joining(", "));
        }
        return success.stream()
                .map(user -> user.getUsername() + "_" + user.getNickname())
                .collect(Collectors.joining(", "));
    }
}
