package com.zcloud.primeport.command;

import com.alibaba.cola.dto.PageResponse;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.zcloud.gbscommon.todolistmq.TodoListEventPusherUtil;
import com.zcloud.gbscommon.todolistmq.event.TodoListAddEvent;
import com.zcloud.gbscommon.utils.DateUtil;
import com.zcloud.primeport.domain.config.MessageTemplateConfig;
import com.zcloud.primeport.domain.gateway.PersonApplyGateway;
import com.zcloud.primeport.domain.gateway.XgfApplyPersonGateway;
import com.zcloud.primeport.domain.model.PersonApplyE;
import com.zcloud.primeport.domain.model.XgfApplyPersonE;
import com.zcloud.primeport.dto.PersonApplyAddCmd;
import com.zcloud.primeport.dto.PersonAuthCmd;
import com.zcloud.primeport.dto.XgfApplyPersonPageQry;
import com.zcloud.primeport.dto.XgfPersonApplyAddCmd;
import com.zcloud.primeport.dto.clientobject.PersonApplyCO;
import com.zcloud.primeport.dto.clientobject.XgfPersonApplyCO;
import jodd.util.Base64;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZoneOffset;
import java.util.*;


/**
 * web-app
 *
 * @Author makejava
 * @Date 2026-03-05 11:33:21
 */
