//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.testor.biz.sys.log.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.testor.biz.sys.log.LogEnumCode;
import com.testor.biz.sys.log.dao.SysLogDao;
import com.testor.biz.sys.log.model.domain.SysLog;
import com.testor.biz.sys.log.service.SysLogService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.resource.model.domain.SysResource;
import com.testor.biz.sys.resource.service.SysResourceService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.tongtech.tfw.backend.common.constants.enumeration.HttpStatusCodeEnum;
import com.tongtech.tfw.backend.common.jwt.JwtHelper;
import com.tongtech.tfw.backend.common.models.jwt.JwtInfos;
import com.tongtech.tfw.backend.common.models.response.FailedResponse;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.common.request.RequestUtil;
import com.tongtech.tfw.backend.common.response.ResponseWrapper;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.json.JacksonHelper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;

public class NewSysLogServiceImpl extends SuperServiceImpl<SysLogDao, SysLog> implements SysLogService {
    private final SysUserService sysUserService;
    private final SysOrgService sysOrgService;
    private final SysResourceService sysResourceService;

    public NewSysLogServiceImpl(SysUserService sysUserService, SysOrgService sysOrgService, SysResourceService sysResourceService) {
        this.sysUserService = sysUserService;
        this.sysOrgService = sysOrgService;
        this.sysResourceService = sysResourceService;
    }

    public void saveLog(HttpServletRequest request, ResponseWrapper response, Object result) throws Exception {
        SysLog sysLog = new SysLog();
        sysLog.setId(IdHelper.getId32bit());
        sysLog.setUri((String) request.getAttribute("url"));
        String contentPath = request.getContextPath();
        String url = StringHelper.removePrefix(sysLog.getUri(), contentPath);

        SysResource sysResource = this.sysResourceService.getOne(new LambdaQueryWrapper<SysResource>()
                .select(SysResource::getResourceId, SysResource::getResourceName, SysResource::getParentIds)
                .eq(SysResource::getResourceUrl, url)
                .eq(SysResource::getStatus, "0")
                .last("LIMIT 1"), false);
        if (ObjectHelper.isNotEmpty(sysResource)) {
            StringBuilder actionName = new StringBuilder();
            String[] parents = StringHelper.split(sysResource.getParentIds(), ",");
            String[] var10 = parents;
            int var11 = parents.length;

            for (int var12 = 0; var12 < var11; ++var12) {
                String pid = var10[var12];
                if (!"0".equals(pid)) {
                    actionName.append(((SysResource) this.sysResourceService.getById(pid)).getResourceName()).append("-");
                }
            }

            actionName.append(sysResource.getResourceName());
            sysLog.setActions(actionName.toString());
        } else {
            sysLog.setActions(url);
        }

        sysLog.setIp(RequestUtil.getIpAddr(request));
        sysLog.setMethod((String) request.getAttribute("method"));
        sysLog.setStatus("0");
        sysLog.setOpTime(new Date());
        sysLog.setUser("Unknown");
        sysLog.setDept("Unknown");
        sysLog.setCreateBy("Unknown");
        sysLog.setCreateDate(new Date());
        String authorization = request.getHeader("Authorization");
        JwtInfos jwtInfos = JwtHelper.parseJwtAuth0(authorization, "Token Issuer");
        if (StringUtils.isNotBlank(jwtInfos.getUserId())) {
            String userId = jwtInfos.getUserId();
            sysLog.setCreateBy(userId);
            SysUser sysUser = (SysUser) this.sysUserService.getById(userId);
            if (ObjectHelper.isNotEmpty(sysUser)) {
                sysLog.setUser(sysUser.getUserName());
                SysOrg sysOrg = (SysOrg) this.sysOrgService.getById(sysUser.getOrgId());
                StringBuilder orgName = new StringBuilder();
                if (ObjectHelper.isNotEmpty(sysOrg)) {
                    String[] parents = StringHelper.split(sysOrg.getParentIds(), ",");
                    String[] var15 = parents;
                    int var16 = parents.length;

                    for (int var17 = 0; var17 < var16; ++var17) {
                        String pid = var15[var17];
                        if (!"0".equals(pid)) {
                            orgName.append(((SysOrg) this.sysOrgService.getById(pid)).getOrgName()).append("-");
                        }
                    }

                    orgName.append(sysOrg.getOrgName());
                    sysLog.setDept(orgName.toString());
                } else {
                    sysLog.setDept(sysUser.getOrgId());
                }
            } else {
                sysLog.setUser(userId);
            }
        }

        if (result instanceof FailedResponse) {
            FailedResponse failedResponse = (FailedResponse) result;
            if (HttpStatusCodeEnum.OK.code() == failedResponse.getCode()) {
                sysLog.setType(new BigDecimal(LogEnumCode.OPERATION.code()));
            } else {
                sysLog.setType(new BigDecimal(LogEnumCode.OTHER.code()));
            }

            sysLog.setMsg(JacksonHelper.toJson(result));
        } else {
            sysLog.setType(new BigDecimal(LogEnumCode.OPERATION.code()));
            if (sysLog.getUri().contains("/auth/login")) {
                sysLog.setType(new BigDecimal(LogEnumCode.LOGGING.code()));
            }
        }

        this.save(sysLog);
    }
}
