package com.hz.pm.api.sys.manage;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.hz.pm.api.expert.entity.ExpertUserFullInfo;
import com.ningdatech.basic.function.VUtils;
import com.hz.pm.api.common.model.constant.BizConst;
import com.hz.pm.api.expert.service.IExpertUserFullInfoService;
import com.hz.pm.api.signature.entity.CompanySignature;
import com.hz.pm.api.signature.service.ICompanySignatureService;
import com.hz.pm.api.sys.contants.UserGuidanceContant;
import com.hz.pm.api.sys.model.entity.UserRole;
import com.hz.pm.api.sys.model.vo.UserGuidanceDetailVO;
import com.hz.pm.api.sys.model.vo.UserGuidanceVO;
import com.hz.pm.api.sys.service.IUserRoleService;
import com.hz.pm.api.user.model.entity.UserAuth;
import com.hz.pm.api.user.model.entity.UserInfo;
import com.hz.pm.api.user.security.model.UserInfoDetails;
import com.hz.pm.api.user.service.IUserAuthService;
import com.hz.pm.api.user.service.IUserInfoService;
import com.wflow.bean.entity.WflowOrgModels;
import com.wflow.enums.ProcessDefTypeEnum;
import com.wflow.service.OrgProcdefService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Classname UserGuidanceManage
 * @Description
 * @Date 2023/8/8 13:49
 * @Author PoffyZhang
 */
@Component
@Slf4j
@AllArgsConstructor
public class UserGuidanceManage {

    private final OrgProcdefService orgProcdefService;

    private final IUserInfoService userInfoService;

    private final IUserRoleService userRoleService;

    private final IUserAuthService userAuthService;

    private final ICompanySignatureService signatureService;

    private final IExpertUserFullInfoService expertUserFullInfoService;

    /**
     * 查询用户引导 详情
     *
     * @param user
     * @return
     */
    public UserGuidanceVO detailUserGuidance(UserInfoDetails user) {
        UserGuidanceVO vo = new UserGuidanceVO();
        vo.setOrgCode(user.getMhUnitId());
        //用户信息
        String username = user.getUsername();
        vo.setUsername(username);
        Long userId = user.getUserId();
        vo.setUserId(userId);

        //查询引导详情
        List<UserGuidanceDetailVO> details = Lists.newArrayList();
        UserGuidanceDetailVO orgModelGuidance = new UserGuidanceDetailVO();
        orgModelGuidance.setName(UserGuidanceContant.OrgModel.GUIDANCE_NAME);
        orgModelGuidance.setRemark(UserGuidanceContant.OrgModel.GUIDANCE_REMARK);

        Integer finishedNum = 0;
        //1.去查询 用户所在单位 有没有单位默认流程配置 并且process 不能为空
        WflowOrgModels orgModel = orgProcdefService.getOne(Wrappers.lambdaQuery(WflowOrgModels.class)
                .eq(WflowOrgModels::getOrgCode, user.getMhUnitIdStr())
                .eq(WflowOrgModels::getType, ProcessDefTypeEnum.DEFAULT.name())
                .eq(WflowOrgModels::getIsDelete, Boolean.FALSE)
                .last(BizConst.LIMIT_1));
        if (Objects.isNull(orgModel)) {
            orgModelGuidance.setPath(UserGuidanceContant.OrgModel.GUIDANCE_PATH1);
            orgModelGuidance.setIsFinish(Boolean.FALSE);
        } else {
            orgModelGuidance.setPath(UserGuidanceContant.OrgModel.GUIDANCE_PATH2 + orgModel.getProcessDefId());
            //判断process是否为空
            if (StringUtils.isNotBlank(orgModel.getProcess()) &&
                    !UserGuidanceContant.OrgModel.EMPTY_PROCESS.equals(orgModel.getProcess())) {
                orgModelGuidance.setIsFinish(Boolean.TRUE);
                finishedNum++;
            } else {
                orgModelGuidance.setIsFinish(Boolean.FALSE);
            }
        }
        details.add(orgModelGuidance);

        //2.去查询 印章编码
        UserGuidanceDetailVO signatureGuidance = new UserGuidanceDetailVO();
        signatureGuidance.setName(UserGuidanceContant.Signature.GUIDANCE_NAME);
        signatureGuidance.setRemark(UserGuidanceContant.Signature.GUIDANCE_REMARK);
        signatureGuidance.setPath(UserGuidanceContant.Signature.GUIDANCE_PATH);
        CompanySignature signature = signatureService.getOne(Wrappers.lambdaQuery(CompanySignature.class)
                .eq(CompanySignature::getOrganizationCode, user.getMhUnitIdStr())
                .last(BizConst.LIMIT_1));
        if (Objects.isNull(signature)) {
            signatureGuidance.setIsFinish(Boolean.FALSE);
        } else {
            //判断印章编码是否为空
            if (StringUtils.isNotBlank(signature.getSealSn())) {
                signatureGuidance.setIsFinish(Boolean.TRUE);
                finishedNum++;
            } else {
                signatureGuidance.setIsFinish(Boolean.FALSE);
            }
        }
        details.add(signatureGuidance);

        if (UserGuidanceContant.ALL_FINISHED_NUM.equals(finishedNum)) {
            vo.setIsAllFinished(Boolean.TRUE);
        }
        vo.setDetails(details);
        return vo;
    }

    /**
     * 删除重复用户
     *
     * @param userId
     * @return
     */
    public String removeRepeat(Long userId) {
        UserInfo user = userInfoService.getById(userId);
        Assert.notNull(user, "该用户不存在 删除重复失败");
        List<UserInfo> repeatUsers = userInfoService.list(Wrappers.lambdaQuery(UserInfo.class)
                .eq(UserInfo::getUsername, user.getUsername())
                .ne(UserInfo::getId, userId)
                .isNull(UserInfo::getAccountId));
        if (CollUtil.isNotEmpty(repeatUsers)) {
            List<Long> repeatIds = repeatUsers.stream().map(UserInfo::getId).collect(Collectors.toList());
            userInfoService.removeBatchByIds(repeatIds);
            userAuthService.remove(Wrappers.lambdaQuery(UserAuth.class)
                    .in(UserAuth::getUserId, repeatIds));
            userRoleService.remove(Wrappers.lambdaQuery(UserRole.class).in(UserRole::getUserId, repeatIds));
            for (Long repeatId : repeatIds) {
                ExpertUserFullInfo expert = expertUserFullInfoService.getByUserId(repeatId);
                expert.setUserId(userId);
                expertUserFullInfoService.updateById(expert);
            }
            return "删除成功";
        }
        return "不存在重复的用户";
    }
}
