package com.zhongshu.card.server.core.service.base;

import com.github.microservice.auth.security.helper.AuthClientSecurityAuthenticationHelper;
import com.github.microservice.auth.security.helper.AuthHelper;
import com.zhongshu.card.client.model.base.SuperParam;
import com.zhongshu.card.client.model.base.SuperSearch;
import com.zhongshu.card.client.model.operLogs.OperationLogsAddParam;
import com.zhongshu.card.server.core.dao.org.OrganizationDao;
import com.zhongshu.card.server.core.dao.org.UserCountDao;
import com.zhongshu.card.server.core.domain.base.SuperMain;
import com.zhongshu.card.server.core.domain.org.Organization;
import com.zhongshu.card.server.core.domain.org.UserAccount;
import com.zhongshu.card.client.utils.DateUtils;
import com.zhongshu.card.server.core.util.CommonUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @author TRX
 * @date 2024/6/3
 */
@Slf4j
public abstract class SuperService {

    @Autowired
    private AuthHelper authHelper;

    @Autowired
    UserCountDao userCountDao;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private AuthClientSecurityAuthenticationHelper authClientSecurityAuthenticationHelper;

    @Autowired
    private OrganizationDao organizationDao;

    /**
     * 得到当前的用户ID
     *
     * @return
     */
    public String getCurrentUserId() {
        try {
            if (authHelper != null && authHelper.getCurrentUser() != null) {
                return authHelper.getCurrentUser().getUserId();
            }
        } catch (Exception e) {
            log.error("getCurrentUserId error: {}", e.getMessage());
        }
        return null;
    }

    /**
     * 得到当前用户 UserAccount 信息
     *
     * @return
     */
    public UserAccount getCurrentUserAccount() {
        UserAccount account = null;
        String userId = getCurrentUserId();
        if (StringUtils.isNotEmpty(userId)) {
            account = userCountDao.findTopByUserId(userId);
        }
        return account;
    }

    /**
     * 得到当前的Oid
     *
     * @return
     */
    public String getCurrentOid() {
        if (authHelper != null && authHelper.getCurrentUser() != null) {
            return authHelper.getOrgId();
        }
        return null;
    }

    public String getCurrentAppId() {
        return authClientSecurityAuthenticationHelper.getParameter(new String[]{"appId", "appid"});
    }

    /**
     * 得到当时设置到head的 项目oid
     *
     * @return
     */
    public String getCurrentProjectOid() {
        return authClientSecurityAuthenticationHelper.getParameter(new String[]{"projectoid", "projectOid"});
    }

    public String getHeadParam(String[] keys) {
        if (keys != null && keys.length > 0) {
            return authClientSecurityAuthenticationHelper.getParameter(keys);
        }
        return "";
    }

    /**
     * 初始Entity的默认参数 oid、createUser (oid为空会抛出异常)
     *
     * @param entity
     */
    public void initEntity(SuperMain entity) {
        if (entity != null) {
            String oid = entity.getOid();
            if (StringUtils.isEmpty(oid)) {
                entity.setOid(getCurrentOid());
            }
            Assert.hasText(entity.getOid(), "oid不能为空");
            try {
                UserAccount account = getCurrentUserAccount();
                if (account != null) {
                    if (StringUtils.isEmpty(entity.getCreateUserId())) {
                        entity.setCreateUserId(account.getUserId());
                        entity.setCreateUserName(account.getName());
                        entity.setCreatePhone(account.getPhone());
                    }
                    entity.setUpdateUserId(account.getUserId());
                    entity.setUpdateUserName(account.getName());
                    entity.setUpdatePhone(account.getPhone());
                }
            } catch (Exception e) {
                log.error("initEntity {}", e.getMessage());
            }
        }
    }

    /**
     * 编辑 entity 记录修改人的信息
     *
     * @param entity
     */
    public void initUpdateEntity(SuperMain entity) {
        if (entity != null) {
            try {
                UserAccount account = getCurrentUserAccount();
                if (account != null) {
                    entity.setUpdateUserId(account.getUserId());
                    entity.setUpdateUserName(account.getName());
                    entity.setUpdatePhone(account.getPhone());
                }
            } catch (Exception e) {
                log.error("initUpdateEntity {}", e.getMessage());
            }
        }
    }

    public void initEntityNoCheckOid(SuperMain entity) {
        if (entity != null) {
            String oid = entity.getOid();
            if (StringUtils.isEmpty(oid)) {
                entity.setOid(getCurrentOid());
            }
            if (StringUtils.isEmpty(entity.getId())) {
                entity.setId(null);
            }
            UserAccount account = getCurrentUserAccount();
            if (account != null) {
                if (StringUtils.isEmpty(entity.getCreateUserId())) {
                    entity.setCreateUserId(account.getUserId());
                    entity.setCreateUserName(account.getName());
                    entity.setCreatePhone(account.getPhone());
                }
                entity.setUpdateUserId(account.getUserId());
                entity.setUpdateUserName(account.getName());
                entity.setUpdatePhone(account.getPhone());
            }
        }
    }

