package com.zcloud.primeport.command;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.zcloud.gbscommon.todolistmq.TodoListEventPusherUtil;
import com.zcloud.gbscommon.todolistmq.event.TodoListCompleteEvent;
import com.zcloud.gbscommon.utils.DateUtil;
import com.zcloud.gbscommon.utils.Tools;
import com.zcloud.gbscommon.zclouduser.facade.ZcloudUserFacade;
import com.zcloud.gbscommon.zclouduser.response.ZcloudUserCo;
import com.zcloud.primeport.domain.config.MessageTemplateConfig;
import com.zcloud.primeport.domain.gateway.ClosedAreaFgsPersonAreaGateway;
import com.zcloud.primeport.domain.gateway.ClosedAreaFgsPersonAuthGateway;
import com.zcloud.primeport.domain.gateway.ClosedAreaPersonApplyGateway;
import com.zcloud.primeport.domain.model.ClosedAreaCarApplyE;
import com.zcloud.primeport.domain.model.ClosedAreaFgsPersonAreaE;
import com.zcloud.primeport.domain.model.ClosedAreaFgsPersonAuthE;
import com.zcloud.primeport.domain.model.ClosedAreaPersonApplyE;
import com.zcloud.primeport.dto.ClosedAreaPersonApplyAuditCmd;
import com.zcloud.primeport.dto.ClosedAreaPersonApplyAuthCmd;
import com.zcloud.primeport.dto.ClosedAreaPersonApplyUpdateCmd;
import com.zcloud.primeport.plan.mjDevice.OnePersonUtil;
import com.zcloud.primeport.plan.mjDevice.TwoPersonUtil;
import lombok.AllArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * web-app
 *
 * @Author dearLin
 * @Date 2026-03-19 13:59:16
 */
@Component
@AllArgsConstructor
public class ClosedAreaPersonApplyUpdateExe {
    private final ClosedAreaPersonApplyGateway closedAreaPersonApplyGateway;
    private final ClosedAreaFgsPersonAuthGateway areaFgsPersonAuthGateway;
    private final ClosedAreaFgsPersonAreaGateway areaFgsPersonAreaGateway;
    private final MessageNoticeExe messageNoticeExe;
    private final MessageTemplateConfig messageTemplateConfig;
    private final TwoPersonUtil twoPersonUtil;
    private final OnePersonUtil onePersonUtil;

    @DubboReference
    private ZcloudUserFacade zcloudUserFacade;

