package com.cmeeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cmeeting.ad.entity.SysUserSync;
import com.cmeeting.dto.CimcEmployee;
import com.cmeeting.dto.CimcOrganization;
import com.cmeeting.pojo.SysUserSyncCategory;
import com.cmeeting.service.ISysUserSyncCategoryService;
import com.cmeeting.service.SysUserSyncService;
import com.cmeeting.util.CimcUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CimcService {
    @Resource
    private ISysUserSyncCategoryService iSysUserSyncCategoryService;
    @Resource
    private SysUserSyncService SysUserSyncService;
    @Resource
    private CimcUtil cimcUtil;

    public void initCimcData(){
        iSysUserSyncCategoryService.remove(new LambdaQueryWrapper<>());
        SysUserSyncService.remove(new LambdaQueryWrapper<>());
    }

    @Transactional(rollbackFor = Exception.class)
    public void pullCimcData() {
        initCimcData();
        int i = 1;
        while (true) {
            List<CimcOrganization> deptList = cimcUtil.getDataByClass(i, CimcOrganization.class);
            if (deptList == null || deptList.size() == 0) {
                log.info("该页没有数据, i: {}", i);
                break;
            }
            log.info("获取到数据, size: {}", deptList.size());
            List<SysUserSyncCategory> data = new ArrayList<>();
            for (CimcOrganization organizations : deptList) {
                SysUserSyncCategory o = new SysUserSyncCategory();
                o.setName(organizations.getUnitName());
                o.setDeptId(organizations.getUnitId());
                o.setParentId(organizations.getParentId());
                data.add(o);
            }
            iSysUserSyncCategoryService.saveBatch(data);
            i++;
        }

        i = 1;
        while (true) {
            List<CimcEmployee> userList = cimcUtil.getDataByClass(i, CimcEmployee.class);
            if (userList == null || userList.size() == 0) {
                log.info("该页没有数据, i: {}", i);
                break;
            }
            log.info("获取到数据, size: {}", userList.size());
            List<SysUserSync> sysUserSyncs = new ArrayList<>();
            for (CimcEmployee employee : userList) {
                SysUserSync sysUserSync = SysUserSync.builder()
                        .userId(employee.getEmployeeCode()).name(employee.getEmployeeName()).deptId(employee.getUnitId())
                        .email(employee.getEmail()).department(employee.getUnitName()).build();
                sysUserSyncs.add(sysUserSync);
            }
            SysUserSyncService.saveBatch(sysUserSyncs);
            i++;
        }
    }
}
