package com.yida.data.system.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import com.yida.data.common.core.entity.constant.AppConstant;
import com.yida.data.common.core.entity.constant.QywxConstant;
import com.yida.data.common.core.entity.constant.QywxServiceProviderConstant;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.system.EduApp;
import com.yida.data.common.core.entity.system.EduQywxServiceProvider;
import com.yida.data.common.core.entity.system.EduQywxServiceProviderSchool;
import com.yida.data.common.core.utils.WxUtil;
import com.yida.data.common.service.CommonService;
import com.yida.data.system.dto.QywxCallbackHandleDTO;
import com.yida.data.system.service.QywxHandleService;
import com.yida.data.system.service.QywxService;
import com.yida.data.system.service.QywxServiceProviderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * 企业微信回调mq处理类
 *
 * @author ZYJ
 * @date 2023/10/27 16:43
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class QywxHandleServiceImpl implements QywxHandleService {

    private final QywxService qywxService;
    private final QywxServiceProviderService qywxServiceProviderService;

    private final WxUtil wxUtil;
    private final CommonService commonService;

    @Override
    @GlobalTransactional
    public void handlePostCallback(QywxCallbackHandleDTO dto) {
        Element root = dto.getRoot();
        String corpId = dto.getCorpId();
        Dept school = dto.getSchool();

        NodeList nodeList1 = root.getElementsByTagName("ChangeType");
        String changeType = nodeList1.item(0).getTextContent();

        NodeList nodeList2 = root.getElementsByTagName("Event");
        String event = nodeList2.item(0).getTextContent();

        if (QywxConstant.SCHOOL_CONTACT_EVENT.equals(event)) {

            EduApp app = commonService.getAppByCodeAndSchool(AppConstant.CONTACT_SCHOOL, null, school.getDeptId());
            String id = root.getElementsByTagName("Id").item(0).getTextContent();

            switch (changeType) {
                case QywxConstant.SCHOOL_DEPT_CREATE_TYPE:
                    qywxService.createSchoolDept(corpId, wxUtil.getAccessToken(app.getWxCorpId(),
                            app.getWxSecret()), Long.valueOf(id), school);
                    break;
                case QywxConstant.SCHOOL_DEPT_UPDATE_TYPE:
                    qywxService.updateSchoolDept(wxUtil.getAccessToken(app.getWxCorpId(),
                            app.getWxSecret()), Long.valueOf(id), school);
                    break;
                case QywxConstant.SCHOOL_DEPT_DELETE_TYPE:
                    qywxService.deleteSchoolDept(Long.valueOf(id), school);
                    break;
                case QywxConstant.STUDENT_CREATE_TYPE:
                case QywxConstant.STUDENT_UPDATE_TYPE:
                    qywxService.changeStudent(wxUtil.getAccessToken(app.getWxCorpId(),
                            app.getWxSecret()), id, school);
                    break;
                case QywxConstant.STUDENT_DELETE_TYPE:
                    qywxService.deleteStudent(id, school.getDeptId());
                    break;
                case QywxConstant.PARENT_CREATE_TYPE:
                    // 新增家长可能是创建学生时创建，等待2s确保学生创建完成
                    ThreadUtil.sleep(2000);
                case QywxConstant.PARENT_UPDATE_TYPE:
                    qywxService.updateParent(wxUtil.getAccessToken(app.getWxCorpId(),
                            app.getWxSecret()), id, school.getDeptId());
                    break;
                case QywxConstant.PARENT_DELETE_TYPE:
                    qywxService.deleteParent(id, school.getDeptId());
                    break;
                case QywxConstant.PARENT_SUBSCRIBE_TYPE:
                    log.info("进入家长关注事件回调");
                    // 调用家长关注发送通知方法
                    qywxService.sendParentSubscribeMessage(id, school.getDeptId());
                    break;
                case QywxConstant.PARENT_UNSUBSCRIBE_TYPE:
                    log.info("进入家长取消关注事件回调");
                    break;
                default:
                    break;
            }
        }

        if (QywxConstant.CONTACT_EVENT.equals(event)) {
            String userid = null, phone = null, name = null, gender = null, avatar = null, department = null,
                    isLeader = null, mainDepartment = null, email = null;
            if (root.getElementsByTagName("UserID").getLength() != 0) {
                userid = root.getElementsByTagName("UserID").item(0).getTextContent();
            }
            if (root.getElementsByTagName("Mobile").getLength() != 0) {
                phone = root.getElementsByTagName("Mobile").item(0).getTextContent();
            }
            if (root.getElementsByTagName("Name").getLength() != 0) {
                name = root.getElementsByTagName("Name").item(0).getTextContent();
            }
            if (root.getElementsByTagName("Gender").getLength() != 0) {
                gender = root.getElementsByTagName("Gender").item(0).getTextContent();
            }
            if (root.getElementsByTagName("Avatar").getLength() != 0) {
                avatar = root.getElementsByTagName("Avatar").item(0).getTextContent();
            }
            if (root.getElementsByTagName("Department").getLength() != 0) {
                department = root.getElementsByTagName("Department").item(0).getTextContent();
            }
            if (root.getElementsByTagName("IsLeaderInDept").getLength() != 0) {
                isLeader = root.getElementsByTagName("IsLeaderInDept").item(0).getTextContent();
            }
            if (root.getElementsByTagName("MainDepartment").getLength() != 0) {
                mainDepartment = root.getElementsByTagName("MainDepartment").item(0).getTextContent();
            }
            if (root.getElementsByTagName("Email").getLength() != 0) {
                email = root.getElementsByTagName("Email").item(0).getTextContent();
            }


            String deptId = null, deptName = null, deptParentId = null, order = null;
            if (root.getElementsByTagName("Id").getLength() != 0) {
                deptId = root.getElementsByTagName("Id").item(0).getTextContent();
            }
            if (root.getElementsByTagName("Name").getLength() != 0) {
                deptName = root.getElementsByTagName("Name").item(0).getTextContent();
            }
            if (root.getElementsByTagName("ParentId").getLength() != 0) {
                deptParentId = root.getElementsByTagName("ParentId").item(0).getTextContent();
            }
            if (root.getElementsByTagName("Order").getLength() != 0) {
                order = root.getElementsByTagName("Order").item(0).getTextContent();
            }

            switch (changeType) {
                case QywxConstant.USER_CREATE_TYPE:
                    qywxService.createUser(name, userid, phone, email, gender, avatar, department, isLeader,
                            mainDepartment, school);
                    break;
                case QywxConstant.USER_UPDATE_TYPE:
                    qywxService.updateUser(name, userid, phone, email, gender, avatar, department, isLeader,
                            mainDepartment, school);
                    break;
                case QywxConstant.USER_DELETE_TYPE:
                    qywxService.deleteUser(userid, school.getDeptId());
                    break;
                case QywxConstant.DEPT_CREATE_TYPE:
                    qywxService.createDept(deptId, deptName, deptParentId, order, school);
                    break;
                case QywxConstant.DEPT_UPDATE_TYPE:
                    qywxService.updateDept(deptId, deptName, deptParentId, school.getDeptId());
                    break;
                case QywxConstant.DEPT_DELETE_TYPE:
                    qywxService.deleteDept(deptId, school.getDeptId());
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    @GlobalTransactional
    public void handlePostNormalCallback(QywxCallbackHandleDTO dto) {
        Element root = dto.getRoot();
        EduQywxServiceProvider serviceProvider = dto.getEduQywxServiceProvider();

        // 通知消息类型
        NodeList nodeList = root.getElementsByTagName("InfoType");
        String infoType = nodeList.item(0).getTextContent();
        // 模板id
        NodeList nodeListSuiteId = root.getElementsByTagName("SuiteId");
        String suiteId = nodeListSuiteId.item(0).getTextContent();
        // 通讯录变更
        if (QywxConstant.CONTACT_EVENT.equals(infoType)) {
            log.info("模板回调进入通讯录变更事件");
            qywxServiceProviderService.handleConcat(root, serviceProvider, suiteId);
        }
        switch (infoType) {
            // 安装应用授权
            case QywxServiceProviderConstant.SERVICE_CREATE_AUTH:
                // 临时授权码
                NodeList nodeListAuthCode = root.getElementsByTagName("AuthCode");
                String authCode = nodeListAuthCode.item(0).getTextContent();
                qywxServiceProviderService.installTemplateApp(suiteId, authCode, serviceProvider);
                break;
            // 客户删除应用
            case QywxServiceProviderConstant.SERVICE_CANCEL_AUTH:
                // 授权企业加密corpId
                NodeList nodeListAuthCorpId = root.getElementsByTagName("AuthCorpId");
                String authCorpId = nodeListAuthCorpId.item(0).getTextContent();
                qywxServiceProviderService.deleteTemplateApp(suiteId, authCorpId, serviceProvider);
                break;
            // 待开发应用模板suite_ticket
            case QywxServiceProviderConstant.TEMPLATE_SUITE_TICKET:
                // 模板id
                NodeList nodeListTicket = root.getElementsByTagName("SuiteTicket");
                String suiteTicket = nodeListTicket.item(0).getTextContent();
                qywxServiceProviderService.handleTemplateSuiteTicket(suiteId, suiteTicket);
                break;
            // 代开发应用重置secret
            case QywxServiceProviderConstant.RESET_PERMANENT_CODE:
                // 临时授权码
                NodeList nodeListResetAuthCode = root.getElementsByTagName("AuthCode");
                String resetAuthCode = nodeListResetAuthCode.item(0).getTextContent();
                qywxServiceProviderService.resetTemplateAppAuthCode(suiteId, resetAuthCode, serviceProvider);
                break;
            default:
                break;
        }
    }

    @Override
    @GlobalTransactional
    public void handlePostEventCallback(QywxCallbackHandleDTO dto) {
        Element root = dto.getRoot();
        Dept school = dto.getSchool();
        EduQywxServiceProviderSchool providerSchool = dto.getProviderSchool();

        NodeList nodeListEvent = root.getElementsByTagName("Event");
        String event = nodeListEvent.item(0).getTextContent();

        if (QywxConstant.SCHOOL_CONTACT_EVENT.equals(event)) {
            log.info("进入家校沟通通讯录处理事件");
            qywxServiceProviderService.handleSchoolConcat(root, providerSchool, school);
        }
        // 通讯录变更
        if (QywxConstant.CONTACT_EVENT.equals(event)) {
            log.info("进入通讯录变更事件");
            qywxServiceProviderService.handleConcat(root, providerSchool);
        }
    }
}
