package com.docus.server.collection.webservice.impl;

import com.docus.core.util.DateUtil;
import com.docus.core.util.Func;
import com.docus.infrastructure.core.exception.BaseException;
import com.docus.server.collection.dto.UserDto;
import com.docus.server.collection.service.IPowerUserService;
import com.docus.server.collection.util.IdUtil;
import com.docus.server.collection.util.XmlUtil;
import com.docus.server.collection.webservice.IUserServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.w3c.dom.Node;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author wen yongbin
 * @date 2023年2月25日21:56:33
 */
@Service
@Slf4j
public class UserServerImpl implements IUserServer {

    @Resource
    IPowerUserService iPowerUserService;

    @Override
    public String userModify(String receiveUser) {
        log.info("新增/修改用户数据：{}", receiveUser);
        UserDto userDto;
        String msgId = "";
        String receiver = "";
        try {
            userDto = strToUserDto(receiveUser);
            msgId = userDto.getMessageId();
            receiver = userDto.getReceiver();
            String operateType = userDto.getOperateType();
            String delType = "D";
            // 判断操作类型 是否是删除，或者 删除标记的
            boolean isDel = (Func.isNotEmpty(operateType) && operateType.contains(delType)) || userDto.isDelFlag();
            if (isDel) {
                iPowerUserService.delUserByUserName(userDto.getUserName());
            } else {
                iPowerUserService.register(userDto);
            }
            return successMessage("操作成功！", msgId, receiver);
        } catch (BaseException e) {
            log.error(e.getMessage(), e);
            return failedMessage(e.getMessage(), msgId, receiver);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return failedMessage("系统出错啦！", msgId, receiver);
        }
    }


    /**
     * 接收用户参数解析 UserDto参数
     *
     * @param receiveUser 接收到的用户参数
     * @return UserDto
     */
    public UserDto strToUserDto(String receiveUser) {
        final String notDelFlag = "1";
        XmlUtil xmlParseUtil = XmlUtil.of(receiveUser);
        Node msgIdNode = xmlParseUtil.getNode("/PRVS_IN000002UV01/id/@extension");
        Node receiverNode = xmlParseUtil.getNode("/PRVS_IN000002UV01/receiver/device/id/item/@extension");
        Node operateTypeNode = xmlParseUtil.getNode("/PRVS_IN000002UV01/controlActProcess/subject/registrationRequest/subject1/valueSet/valueSetItems/@operateType");
        Node employeeCodeNode = xmlParseUtil.getNode("/PRVS_IN000002UV01/controlActProcess/subject/registrationRequest/subject1/valueSet/valueSetItems/EMPL_CODE/@value");
        Node employeeNameNode = xmlParseUtil.getNode("/PRVS_IN000002UV01/controlActProcess/subject/registrationRequest/subject1/valueSet/valueSetItems/EMPL_NAME/@value");
        Node deptCodeNode = xmlParseUtil.getNode("/PRVS_IN000002UV01/controlActProcess/subject/registrationRequest/subject1/valueSet/valueSetItems/DEPT_CODE/@value");
        Node positionNode = xmlParseUtil.getNode("/PRVS_IN000002UV01/controlActProcess/subject/registrationRequest/subject1/valueSet/valueSetItems/POSI_NAME/@value");
        Node authorIdNode = xmlParseUtil.getNode("/PRVS_IN000002UV01/controlActProcess/subject/registrationRequest/author/assignedEntity/id/item/@extension");
        Node authorNameNode = xmlParseUtil.getNode("/PRVS_IN000002UV01/controlActProcess/subject/registrationRequest/author/assignedEntity/assignedPerson/name/item/part/@value");
        Node telephoneNode = xmlParseUtil.getNode("/PRVS_IN000002UV01/controlActProcess/subject/registrationRequest/subject1/valueSet/valueSetItems/EMPL_TEL/@value");
        Node delFlagNode = xmlParseUtil.getNode("/PRVS_IN000002UV01/controlActProcess/subject/registrationRequest/subject1/valueSet/valueSetItems/STATUS_CODE/@value");
        boolean isDel = !notDelFlag.equals(delFlagNode.getNodeValue());
        UserDto userDto = new UserDto();
        userDto.setDeptId(deptCodeNode.getNodeValue());
        userDto.setReceiver(receiverNode.getNodeValue());
        userDto.setOperateType(operateTypeNode.getNodeValue());
        userDto.setUserName(employeeCodeNode.getNodeValue());
        userDto.setName(employeeNameNode.getNodeValue());
        userDto.setPosition(positionNode.getNodeValue());
        userDto.setAuthorId(authorIdNode.getNodeValue());
        userDto.setMessageId(msgIdNode.getNodeValue());
        userDto.setAuthorName(authorNameNode.getNodeValue());
        userDto.setRoleId(0L);
        userDto.setTelephone(telephoneNode != null ? telephoneNode.getNodeValue() : "");
        userDto.setDelFlag(isDel);
        return userDto;
    }