    public void initEntityNoOid(SuperMain entity) {
        if (entity != null) {
            UserAccount account = getCurrentUserAccount();
            if (account != null) {
                if (StringUtils.isEmpty(entity.getCreateUserId())) {
                    entity.setCreateUserId(account.getUserId());
                    entity.setCreateUserName(account.getName());
                    entity.setCreatePhone(account.getPhone());
                }
                entity.setUpdateUserId(account.getUserId());
                entity.setUpdateUserName(account.getName());
                entity.setUpdatePhone(account.getPhone());
            }
        }
    }

    /**
     * 填充当前用户和oid信息 (oid为空会抛出异常)
     *
     * @param param
     */
    public void initDefaultUserAndOid(SuperParam param) {
        initDefaultUserParam(param);
        initOid(param);
        if (param.getId() != null && param.getId().trim().equals("")) {
            param.setId(null);
        }
    }

    public void initDefaultUserAndOidCheck(SuperParam param) {
        initDefaultUserParam(param);
        Assert.hasText(param.getOid(), "oid不能为空");
        if (param.getId() != null && param.getId().trim().equals("")) {
            param.setId(null);
        }
    }

    public void initDefaultUserAndOidNoExcept(SuperParam param) {
        initDefaultUserParam(param);
        String oid = param.getOid();
        if (StringUtils.isEmpty(oid)) {
            param.setOid(getCurrentOid());
        }
        if (param.getId() != null && param.getId().trim().equals("")) {
            param.setId(null);
        }
    }

    public void initDefaultUserParam(SuperParam param) {
        if (authHelper != null && authHelper.getCurrentUser() != null && StringUtils.isEmpty(param.getCreateUserId())) {
            param.setCreateUserId(authHelper.getCurrentUser().getUserId());
            param.setCreateUserName(authHelper.getCurrentUser().getUserName());
            param.setCreatePhone(authHelper.getCurrentUser().getPhone());
        }
    }

    public void initOid(SuperParam param) {
        String oid = param.getOid();
        if (StringUtils.isEmpty(oid)) {
            param.setOid(getCurrentOid());
        }
        Assert.hasText(param.getOid(), "oid不能为空");
    }

    /**
     * 初始填充搜索 oid times
     *
     * @param param
     */
    public void initOidSearchParam(SuperSearch param) {
        String oid = param.getOid();
        if (StringUtils.isEmpty(oid)) {
            param.setOid(getCurrentOid());
        }
        Assert.hasText(param.getOid(), "oid不能为空");
        initSearchParam(param);
    }

    public void initOidSearchParamNoCheckOid(SuperSearch param) {
        String oid = param.getOid();
        if (StringUtils.isEmpty(oid)) {
            param.setOid(getCurrentOid());
        }
        initSearchParam(param);
    }

    public void initSearchParamCheckOid(SuperSearch param) {
        String oid = param.getOid();
        Assert.hasText(oid, "oid不能为空");
        initSearchParam(param);
    }

    public void initSearchParam(SuperSearch param) {
        List<Long> times = param.getTimes();
        if (ObjectUtils.isNotEmpty(times) && times.size() == 2) {
            Long startTime = times.get(0);
            startTime = DateUtils.getDayStartTime(startTime);
            Long endTime = times.get(1);
            endTime = DateUtils.getDayEndTime(endTime);
            param.setStartTime(startTime);
            param.setEndTime(endTime);
        }
    }

    /**
     * 检查是否有 projectOid
     *
     * @param param
     */
    public void initSearchParamCheckProjectOid(SuperSearch param) {
        checkParamProjectOid(param);
        initSearchParam(param);
    }

    public void checkParamProjectOid(SuperSearch param) {
        Assert.hasText(param.getProjectOid(), "projectOid不能为空");
    }

    public void checkSaveParamProjectOid(SuperParam param) {
        Assert.hasText(param.getProjectOid(), "projectOid不能为空");
    }

    public void checkParamOid(SuperParam param) {
        Assert.hasText(param.getOid(), "oid不能为空");
    }

    public void checkParamOid(SuperSearch param) {
        Assert.hasText(param.getOid(), "oid不能为空");
    }

    public OperationLogsAddParam initLog(String userId) {
        return CommonUtil.initLog(request, userId);
    }

    /**
     * 根据结构code查询oid
     *
     * @param code
     * @return
     */
    public String getOidByCode(String code) {
        if (StringUtils.isNotEmpty(code)) {
            Organization organization = organizationDao.findTopByCode(code);
            if (ObjectUtils.isNotEmpty(organization)) {
                return organization.getOid();
            }
        }
        return "";
    }
}