    @Transactional(rollbackFor = Exception.class)
    public void execute(ClosedAreaPersonApplyUpdateCmd closedAreaPersonApplyUpdateCmd) {
        ClosedAreaPersonApplyE closedAreaPersonApplyE = new ClosedAreaPersonApplyE();
        BeanUtils.copyProperties(closedAreaPersonApplyUpdateCmd, closedAreaPersonApplyE);
        boolean res = closedAreaPersonApplyGateway.update(closedAreaPersonApplyE);
        if (!res) {
            throw new BizException("修改失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void auditPersonApply(ClosedAreaPersonApplyAuditCmd auditCmd) {
        ClosedAreaPersonApplyE closedAreaPersonApplyE =  closedAreaPersonApplyGateway.queryById(auditCmd.getId());
        if (closedAreaPersonApplyE == null) {
            throw new BizException("车辆申请记录不存在");
        };
        closedAreaPersonApplyE.setId(auditCmd.getId());
        closedAreaPersonApplyE.setAuditFlag(auditCmd.getAuditFlag());
        closedAreaPersonApplyE.setRefusalReason(auditCmd.getRefusalReason());
        closedAreaPersonApplyE.setAuditTime(DateUtil.date2Str(new Date()));
        closedAreaPersonApplyGateway.update(closedAreaPersonApplyE);

        // 完成待办
        messageNoticeExe.sendMessageCompleteEvent(auditCmd.getId());

        // 发送通知
        if (closedAreaPersonApplyE.getApplyPersonUserId() != null) {
            Map <String, Object> sendParams = new HashMap <>();
            if (closedAreaPersonApplyE.getProjectName() != null) {
                sendParams.put("projectName", closedAreaPersonApplyE.getProjectName());
            }

            String sourceCode = "您提交的一级口门车辆审批已通过";
            if (auditCmd.getAuditFlag().equals(2)) {
                // 通过
                sourceCode = messageTemplateConfig.getClosedAreaPersonReceiveAudit();
            }else {
                // 驳回
                sourceCode = messageTemplateConfig.getClosedAreaPersonReceiveAuditReject();
            }

            messageNoticeExe.sendMessageNotice(closedAreaPersonApplyE.getApplyPersonUserId(), sourceCode, sendParams);
        }

        // 审批通过 → 同步门禁权限（二级海康 + 一级大华）
        // 内部会先查大华系统判断是否已有权限，不覆盖原有权限
        if (auditCmd.getAuditFlag().equals(2)) {
            twoPersonUtil.levelTwoPeopleCompanyByApplyId(auditCmd.getId());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void authPerson(ClosedAreaPersonApplyAuthCmd cmd) {
        areaFgsPersonAuthGateway.removeByUserId(cmd.getUserId());
        ClosedAreaFgsPersonAuthE closedAreaFgsPersonAuthE = new ClosedAreaFgsPersonAuthE();
        closedAreaFgsPersonAuthE.setUserId(cmd.getUserId());
        closedAreaFgsPersonAuthE.setCorpId(cmd.getCorpId());
        closedAreaFgsPersonAuthE.setMkmjPermission(cmd.getMkmjPermission());
        closedAreaFgsPersonAuthE.setDepartmentId(cmd.getDepartmentId());
        areaFgsPersonAuthGateway.addOrUpdate(closedAreaFgsPersonAuthE);
        areaFgsPersonAreaGateway.removeByFgspersonAuthId(cmd.getUserId());
        ArrayList<ClosedAreaFgsPersonAreaE> objects = new ArrayList<>();
        List<ClosedAreaPersonApplyAuthCmd.FgsPersonArea> areaList = cmd.getAreaList();
        for (ClosedAreaPersonApplyAuthCmd.FgsPersonArea fgsPersonArea : areaList) {
            ClosedAreaFgsPersonAreaE closedAreaFgsPersonAreaE = new ClosedAreaFgsPersonAreaE();
            closedAreaFgsPersonAreaE.setClosedAreaId(fgsPersonArea.getClosedAreaId());
            closedAreaFgsPersonAreaE.setClosedAreaName(fgsPersonArea.getClosedAreaName());
            closedAreaFgsPersonAreaE.setFgsPersonAuthId(fgsPersonArea.getFgsPersonAuthId());
            objects.add(closedAreaFgsPersonAreaE);
        }
        areaFgsPersonAreaGateway.saveBatch(objects);
        // 开启门禁权限时，查一级大华是否有已有权限，不覆盖
        if (cmd.getMkmjPermission() != null && cmd.getMkmjPermission().equals(1)) {
            // 获取人员身份证号
            SingleResponse<ZcloudUserCo> userInfo = zcloudUserFacade.getInfoByUserId(cmd.getUserId());
            if (userInfo != null && userInfo.getData() != null) {
                String userCard = userInfo.getData().getUserIdCard();
                String userName = userInfo.getData().getName();
                String userFaceUrl = userInfo.getData().getUserAvatarUrl();
                if (Tools.notEmpty(userCard)) {
                    // 查询一级门禁(大华)是否已有权限
                    try {
                        cn.hutool.json.JSONArray dahuaUsers = onePersonUtil.getMkmjUserInfoByUserCard(Collections.singletonList(userCard));
                        if (dahuaUsers == null || dahuaUsers.isEmpty()) {
                            // 大华没有该用户 → 新增（有效期按每日任务刷新）
                            onePersonUtil.dockLongTermUserByUserCardAndFaceImg(
                                    userCard,
                                    "hbqa" + userCard,
                                    userName,
                                    userFaceUrl,
                                    DateUtil.date2Str(new Date(), "yyyy-MM-dd") + " 00:00:00",
                                    DateUtil.date2Str(new Date(), "yyyy-MM-dd") + " 23:59:59"
                            );
                        }
                        // 已有大华权限 → 保留，不覆盖
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}

