package org.qinan.safetyeval.app.executor;

import org.apache.commons.lang3.StringUtils;
import org.qinan.safetyeval.client.api.OrgQualificationApi;
import org.qinan.safetyeval.client.dto.PageResponse;
import org.qinan.safetyeval.client.dto.SingleResponse;
import org.qinan.safetyeval.client.co.OrgQualificationCO;
import org.qinan.safetyeval.client.dto.OrgQualificationAddCmd;
import org.qinan.safetyeval.client.dto.OrgQualificationModifyCmd;
import org.qinan.safetyeval.client.dto.OrgQualificationPageQuery;
import org.qinan.safetyeval.domain.entity.OrgQualificationEntity;
import org.qinan.safetyeval.domain.query.OrgQualificationQuery;
import org.qinan.safetyeval.domain.query.PageResult;
import org.qinan.safetyeval.domain.service.OrgQualificationDomainService;
import org.qinan.safetyeval.infrastructure.adapter.auth.AuthUserContextAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 机构资质证书执行器（App层）
 *
 * @author safety-eval
 */
@Service
public class OrgQualificationExecutor implements OrgQualificationApi {

    @Lazy
    @Autowired(required = false)
    private OrgQualificationDomainService orgQualificationDomainService;

    @Override
    public SingleResponse<OrgQualificationCO> add(OrgQualificationAddCmd cmd) {
        OrgQualificationEntity entity = new OrgQualificationEntity();
        entity.setLicenseTypeCode(cmd.getLicenseTypeCode());
        entity.setLicenseTypeName(cmd.getLicenseTypeName());
        entity.setCertName(cmd.getCertName());
        entity.setCertNo(cmd.getCertNo());
        entity.setIssueDate(cmd.getIssueDate());
        entity.setIssueOrg(cmd.getIssueOrg());
        entity.setValidStartDate(cmd.getValidStartDate());
        entity.setValidEndDate(cmd.getValidEndDate());
        entity.setCertImageUrl(cmd.getCertImageUrl());
        entity.setEnableFlag(cmd.getEnableFlag());
        entity.setRemark(cmd.getRemark());

        OrgQualificationEntity result = orgQualificationDomainService.add(entity);
        return SingleResponse.success(toCO(result));
    }

    @Override
    public SingleResponse<OrgQualificationCO> get(Long id) {
        OrgQualificationEntity entity = orgQualificationDomainService.get(id);
        return SingleResponse.success(toCO(entity));
    }

    @Override
    public SingleResponse<OrgQualificationCO> modify(OrgQualificationModifyCmd cmd) {
        OrgQualificationEntity entity = new OrgQualificationEntity();
        entity.setId(cmd.getId());
        entity.setLicenseTypeCode(cmd.getLicenseTypeCode());
        entity.setLicenseTypeName(cmd.getLicenseTypeName());
        entity.setCertName(cmd.getCertName());
        entity.setCertNo(cmd.getCertNo());
        entity.setIssueDate(cmd.getIssueDate());
        entity.setIssueOrg(cmd.getIssueOrg());
        entity.setValidStartDate(cmd.getValidStartDate());
        entity.setValidEndDate(cmd.getValidEndDate());
        entity.setCertImageUrl(cmd.getCertImageUrl());
        entity.setEnableFlag(cmd.getEnableFlag());
        entity.setRemark(cmd.getRemark());

        OrgQualificationEntity result = orgQualificationDomainService.modify(entity);
        return SingleResponse.success(toCO(result));
    }

    @Override
    public SingleResponse<Void> delete(Long id) {
        orgQualificationDomainService.delete(id);
        return SingleResponse.success();
    }

    @Override
    public PageResponse<OrgQualificationCO> page(OrgQualificationPageQuery query) {
        OrgQualificationQuery domainQuery = new OrgQualificationQuery();
        domainQuery.setPageNum(query.getCurrent());
        domainQuery.setPageSize(query.getSize());
        domainQuery.setTenantId(AuthUserContextAdapter.getCurrentTenantId());
        domainQuery.setOrgId(query.getOrgId());
        domainQuery.setCertName(query.getCertName());
        domainQuery.setCertNo(query.getCertNo());
        domainQuery.setEnableFlag(query.getEnableFlag());

        PageResult<OrgQualificationEntity> pageResult = orgQualificationDomainService.page(domainQuery);

        return PageResponse.of(
                pageResult.getRecords().stream()
                        .map(this::toCO)
                        .collect(java.util.stream.Collectors.toList()),
                pageResult.getTotal());
    }

    @Override
    public SingleResponse<Map<String, List<OrgQualificationCO>>> classGet(Long id) {
        List<OrgQualificationEntity> list = orgQualificationDomainService.classGet(id);
        return SingleResponse.success(list.stream()
                .map(this::toCO)
                .collect(Collectors.groupingBy(this::resolveLicenseGroupKey, Collectors.toList())));
    }

    /** licenseTypeCode 可能为空（如营业执照），分组键回退到 licenseTypeName */
    private String resolveLicenseGroupKey(OrgQualificationCO co) {
        if (StringUtils.isNotBlank(co.getLicenseTypeCode())) {
            return co.getLicenseTypeCode();
        }
        if (StringUtils.isNotBlank(co.getLicenseTypeName())) {
            return co.getLicenseTypeName();
        }
        return "default";
    }

    private OrgQualificationCO toCO(OrgQualificationEntity entity) {
        if (entity == null) {
            return null;
        }
        OrgQualificationCO co = new OrgQualificationCO();
        co.setId(entity.getId());
        co.setLicenseTypeCode(entity.getLicenseTypeCode());
        co.setLicenseTypeName(entity.getLicenseTypeName());
        co.setCertName(entity.getCertName());
        co.setCertNo(entity.getCertNo());
        co.setIssueDate(entity.getIssueDate());
        co.setIssueOrg(entity.getIssueOrg());
        co.setValidStartDate(entity.getValidStartDate());
        co.setValidEndDate(entity.getValidEndDate());
        co.setCertImageUrl(entity.getCertImageUrl());
        co.setEnableFlag(entity.getEnableFlag());
        co.setRemark(entity.getRemark());
        co.setTenantId(entity.getTenantId());
        return co;
    }
}