    /**
     * @param message  成功消息提示
     * @param msgId    消息id
     * @param receiver 接收方
     * @return 成功消息
     */
    private String successMessage(String message, String msgId, String receiver) {
        String createTime = Func.format(new Date(), DateUtil.PATTERN_DATETIME_MINI);
        return "<MCCI_IN000002UV01 ITSVersion=\"XML_1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:hl7-org:v3\" xsi:schemaLocation=\"urn:hl7-org:v3\n" +
                "file:///E:/hl7/HL7/v3ballot_fullsite_2011MAY/v3ballot/html/processable/multicacheschemas/MCCI\n" +
                "_IN000002UV01.xsd\">\n" +
                "\t<id extension=\"" + IdUtil.standardUUID() + "\"/>\n" +
                "\t<creationTime value=\"" + createTime + "\"/>\n" +
                "\t<interactionId root=\"2.16.840.1.113883.1.6\" extension=\"MCCI_IN000002UV01\"/>\n" +
                "\t<processingCode code=\"P\"/>\n" +
                "\t<processingModeCode/>\n" +
                "\t<acceptAckCode code=\"AL\"/>\n" +
                "\t<receiver typeCode=\"RCV\">\n" +
                "\t\t<device classCode=\"DEV\" determinerCode=\"INSTANCE\">\n" +
                "\t\t\t<id>\n" +
                "\t\t\t\t<item extension=\"MDM\"/>\n" +
                "\t\t\t</id>\n" +
                "\t\t</device>\n" +
                "\t</receiver>\n" +
                "\t<sender typeCode=\"SND\">\n" +
                "\t\t<device classCode=\"DEV\" determinerCode=\"INSTANCE\">\n" +
                "\t\t\t<id>\n" +
                "\t\t\t\t<item extension=\"" + receiver + "\"/>\n" +
                "\t\t\t</id>\n" +
                "\t\t</device>\n" +
                "\t</sender>\n" +
                "\t<acknowledgement typeCode=\"AA\">\n" +
                "\t\t<targetMessage>\n" +
                "\t\t\t<id extension=\"" + msgId + "\"/>\n" +
                "\t\t</targetMessage>\n" +
                "\t\t<acknowledgementDetail>\n" +
                "\t\t\t<text value=\"" + message + "\"/>\n" +
                "\t\t</acknowledgementDetail>\n" +
                "\t</acknowledgement>\n" +
                "</MCCI_IN000002UV01>";
    }

    /**
     * @param message  失败消息提示
     * @param msgId    消息id
     * @param receiver 接收方
     * @return 失败消息
     */
    private String failedMessage(String message, String msgId, String receiver) {
        String createTime = Func.format(new Date(), DateUtil.PATTERN_DATETIME_MINI);
        return "<RCMR_IN000030UV01 ITSVersion=\"XML_1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:hl7-org:v3\" xsi:schemaLocation=\"urn:hl7-org:v3\n" +
                "file:///E:/hl7/HL7/v3ballot_fullsite_2011MAY/v3ballot/html/processable/multicacheschemas/RCMR\n" +
                "_IN000030UV01.xsd\">\n" +
                "\n" +
                "\t<id extension=\"" + IdUtil.standardUUID() + "\"/>\n" +
                "\t<creationTime value=\"" + createTime + "\"/>\n" +
                "\t<interactionId root=\"2.16.840.1.113883.1.6\" extension=\"RCMR_IN000030UV01\"/>\n" +
                "\t<processingCode code=\"P\"/>\n" +
                "\t<processingModeCode/>\n" +
                "\t<acceptAckCode code=\"AL\"/>\n" +
                "\t<receiver typeCode=\"RCV\">\n" +
                "\t\t<device classCode=\"DEV\" determinerCode=\"INSTANCE\">\n" +
                "\t\t\t<id>\n" +
                "\t\t\t\t<item extension=\"MDM\"/>\n" +
                "\t\t\t</id>\n" +
                "\t\t</device>\n" +
                "\t</receiver>\n" +
                "\t<sender typeCode=\"SND\">\n" +
                "\t\t<device classCode=\"DEV\" determinerCode=\"INSTANCE\">\n" +
                "\t\t\t<id>\n" +
                "\t\t\t\t<item extension=\"" + receiver + "\"/>\n" +
                "\t\t\t</id>\n" +
                "\t\t</device>\n" +
                "\t</sender>\n" +
                "\t<acknowledgement typeCode=\"AE\">\n" +
                "\t\t<targetMessage>\n" +
                "\t\t\t<id extension=\"" + msgId + "\"/>\n" +
                "\t\t</targetMessage>\n" +
                "\t\t<acknowledgementDetail>\n" +
                "\t\t\t<text value=\"" + message + "\"/>\n" +
                "\t\t</acknowledgementDetail>\n" +
                "\t</acknowledgement>\n" +
                "</RCMR_IN000030UV01>\n";
    }

}

