package com.changhu.module.management.enums.handler;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.changhu.common.db.enums.*;
import com.changhu.common.enums.ResultCode;
import com.changhu.common.exception.MessageException;
import com.changhu.common.utils.UserUtil;
import com.changhu.module.management.pojo.entity.ManagementSecurityUnitUser;
import com.changhu.module.management.pojo.entity.SecurityUnit;
import com.changhu.module.management.pojo.vo.UnitCheckStatusVo;
import com.changhu.module.management.service.ManagementSecurityUnitUserService;
import com.changhu.module.management.service.SecurityUnitService;
import com.changhu.module.miniProgram.pojo.entity.MiniProgramUser;
import com.changhu.module.miniProgram.service.MiniProgramUserService;
import com.changhu.support.mybatisplus.pojo.entity.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.List;

/**
 * @author 20252
 * @createTime 2024/9/2 上午9:55
 * @desc SecurityCheckPassHandler...
 */
@Slf4j
public class SecurityUnitTypeHandler extends AbstractUnitTypeHandler {

    private final SecurityUnitService securityUnitService = SpringUtil.getBean(SecurityUnitService.class);

    private final ManagementSecurityUnitUserService securityUnitUserService = SpringUtil.getBean(ManagementSecurityUnitUserService.class);

    private final MiniProgramUserService miniProgramUserService = SpringUtil.getBean(MiniProgramUserService.class);

    @Override
    public void pass(Long checkDataId) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);

        try {
            SecurityUnit securityUnit = securityUnitService.getOptById(checkDataId).orElseThrow(() -> new MessageException(ResultCode.DATA_NOT_FOUND));
            //更新状态
            boolean update = securityUnitService.lambdaUpdate()
                    .set(SecurityUnit::getCheckStatus, CheckStatus.checked)
                    .eq(BaseEntity::getSnowFlakeId, checkDataId)
                    .update();
            if (!update) {
                throw new MessageException(ResultCode.ERROR);
            }
            //生成简单的超级管理员账号密码
            String passWordEncrypt = UserUtil.passWordEncrypt(UserUtil.DEFAULT_PASSWORD);
            List<String> saltAndPassWord = StrUtil.split(passWordEncrypt, "$$");

            ManagementSecurityUnitUser managementSecurityUnitUser = new ManagementSecurityUnitUser();
            managementSecurityUnitUser.setSecurityUnitId(securityUnit.getSnowFlakeId());
            managementSecurityUnitUser.setName("超级管理员");
            managementSecurityUnitUser.setSex(Sex.UNKNOWN);
            managementSecurityUnitUser.setAccount(RandomUtil.randomString(6));
            managementSecurityUnitUser.setTelephone("");
            managementSecurityUnitUser.setSalt(saltAndPassWord.get(0));
            managementSecurityUnitUser.setPassword(saltAndPassWord.get(1));
            managementSecurityUnitUser.setIsEnable(IsEnable.TRUE);
            managementSecurityUnitUser.setIsAdmin(IsOrNot.IS);
            managementSecurityUnitUser.setRemark("单位审核通过 默认分配超管账号");
            boolean save = securityUnitUserService.save(managementSecurityUnitUser);
            if (!save) {
                throw new MessageException(ResultCode.ERROR);
            }

            //提交事务
            transactionManager.commit(status);
        } catch (Exception e) {
            //回滚事务
            transactionManager.rollback(status);
            log.error("保安单位审核通过错误:{}", e.getMessage());
            throw new MessageException(e.getMessage());
        }
    }

    @Override
    public UnitCheckStatusVo getCheckStatus(String onlyCode) {
        SecurityUnit securityUnit = securityUnitService.lambdaQuery()
                .eq(SecurityUnit::getSocialCode, onlyCode)
                .oneOpt()
                .orElseThrow(() -> new MessageException(ResultCode.DATA_NOT_FOUND));

        UnitCheckStatusVo unitCheckStatusVo = new UnitCheckStatusVo();
        unitCheckStatusVo.setCheckStatus(securityUnit.getCheckStatus());

        if (securityUnit.getCheckStatus().equals(CheckStatus.checked)) {
            ManagementSecurityUnitUser managementSecurityUnitUser = securityUnitUserService.lambdaQuery()
                    .eq(ManagementSecurityUnitUser::getSecurityUnitId, securityUnit.getSnowFlakeId())
                    .eq(ManagementSecurityUnitUser::getIsAdmin, IsOrNot.IS)
                    .oneOpt()
                    .orElseThrow(() -> new MessageException("超管账号未初始化 请联系管理员"));
            unitCheckStatusVo.setAccount(managementSecurityUnitUser.getAccount());
            unitCheckStatusVo.setRemark("恭喜!单位审核通过了,请使用管理员账号前往登录页进行登录.");
        } else {
            unitCheckStatusVo.setPassword(null);
            unitCheckStatusVo.setRemark("单位注册申请正在审核中...");
        }

        return unitCheckStatusVo;
    }

    @Override
    public void disableOrEnable(Long unitId) {
        SecurityUnit securityUnit = securityUnitService.lambdaQuery()
                .eq(BaseEntity::getSnowFlakeId, unitId)
                .oneOpt()
                .orElseThrow(() -> new MessageException(ResultCode.DATA_NOT_FOUND));
        //取反
        IsEnable isEnable = switch (securityUnit.getIsEnable()) {
            case TRUE -> IsEnable.FALSE;
            case FALSE -> IsEnable.TRUE;
        };

        boolean update = securityUnitService.lambdaUpdate()
                .set(SecurityUnit::getIsEnable, isEnable)
                .eq(BaseEntity::getSnowFlakeId, unitId)
                .update();
        if (!update) {
            throw new MessageException();
        }
    }

    @Override
    public void passMiniProgramUser(Long miniProgramUserId) {
        boolean update = miniProgramUserService.lambdaUpdate()
                .set(MiniProgramUser::getCheckStatus, CheckStatus.checked)
                .eq(BaseEntity::getSnowFlakeId, miniProgramUserId)
                .eq(MiniProgramUser::getIdentity, MiniProgramUserIdentity.PROJECT_MANAGER)
                .update();
        if (!update) {
            throw new MessageException();
        }
    }

    @Override
    public void disableOrEnableMiniProgramUser(Long miniProgramUserId) {
        MiniProgramUser miniProgramUser = miniProgramUserService.lambdaQuery()
                .eq(BaseEntity::getSnowFlakeId, miniProgramUserId)
                .eq(MiniProgramUser::getIdentity, MiniProgramUserIdentity.PROJECT_MANAGER)
                .oneOpt()
                .orElseThrow(() -> new MessageException(ResultCode.DATA_NOT_FOUND));

        //取反
        IsEnable isEnable = switch (miniProgramUser.getIsEnable()) {
            case TRUE -> IsEnable.FALSE;
            case FALSE -> IsEnable.TRUE;
        };

        boolean update = miniProgramUserService.lambdaUpdate()
                .set(MiniProgramUser::getIsEnable, isEnable)
                .eq(BaseEntity::getSnowFlakeId, miniProgramUserId)
                .update();
        if (!update) {
            throw new MessageException();
        }

    }

}
