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

import com.alibaba.cola.dto.PageResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.AlarmRuleConfigPersistence;
import com.zcloud.personnel.positioning.command.FencePersistenceSupport;
import com.zcloud.personnel.positioning.command.convertor.FenceCoConvertor;
import com.zcloud.personnel.positioning.dto.FenceCompanyPageQry;
import com.zcloud.personnel.positioning.dto.FencePageQry;
import com.zcloud.personnel.positioning.dto.clientobject.FenceCO;
import com.zcloud.personnel.positioning.dto.clientobject.FenceCompanyStatCO;
import com.zcloud.personnel.positioning.dto.clientobject.OptionCO;
import com.zcloud.personnel.positioning.persistence.dataobject.CompanyOptionDO;
import com.zcloud.personnel.positioning.persistence.dataobject.FenceDO;
import com.zcloud.personnel.positioning.persistence.dataobject.FenceCompanyStatDO;
import com.zcloud.personnel.positioning.persistence.repository.FenceRepository;
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 FenceQueryExe {
    private final FenceRepository fenceRepository;
    private final FenceCoConvertor fenceCoConvertor;

    public List<OptionCO> listCompanyOptions(String keyword) {
        Map<String, Object> params = new HashMap<>();
        SSOUser ssoUser = AuthContext.getCurrentUser();
        if (ssoUser != null && ssoUser.getCompanyId() != null) {
            params.put("eqCorpinfoId", String.valueOf(ssoUser.getCompanyId()));
        }
        if (StringUtils.hasText(keyword)) {
            params.put("keyword", keyword.trim());
        }
        List<CompanyOptionDO> dataObjects = fenceRepository.listCompanyOptions(params);
        return fenceCoConvertor.converCompanyOptionDOsToCOs(dataObjects);
    }

    public PageResponse<FenceCompanyStatCO> listCompanyStats(FenceCompanyPageQry qry) {
        FenceCompanyPageQry query = qry == null ? new FenceCompanyPageQry() : qry;
        Map<String, Object> params = PageQueryHelper.toHashMap(query);
        PageResponse<FenceCompanyStatDO> pageResponse = fenceRepository.listCompanyStats(params);
        List<FenceCompanyStatCO> data = fenceCoConvertor.converCompanyStatDOsToCOs(pageResponse.getData());
        return PageResponse.of(data, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public PageResponse<FenceCO> execute(FencePageQry qry) {
        FencePageQry query = qry == null ? new FencePageQry() : qry;
        Map<String, Object> params = PageQueryHelper.toHashMap(query);
        params.put("eqDeleteEnum", "FALSE");
        if (!StringUtils.hasText((String) params.get("eqFenceScope"))) {
            params.put("electronicFenceOnly", Boolean.TRUE);
        }
        normalizeListParams(params);
        fillCorpinfo(params);
        preferCorpinfoId(params);
        PageResponse<FenceDO> pageResponse = fenceRepository.listPage(params);
        List<FenceCO> data = fenceCoConvertor.converDOsToCOs(pageResponse.getData());
        return PageResponse.of(data, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public List<FenceCO> listAll() {
        QueryWrapper<FenceDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_enum", "FALSE");
        queryWrapper.ne("fence_scope", FencePersistenceSupport.SCOPE_COMPANY_AREA);
        applyCorpinfo(queryWrapper);
        queryWrapper.orderByDesc("create_time");
        return fenceCoConvertor.converDOsToCOs(fenceRepository.list(queryWrapper));
    }

    public FenceCO queryById(Long id) {
        QueryWrapper<FenceDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("delete_enum", "FALSE");
        FenceDO dataObject = fenceRepository.getOne(queryWrapper, false);
        return fenceCoConvertor.converDOToCO(dataObject);
    }

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

    private void preferCorpinfoId(Map<String, Object> params) {
        String corpinfoId = (String) params.get("eqCorpinfoId");
        if (!StringUtils.hasText(corpinfoId)) {
            return;
        }
        params.remove("eqCorpinfoName");
    }

    private void applyCorpinfo(QueryWrapper<FenceDO> queryWrapper) {
        SSOUser ssoUser = AuthContext.getCurrentUser();
        if (ssoUser != null && ssoUser.getCompanyId() != null) {
            queryWrapper.eq("corpinfo_id", String.valueOf(ssoUser.getCompanyId()));
        }
    }

    private void normalizeListParams(Map<String, Object> params) {
        String status = normalizeStatus((String) params.get("eqStatus"));
        if (StringUtils.hasText(status)) {
            params.put("eqStatus", status);
        }
    }

    private String normalizeStatus(String status) {
        if (!StringUtils.hasText(status)) {
            return null;
        }
        String value = status.trim();
        if ("1".equals(value) || "\u542f\u7528".equals(value)) {
            return AlarmRuleConfigPersistence.STATUS_ENABLED;
        }
        if ("0".equals(value) || "\u505c\u7528".equals(value)) {
            return AlarmRuleConfigPersistence.STATUS_DISABLED;
        }
        return value;
    }

}