@Component
@AllArgsConstructor
public class PersonApplyAddExe {
    private final PersonApplyGateway personApplyGateway;
    private final XgfApplyPersonGateway xgfApplyPersonGateway;
    private final MessageNoticeExe messageNoticeExe;
    private final MessageTemplateConfig messageTemplateConfig;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(PersonApplyAddCmd cmd) {
        PersonApplyE examTypeE = new PersonApplyE();
        BeanUtils.copyProperties(cmd, examTypeE);
        boolean res = false;
        try {
            res = personApplyGateway.add(examTypeE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!res) {
            throw new BizException("保存失败");
        }
        return true;
    }

    public Long xgfPersonSave(XgfPersonApplyAddCmd cmd) {
        // 先进行相关方申请的保存
        XgfApplyPersonE build = XgfApplyPersonE.builder().personBelongType(cmd.getPersonBelongType())
                .gateLevelAuthArea(cmd.getGateLevelAuthArea())
                .mkmjId(cmd.getMkmjId())
                .mkmjName(cmd.getMkmjName())
                .auditFlag((cmd.getPersonBelongType() == 1 || cmd.getPersonBelongType() == 2) ? 2 : 1)
                .auditCorpId(cmd.getAuditCorpId()).auditCorpName(cmd.getAuditCorpName())
                .auditDeptId(cmd.getAuditDeptId()).auditDeptName(cmd.getAuditDeptName())
                .auditUserId(cmd.getAuditUserId()).auditUserName(cmd.getAuditUserName())
                .reasonVisit(cmd.getReasonVisit())
                .visitStartTime(cmd.getVisitStartTime())
                .visitEndTime(cmd.getVisitEndTime())
                .applyCorpId(cmd.getPersonBelongType() != 4 ? AuthContext.getTenantId() : null)
                .applyCorpName(cmd.getPersonBelongType() != 4 ? AuthContext.getCurrentUser().getTenantName() : null)
                .projectId(cmd.getProjectId()).projectName(cmd.getProjectName()).informSignId(cmd.getInformSignId()).build();
        xgfApplyPersonGateway.save(build);


        // 发送 消息提醒 和 待办
        if (cmd.getAuditUserId() != null) {
            // 发送消息提醒
            Map <String, Object> sendParams = new HashMap <>();
            messageNoticeExe.sendMessageNotice(cmd.getAuditUserId(), messageTemplateConfig.getFirstLevelApplyReceiveAudit(), sendParams);
            // 发送待办
            messageNoticeExe.sendMessageTodoEvent(cmd.getAuditUserId(), "您有一条口门审核，请及时进行审核。", "待审核", build.getId(), build.getId(), 1, 1);
        }

        List<XgfPersonApplyAddCmd.PersonApplyAddCmdExt> personApplyList = cmd.getPersonApplyList();
        // 相关方人员信息的保存
        ArrayList<PersonApplyE> personApplyES = new ArrayList<>();
        personApplyList.forEach(personApply -> {
            PersonApplyE personApplyE = new PersonApplyE();
            BeanUtils.copyProperties(personApply, personApplyE);
            personApplyE.setXgfApplyPersonId(build.getId());
            personApplyE.setMkmjPermission((cmd.getPersonBelongType() == 1 || cmd.getPersonBelongType() == 2) ? 1 : 2);
            personApplyE.setUserCard(personApply.getUserCard());
            personApplyES.add(personApplyE);
        });
        personApplyGateway.saveBatch(personApplyES);
        return build.getId();
    }

    public void authorization(PersonAuthCmd cmd) {
        XgfPersonApplyAddCmd xgfPersonApplyAddCmd = new XgfPersonApplyAddCmd();
        xgfPersonApplyAddCmd.setPersonBelongType(cmd.getPersonBelongType());
        xgfPersonApplyAddCmd.setGateLevelAuthArea(cmd.getGateLevelAuthArea());
        XgfPersonApplyAddCmd.PersonApplyAddCmdExt personApplyAddCmdExt = new XgfPersonApplyAddCmd.PersonApplyAddCmdExt();
        personApplyAddCmdExt.setPersonCorpId(cmd.getCorpinfoId());
        personApplyAddCmdExt.setPersonCorpName(cmd.getCorpName());
        personApplyAddCmdExt.setPersonDepartmentId(cmd.getDepartmentId());
        personApplyAddCmdExt.setPersonDepartmentName(cmd.getDepartmentName());
        personApplyAddCmdExt.setEmployeePersonUserName(cmd.getUserName());
        personApplyAddCmdExt.setEmployeePersonUserId(cmd.getUserId());
        personApplyAddCmdExt.setUserFaceUrl(cmd.getUserFaceUrl());
        personApplyAddCmdExt.setUserCard(cmd.getUserCard());
        personApplyAddCmdExt.setUserPhone(cmd.getUserPhone());
        personApplyAddCmdExt.setVisitStartTime(DateUtil.date2Str(new Date()));
        personApplyAddCmdExt.setVisitEndTime("2099-12-31 23:59:59");
        personApplyAddCmdExt.setUserPhone(cmd.getUserPhone());
        xgfPersonApplyAddCmd.setPersonApplyList(new ArrayList<XgfPersonApplyAddCmd.PersonApplyAddCmdExt>() {{
            add(personApplyAddCmdExt);
        }});
        xgfPersonSave(xgfPersonApplyAddCmd);
    }

    public XgfPersonApplyCO xgfPersonApplyInfoById(Long id) {
        XgfPersonApplyCO xgfPersonApplyCO = new XgfPersonApplyCO();
        XgfApplyPersonE xgfApplyPersonE = xgfApplyPersonGateway.getInfoById(id);
        xgfApplyPersonE.setApplyTime(DateUtil.date2Str(Date.from(xgfApplyPersonE.getCreateTime().toInstant(ZoneOffset.ofHours(8)))));
        BeanUtils.copyProperties(xgfApplyPersonE, xgfPersonApplyCO);
        List<PersonApplyE> userApplyList = personApplyGateway.personListByxgfApplyPersonId(id);
        ArrayList<XgfPersonApplyAddCmd.PersonApplyAddCmdExt> personApplyAddCmdExts = new ArrayList<>();
        userApplyList.forEach(item -> {
            XgfPersonApplyAddCmd.PersonApplyAddCmdExt personApplyAddCmdExt = new XgfPersonApplyAddCmd.PersonApplyAddCmdExt();
            BeanUtils.copyProperties(item, personApplyAddCmdExt);
            personApplyAddCmdExts.add(personApplyAddCmdExt);
        });
        xgfPersonApplyCO.setPersonApplyCount(personApplyAddCmdExts.size());
        xgfPersonApplyCO.setPersonApplyList(personApplyAddCmdExts);
        return xgfPersonApplyCO;
    }
}

