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.MzsyUserInfoConverter;
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.mzsy.entity.MzsyDeptInfoView;
import com.docus.server.mzsy.entity.MzsyHisUserInfo;
import com.docus.server.mzsy.entity.MzsyUserInfoView;
import com.docus.server.mzsy.mapper.MzsyDeptInfoViewMapper;
import com.docus.server.mzsy.mapper.MzsyHisUserInfoMapper;
import com.docus.server.mzsy.mapper.MzsyUserInfoViewMapper;
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("Mzsy" + SyncConstant.USER_INFO_SYNC_SERVICE_SUFFIX)
@Slf4j
public class MzsyUserInfoSyncServiceImpl implements UserInfoSyncService {
    @Resource
    private PowerUserMapper powerUserMapper;
    @Resource
    private MzsyUserInfoViewMapper userInfoViewMapper;
    @Resource
    private MzsyHisUserInfoMapper hisUserInfoMapper;
    @Resource
    private MzsyDeptInfoViewMapper deptInfoViewMapper;
    @Resource
    private IdService idService;
    @Resource
    private DocusProperties docusProperties;

    @Override
    public void fullSync() {
        int size = 2000;
        int pageNumber = 1;
        List<MzsyDeptInfoView> deptInfoViews = deptInfoViewMapper.list();
        Map<String, String> deptNameIdMap = new HashMap<>();

        while (true) {
            int startRow = ((pageNumber - 1) * size) + 1;
            int endRow = pageNumber * size;
            List<MzsyUserInfoView> userInfoViews = userInfoViewMapper.page(startRow, endRow);
            if (Func.isNotEmpty(userInfoViews)) {
                // 转换保存
                List<PowerUser> powerUsers = userInfoViews.stream()
                        .map(MzsyUserInfoConverter::convertUserInfo)
                        .collect(Collectors.toList());
                // 360his查询用户电话信息并设置
                List<String> userNames = powerUsers.stream().map(PowerUser::getUserName).collect(Collectors.toList());
                List<MzsyHisUserInfo> hisUserInfoList = hisUserInfoMapper.findByYgDms(userNames);
                Map<String, String> userTelMap =new HashMap<>();
                for (MzsyHisUserInfo hisUserInfo : hisUserInfoList) {
                    userTelMap.put(hisUserInfo.getYGDM(),hisUserInfo.getYGDH());
                }
                for (PowerUser powerUser : powerUsers) {
                    powerUser.setUserTel(userTelMap.get(powerUser.getUserName()));
                }
                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()) && Func.isNotBlank(powerDept)) {
                    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()) && Func.isNotBlank(powerAttending)) {
                    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.setUserTel(iuPowerUser.getUserTel());
                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);
        }
    }
}
