package com.zcloud.personnel.positioning.command.query;

import com.alibaba.cola.dto.PageResponse;
import com.alibaba.cola.exception.BizException;
import com.jjb.saas.framework.auth.model.SSOUser;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.zcloud.gbscommon.utils.PageQueryHelper;
import com.zcloud.personnel.positioning.command.convertor.TerminalAppCoConvertor;
import com.zcloud.personnel.positioning.dto.TerminalAppCompanyPageQry;
import com.zcloud.personnel.positioning.dto.TerminalAppPageQry;
import com.zcloud.personnel.positioning.dto.clientobject.TerminalAppCO;
import com.zcloud.personnel.positioning.dto.clientobject.TerminalAppCompanyCO;
import com.zcloud.personnel.positioning.persistence.dataobject.TerminalAppCompanyStatDO;
import com.zcloud.personnel.positioning.persistence.dataobject.TerminalAppDetailDO;
import com.zcloud.personnel.positioning.persistence.repository.TerminalRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Component
@AllArgsConstructor
public class TerminalAppQueryExe {
    private final TerminalRepository terminalRepository;
    private final TerminalAppCoConvertor terminalAppCoConvertor;

    public PageResponse<TerminalAppCompanyCO> listCompanyPage(TerminalAppCompanyPageQry qry) {
        TerminalAppCompanyPageQry query = qry == null ? new TerminalAppCompanyPageQry() : qry;
        Map<String, Object> params = PageQueryHelper.toHashMap(query);
        trim(params, "eqCorpinfoId", "likeCorpinfoName", "likeContactName");
        if (query.getEqEnable() == null) {
            Integer enable = normalizeEnable(query.getStatus());
            if (enable != null) {
                params.put("eqEnable", enable);
            }
        }
        PageResponse<TerminalAppCompanyStatDO> page = terminalRepository.listAppCompanyStats(params);
        return PageResponse.of(terminalAppCoConvertor.convertCompanyStats(page.getData()),
                page.getTotalCount(), page.getPageSize(), page.getPageIndex());
    }

    public PageResponse<TerminalAppCO> listAppPage(TerminalAppPageQry qry) {
        TerminalAppPageQry query = qry == null ? new TerminalAppPageQry() : qry;
        Map<String, Object> params = PageQueryHelper.toHashMap(query);
        trim(params, "appAccount", "terminalNo", "staffName", "staffNo", "idCardNo",
                "eqCorpinfoId", "eqCorpinfoName", "likeCorpinfoName", "orgCode", "orgName", "deviceStatus");
        applyCurrentCompany(params);
        PageResponse<TerminalAppDetailDO> page = terminalRepository.listApps(params);
        return PageResponse.of(terminalAppCoConvertor.convertApps(page.getData()),
                page.getTotalCount(), page.getPageSize(), page.getPageIndex());
    }

    public TerminalAppCO queryAppById(Long id) {
        if (id == null) {
            throw new BizException("APP terminal id is required");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        return terminalAppCoConvertor.convertApp(terminalRepository.getAppDetail(params));
    }

    private void applyCurrentCompany(Map<String, Object> params) {
        if (hasText(params, "eqCorpinfoId") || hasText(params, "eqCorpinfoName")
                || hasText(params, "likeCorpinfoName")) {
            return;
        }
        SSOUser user = AuthContext.getCurrentUser();
        if (user != null && user.getCompanyId() != null) {
            params.put("eqCorpinfoId", String.valueOf(user.getCompanyId()));
        }
    }

    private boolean hasText(Map<String, Object> params, String key) {
        Object value = params.get(key);
        return value != null && (!(value instanceof String) || StringUtils.hasText((String) value));
    }

    private void trim(Map<String, Object> params, String... keys) {
        for (String key : keys) {
            Object value = params.get(key);
            if (value instanceof String) {
                String text = ((String) value).trim();
                if (text.isEmpty()) {
                    params.remove(key);
                } else {
                    params.put(key, text);
                }
            }
        }
    }

    private Integer normalizeEnable(String status) {
        if (!StringUtils.hasText(status)) {
            return null;
        }
        String value = status.trim().toLowerCase();
        if ("1".equals(value) || "enabled".equals(value) || "enable".equals(value)
                || "启用".equals(status.trim())) {
            return 1;
        }
        if ("0".equals(value) || "disabled".equals(value) || "disable".equals(value)
                || "停用".equals(status.trim())) {
            return 0;
        }
        return null;
    }
}
