package com.docus.server.archive.service.impl;

import com.docus.core.util.Func;
import com.docus.infrastructure.redis.service.IdService;
import com.docus.server.archive.config.DocusProperties;
import com.docus.server.archive.constans.SyncConstant;
import com.docus.server.archive.converter.ZqDyRyUserInfoConverter;
import com.docus.server.archive.entity.PowerUser;
import com.docus.server.archive.mapper.PowerUserMapper;
import com.docus.server.archive.service.UserInfoSyncService;
import com.docus.server.zqdyry.entity.ZqDyRyDeptInfoView;
import com.docus.server.zqdyry.entity.ZqDyRyUserInfoView;
import com.docus.server.zqdyry.mapper.ZqDyRyDeptInfoViewMapper;
import com.docus.server.zqdyry.mapper.ZqDyRyUserInfoViewMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * @author YongBin Wen
 * @date 2024/3/27 16:25
 */
@Service("ZqDyRy" + SyncConstant.USER_INFO_SYNC_SERVICE_SUFFIX)
@Slf4j
public class ZqDyRyUserInfoSyncServiceImpl implements UserInfoSyncService {
    @Resource
    private PowerUserMapper powerUserMapper;
    @Resource
    private ZqDyRyUserInfoViewMapper userInfoViewMapper;
    @Resource
    private ZqDyRyDeptInfoViewMapper deptInfoViewMapper;
    @Resource
    private IdService idService;
    @Resource
    private DocusProperties docusProperties;

    @Override
    public void fullSync() {
        int size = 2000;
        int pageNumber = 1;
        List<ZqDyRyDeptInfoView> deptInfoViews = deptInfoViewMapper.list();
        Map<String, String> deptNameIdMap = new HashMap<>();
        for (ZqDyRyDeptInfoView deptInfoView : deptInfoViews) {
            // 包含了这个部门，并且这个部门状态为不为启用，不会选择此部门
            if (deptNameIdMap.containsKey(deptInfoView.getFDEPTNAME()) && !"1".equals(deptInfoView.getSTATUS())) {
                continue;
            }
            deptNameIdMap.put(deptInfoView.getFDEPTNAME(), deptInfoView.getID());
        }
        while (true) {
            int startRow = ((pageNumber - 1) * size) + 1;
            int endRow = pageNumber * size;
            List<ZqDyRyUserInfoView> userInfoViews = userInfoViewMapper.page(startRow, endRow);
            if (Func.isNotEmpty(userInfoViews)) {
                // 目前视图是名称，将名称转换为科室id
                for (ZqDyRyUserInfoView userInfoView : userInfoViews) {
                    String deptId = deptNameIdMap.get(userInfoView.getFIPDEPTID());
                    userInfoView.setFIPDEPTID(deptId);
                }
                // 转换保存
                List<PowerUser> powerUsers = userInfoViews.stream()
                        .map(ZqDyRyUserInfoConverter::convertUserInfo)
                        .collect(Collectors.toList());
                saveOrUpdate(powerUsers);
            }
            if (Func.isEmpty(userInfoViews) || userInfoViews.size() < size) {
                break;
            }
            pageNumber++;
        }
    }

    /**
     * 根据修改的用户信息，根据工号判断是否存在，如果存在则更新名字，科室 状态等信息，如果不存在则插入用户信息
     *
     * @param iuPowerUserList 修改的用户信息
     */
    private void saveOrUpdate(List<PowerUser> iuPowerUserList) {
        Date nowDate = new Date();
        List<String> iuUserNames = iuPowerUserList.stream()
                .map(PowerUser::getUserName)
                .collect(Collectors.toList());

        List<PowerUser> existsPowerUserList = powerUserMapper.findByUserNames(iuUserNames);
        Map<String, PowerUser> existsPowerUserMap = existsPowerUserList.stream().collect(Collectors.toMap(PowerUser::getUserName, Function.identity()));
        final String delimiter = ",";

        List<PowerUser> insertUserList = new ArrayList<>();
        List<PowerUser> updateUserList = new ArrayList<>();
        for (PowerUser iuPowerUser : iuPowerUserList) {
            if (existsPowerUserMap.containsKey(iuPowerUser.getUserName())) {
                PowerUser powerUser = existsPowerUserMap.get(iuPowerUser.getUserName());
                // 如果修改的管辖科室不为空，获取原来的，加上现在的，得到最新的，下面管辖医生同理
                String powerDept = powerUser.getPowerDept();
                if (Func.isNotBlank(iuPowerUser.getPowerDept())) {
                    HashSet<String> powerDepts = new HashSet<>();
                    if (Func.isNotBlank(powerDept)) {
                        Collections.addAll(powerDepts, powerDept.split(delimiter));
                    }
                    powerDepts.add(iuPowerUser.getPowerDept());
                    powerDept = String.join(delimiter, powerDepts);
                }
                String powerAttending = powerUser.getPowerAttending();
                if (Func.isNotBlank(iuPowerUser.getPowerAttending())) {
                    HashSet<String> powerAttendings = new HashSet<>();
                    if (Func.isNotBlank(powerAttending)) {
                        Collections.addAll(powerAttendings, powerAttending.split(delimiter));
                    }
                    powerAttendings.add(iuPowerUser.getPowerAttending());
                    powerAttending = String.join(delimiter, powerAttendings);
                }
                powerUser.setName(iuPowerUser.getName());
                powerUser.setEnabled(iuPowerUser.getEnabled());
                powerUser.setEffective(iuPowerUser.getEffective());
//                powerUser.setDeptId(iuPowerUser.getDeptId());
                powerUser.setPowerDept(powerDept);
                powerUser.setPowerAttending(powerAttending);
                powerUser.setUpdateDate(nowDate);
                powerUser.setUpdater("java-sync");
                updateUserList.add(powerUser);
                continue;
            }
            iuPowerUser.setUserId(idService.getDateSeq());
            iuPowerUser.setUpdater("java-sync");
            iuPowerUser.setUpdateDate(nowDate);
            iuPowerUser.setCreater("java-sync");
            iuPowerUser.setCreateDate(nowDate);
            iuPowerUser.setAccountState(0);
            iuPowerUser.setIsThird(0);
            iuPowerUser.setLoginFlag(0);
            iuPowerUser.setPwdChange(0);
            iuPowerUser.setUserPwd(docusProperties.getDefaultUserPwd());
            insertUserList.add(iuPowerUser);
        }

        if (Func.isNotEmpty(insertUserList)) {
            powerUserMapper.insertBatch(insertUserList);
        }

        if (Func.isNotEmpty(updateUserList)) {
            powerUserMapper.updateBatch(updateUserList);
        }
    }
}
