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

import com.zcloud.personnel.positioning.command.convertor.AreaCoConvertor;
import com.zcloud.personnel.positioning.dto.AreaPageQry;
import com.zcloud.personnel.positioning.dto.clientobject.AreaCO;
import com.zcloud.personnel.positioning.dto.clientobject.OptionCO;
import com.zcloud.personnel.positioning.persistence.dataobject.AreaDO;
import com.zcloud.personnel.positioning.persistence.repository.AreaRepository;
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 lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * web-app
 *
 * @Author fangjiakai
 * @Date 2026-07-07
 */
@Component
@AllArgsConstructor
public class AreaQueryExe {
    private final AreaRepository areaRepository;
    private final AreaCoConvertor areaCoConvertor;

    public PageResponse<AreaCO> execute(AreaPageQry qry) {
        AreaPageQry query = qry == null ? new AreaPageQry() : qry;
        Map<String, Object> params = query.toHashMap();
        fillCorpinfo(params);
        PageResponse<AreaDO> pageResponse = areaRepository.listPage(params);
        List<AreaCO> data = areaCoConvertor.converDOsToCOs(pageResponse.getData());
        return PageResponse.of(data, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public List<AreaCO> listAll() {
        QueryWrapper<AreaDO> queryWrapper = new QueryWrapper<>();
        applyCorpinfo(queryWrapper, null);
        queryWrapper.orderByDesc("create_time");
        return areaCoConvertor.converDOsToCOs(areaRepository.list(queryWrapper));
    }

    public List<OptionCO> listOptions(Long corpinfoId, String keyword) {
        QueryWrapper<AreaDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper.isNull("delete_enum").or().eq("delete_enum", "FALSE"));
        queryWrapper.and(wrapper -> wrapper.isNull("status").or().eq("status", "ENABLED"));
        queryWrapper.in("area_type", "COMPANY_AREA", "WORK_AREA", "BUFFER");
        applyCorpinfo(queryWrapper, corpinfoId);
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like("area_name", keyword.trim());
        }
        queryWrapper.orderByAsc("sort_no").orderByAsc("area_name");

        List<AreaDO> areas = areaRepository.list(queryWrapper);
        List<OptionCO> options = new ArrayList<>(areas.size());
        for (AreaDO area : areas) {
            options.add(new OptionCO(area.getAreaName(), String.valueOf(area.getId())));
        }
        return options;
    }

    public AreaCO queryById(Long id) {
        QueryWrapper<AreaDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        applyCorpinfo(queryWrapper, null);
        AreaDO dataObject = areaRepository.getOne(queryWrapper, false);
        return areaCoConvertor.converDOToCO(dataObject);
    }

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

    private void applyCorpinfo(QueryWrapper<AreaDO> queryWrapper, Long corpinfoId) {
        if (corpinfoId != null) {
            queryWrapper.eq("corpinfo_id", corpinfoId);
            return;
        }
        SSOUser ssoUser = AuthContext.getCurrentUser();
        if (ssoUser != null && ssoUser.getCompanyId() != null) {
            queryWrapper.eq("corpinfo_id", ssoUser.getCompanyId());
        }
    }
}
