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

import com.docus.core.util.Func;
import com.docus.infrastructure.core.exception.BaseException;
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.entity.PowerUser;
import com.docus.server.archive.mapper.PowerUserMapper;
import com.docus.server.archive.service.FoShanThreeHospUserInfoSyncService;
import com.docus.server.archive.utils.XmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

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("fssy" + SyncConstant.USER_INFO_SYNC_SERVICE_SUFFIX)
@Slf4j
public class FoShanThreeHospUserInfoSyncServiceImpl implements FoShanThreeHospUserInfoSyncService {
    @Resource
    private PowerUserMapper powerUserMapper;
    @Resource
    private IdService idService;
    @Resource
    private DocusProperties docusProperties;

    @Override
    public void syncByUnifyMessageReceive(String message) {
        List<PowerUser> powerUserList = parsePowerUser(message);
        if (Func.isNotEmpty(powerUserList)) {
            saveOrUpdate(powerUserList);
        }

    }

    private List<PowerUser> parsePowerUser(String message) {
        List<PowerUser> powerUserList = new ArrayList<>();
        XmlUtil xmlUtil = XmlUtil.of(message);
        NodeList employeeNodeList = xmlUtil.getNodeList("/Request/Body/ResultContent/Employee");
        if (employeeNodeList != null && employeeNodeList.getLength() > 0) {
            int nodeListLength = employeeNodeList.getLength();
            for (int i = 0; i < nodeListLength; i++) {
                String userName = "";
                String name = "";
                String deptId = "";
                Integer effective = 1;
                Integer enabled = 1;
                Long roleId=0L;

                Node employeeNode = employeeNodeList.item(i);
                NodeList childNodes = employeeNode.getChildNodes();
                int childNodesLength = childNodes.getLength();
                for (int j = 0; j < childNodesLength; j++) {
                    Node node = childNodes.item(j);
                    String nodeName = node.getNodeName();
                    if ("BANK_ACCOUNT".equals(nodeName)) {
                        userName = node.getTextContent();
                        continue;
                    }
                    if ("EMPL_NAME".equals(nodeName)) {
                        name = node.getTextContent();
                        continue;
                    }
//                    if ("DEPT_CODE".equals(nodeName)) {
//                        deptId = node.getTextContent();
//                    }
                    if ("CUSTOM_CODE".equals(nodeName)) {
                        deptId = node.getTextContent();
                    }
                }
                if(Func.isBlank(userName)){
                    throw new BaseException("用户工号不能为空！");
                }
                if(Func.isBlank(name)){
                    throw new BaseException("用户姓名不能为空！");
                }
                PowerUser powerUser = new PowerUser();
                powerUser.setUserName(userName);
                powerUser.setName(name);
                powerUser.setDeptId(deptId);
                powerUser.setEffective(effective);
                powerUser.setEnabled(enabled);
                powerUser.setPowerDept(deptId);
                powerUser.setRoleId(roleId);
                powerUserList.add(powerUser);
            }
        }
        return powerUserList;
    }

    /**
     * 根据修改的用户信息，根据工号判断是否存在，如果存在则更新名字，科室 状态等信息，如果不存在则插入用户信息
     *
     * @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);
        }
    }
}
