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.TerminalCardCoConvertor;
import com.zcloud.personnel.positioning.dto.TerminalCardCompanyOptionQry;
import com.zcloud.personnel.positioning.dto.TerminalCardCompanyPageQry;
import com.zcloud.personnel.positioning.dto.TerminalCardPageQry;
import com.zcloud.personnel.positioning.dto.TerminalCardPersonOptionQry;
import com.zcloud.personnel.positioning.dto.clientobject.TerminalCardCO;
import com.zcloud.personnel.positioning.dto.clientobject.TerminalCardCompanyCO;
import com.zcloud.personnel.positioning.dto.clientobject.TerminalCardCompanyOptionCO;
import com.zcloud.personnel.positioning.dto.clientobject.TerminalCardPersonOptionCO;
import com.zcloud.personnel.positioning.persistence.dataobject.TerminalCardCompanyStatDO;
import com.zcloud.personnel.positioning.persistence.dataobject.TerminalCardDetailDO;
import com.zcloud.personnel.positioning.persistence.dataobject.TerminalCardPersonOptionDO;
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.List;
import java.util.Map;

@Component
@AllArgsConstructor
public class TerminalCardQueryExe {
    private final TerminalRepository terminalRepository;
    private final TerminalCardCoConvertor terminalCardCoConvertor;

    public PageResponse<TerminalCardCompanyCO> listCompanyPage(TerminalCardCompanyPageQry qry) {
        TerminalCardCompanyPageQry query = qry == null ? new TerminalCardCompanyPageQry() : 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<TerminalCardCompanyStatDO> page = terminalRepository.listCardCompanyStats(params);
        return PageResponse.of(terminalCardCoConvertor.convertCompanyStats(page.getData()),
                page.getTotalCount(), page.getPageSize(), page.getPageIndex());
    }

    public PageResponse<TerminalCardCO> listCardPage(TerminalCardPageQry qry) {
        TerminalCardPageQry query = qry == null ? new TerminalCardPageQry() : qry;
        Map<String, Object> params = PageQueryHelper.toHashMap(query);
        trim(params, "terminalNo", "staffName", "staffNo", "idCardNo", "eqCorpinfoId",
                "eqCorpinfoName", "likeCorpinfoName", "orgCode", "orgName", "deviceStatus");
        applyCurrentCompany(params, "eqCorpinfoId", "eqCorpinfoName", "likeCorpinfoName");
        PageResponse<TerminalCardDetailDO> page = terminalRepository.listCards(params);
        return PageResponse.of(terminalCardCoConvertor.convertCards(page.getData()),
                page.getTotalCount(), page.getPageSize(), page.getPageIndex());
    }

    public TerminalCardCO queryCardById(Long id) {
        if (id == null) {
            throw new BizException("Terminal card id is required");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        TerminalCardDetailDO dataObject = terminalRepository.getCardDetail(params);
        return terminalCardCoConvertor.convertCard(dataObject);
    }

    public PageResponse<TerminalCardPersonOptionCO> listPersonOptions(TerminalCardPersonOptionQry qry) {
        TerminalCardPersonOptionQry query = qry == null ? new TerminalCardPersonOptionQry() : qry;
        Map<String, Object> params = PageQueryHelper.toHashMap(query);
        trim(params, "keyword", "staffName", "staffNo", "idCardNo", "corpinfoId", "corpinfoName");
        applyCurrentCompany(params, "corpinfoId");
        PageResponse<TerminalCardPersonOptionDO> page = terminalRepository.listCardPersonOptions(params);
        return PageResponse.of(terminalCardCoConvertor.convertPersonOptions(page.getData()),
                page.getTotalCount(), page.getPageSize(), page.getPageIndex());
    }

    public List<TerminalCardCompanyOptionCO> listCompanyOptions(TerminalCardCompanyOptionQry qry) {
        Map<String, Object> params = new HashMap<>();
        if (qry != null && StringUtils.hasText(qry.getKeyword())) {
            params.put("keyword", qry.getKeyword().trim());
        }
        return terminalCardCoConvertor.convertCompanyOptions(terminalRepository.listCardCompanyOptions(params));
    }

    private void applyCurrentCompany(Map<String, Object> params, String... explicitKeys) {
        for (String key : explicitKeys) {
            Object value = params.get(key);
            if (value != null && (!(value instanceof String) || StringUtils.hasText((String) value))) {
                return;
            }
        }
        SSOUser user = AuthContext.getCurrentUser();
        if (user != null && user.getCompanyId() != null) {
            params.put(explicitKeys[0], String.valueOf(user.getCompanyId()));
        }
    }

    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;
    }
}
