package org.qinan.safetyeval.app.executor;

import org.qinan.safetyeval.client.api.OrgInfoApi;
import org.qinan.safetyeval.client.dto.PageResponse;
import org.qinan.safetyeval.client.dto.SingleResponse;
import org.qinan.safetyeval.client.co.OrgInfoCO;
import org.qinan.safetyeval.client.dto.OrgInfoAddCmd;
import org.qinan.safetyeval.client.dto.OrgInfoModifyCmd;
import org.qinan.safetyeval.client.dto.OrgInfoPageQuery;
import org.qinan.safetyeval.client.dto.OrgInfoUpdateStateCmd;
import org.qinan.safetyeval.domain.entity.OrgInfoEntity;
import org.qinan.safetyeval.domain.exception.BizException;
import org.qinan.safetyeval.domain.exception.ErrorCode;
import org.qinan.safetyeval.domain.query.OrgInfoQuery;
import org.qinan.safetyeval.domain.query.PageResult;
import org.qinan.safetyeval.domain.service.OrgInfoDomainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 机构信息执行器（App层）
 *
 * @author safety-eval
 */
@Service
public class OrgInfoExecutor implements OrgInfoApi {

    @Lazy
    @Autowired(required = false)
    private OrgInfoDomainService orgInfoDomainService;

    @Override
    public SingleResponse<OrgInfoCO> add(OrgInfoAddCmd cmd) {
        OrgInfoEntity entity = new OrgInfoEntity();
        entity.setUnitName(cmd.getUnitName());
        entity.setCreditCode(cmd.getCreditCode());
        entity.setSafetyIndustryCategoryCode(cmd.getSafetyIndustryCategoryCode());
        entity.setSafetyIndustryCategoryName(cmd.getSafetyIndustryCategoryName());
        entity.setDistrictCode(cmd.getDistrictCode());
        entity.setDistrictName(cmd.getDistrictName());
        entity.setTownStreet(cmd.getTownStreet());
        entity.setVillageCommunity(cmd.getVillageCommunity());
        entity.setLongitude(cmd.getLongitude());
        entity.setLatitude(cmd.getLatitude());
        entity.setRegisterAddress(cmd.getRegisterAddress());
        entity.setBusinessAddress(cmd.getBusinessAddress());
        entity.setOwnershipTypeCode(cmd.getOwnershipTypeCode());
        entity.setOwnershipTypeName(cmd.getOwnershipTypeName());
        entity.setLegalRepresentative(cmd.getLegalRepresentative());
        entity.setLegalRepresentativePhone(cmd.getLegalRepresentativePhone());
        entity.setPrincipalName(cmd.getPrincipalName());
        entity.setPrincipalPhone(cmd.getPrincipalPhone());
        entity.setSafetyDeptManager(cmd.getSafetyDeptManager());
        entity.setSafetyDeptManagerPhone(cmd.getSafetyDeptManagerPhone());
        entity.setSafetyDeputyPhone(cmd.getSafetyDeputyPhone());
        entity.setProductionDate(cmd.getProductionDate());
        entity.setBusinessStatusCode(cmd.getBusinessStatusCode());
        entity.setBusinessStatusName(cmd.getBusinessStatusName());
        entity.setInfoDisclosureUrl(cmd.getInfoDisclosureUrl());
        entity.setWorkplaceArea(cmd.getWorkplaceArea());
        entity.setArchiveRoomArea(cmd.getArchiveRoomArea());
        entity.setFulltimeEvaluatorCount(cmd.getFulltimeEvaluatorCount());
        entity.setRegisteredEngineerCount(cmd.getRegisteredEngineerCount());
        entity.setEconomyIndustryCode(cmd.getEconomyIndustryCode());
        entity.setEconomyIndustryName(cmd.getEconomyIndustryName());
        entity.setAuthStatusCode(cmd.getAuthStatusCode());
        entity.setAuthStatusName(cmd.getAuthStatusName());
        entity.setEnterpriseStatusCode(cmd.getEnterpriseStatusCode());
        entity.setEnterpriseStatusName(cmd.getEnterpriseStatusName());
        entity.setEnterpriseScaleCode(cmd.getEnterpriseScaleCode());
        entity.setEnterpriseScaleName(cmd.getEnterpriseScaleName());
        entity.setFilingTypeCode(cmd.getFilingTypeCode());
        entity.setFilingTypeName(cmd.getFilingTypeName());
        entity.setFilingRecordStatusCode(cmd.getFilingRecordStatusCode());
        entity.setFilingRecordStatusName(cmd.getFilingRecordStatusName());
        entity.setAttachmentUrls(cmd.getAttachmentUrls());

        OrgInfoEntity result = orgInfoDomainService.add(entity);
        return SingleResponse.success(toCO(result));
    }

    @Override
    public SingleResponse<OrgInfoCO> get(Long id) {
        OrgInfoEntity entity = orgInfoDomainService.get(id);
        return SingleResponse.success(toCO(entity));
    }

    @Override
    public SingleResponse<OrgInfoCO> modify(OrgInfoModifyCmd cmd) {
        OrgInfoEntity entity = new OrgInfoEntity();
        entity.setId(cmd.getId());
        entity.setUnitName(cmd.getUnitName());
        entity.setCreditCode(cmd.getCreditCode());
        entity.setSafetyIndustryCategoryCode(cmd.getSafetyIndustryCategoryCode());
        entity.setSafetyIndustryCategoryName(cmd.getSafetyIndustryCategoryName());
        entity.setDistrictCode(cmd.getDistrictCode());
        entity.setDistrictName(cmd.getDistrictName());
        entity.setTownStreet(cmd.getTownStreet());
        entity.setVillageCommunity(cmd.getVillageCommunity());
        entity.setLongitude(cmd.getLongitude());
        entity.setLatitude(cmd.getLatitude());
        entity.setRegisterAddress(cmd.getRegisterAddress());
        entity.setBusinessAddress(cmd.getBusinessAddress());
        entity.setOwnershipTypeCode(cmd.getOwnershipTypeCode());
        entity.setOwnershipTypeName(cmd.getOwnershipTypeName());
        entity.setLegalRepresentative(cmd.getLegalRepresentative());
        entity.setLegalRepresentativePhone(cmd.getLegalRepresentativePhone());
        entity.setPrincipalName(cmd.getPrincipalName());
        entity.setPrincipalPhone(cmd.getPrincipalPhone());
        entity.setSafetyDeptManager(cmd.getSafetyDeptManager());
        entity.setSafetyDeptManagerPhone(cmd.getSafetyDeptManagerPhone());
        entity.setSafetyDeputyPhone(cmd.getSafetyDeputyPhone());
        entity.setProductionDate(cmd.getProductionDate());
        entity.setBusinessStatusCode(cmd.getBusinessStatusCode());
        entity.setBusinessStatusName(cmd.getBusinessStatusName());
        entity.setInfoDisclosureUrl(cmd.getInfoDisclosureUrl());
        entity.setWorkplaceArea(cmd.getWorkplaceArea());
        entity.setArchiveRoomArea(cmd.getArchiveRoomArea());
        entity.setFulltimeEvaluatorCount(cmd.getFulltimeEvaluatorCount());
        entity.setRegisteredEngineerCount(cmd.getRegisteredEngineerCount());
        entity.setEconomyIndustryCode(cmd.getEconomyIndustryCode());
        entity.setEconomyIndustryName(cmd.getEconomyIndustryName());
        entity.setAuthStatusCode(cmd.getAuthStatusCode());
        entity.setAuthStatusName(cmd.getAuthStatusName());
        entity.setEnterpriseStatusCode(cmd.getEnterpriseStatusCode());
        entity.setEnterpriseStatusName(cmd.getEnterpriseStatusName());
        entity.setEnterpriseScaleCode(cmd.getEnterpriseScaleCode());
        entity.setEnterpriseScaleName(cmd.getEnterpriseScaleName());
        entity.setFilingTypeCode(cmd.getFilingTypeCode());
        entity.setFilingTypeName(cmd.getFilingTypeName());
        entity.setFilingRecordStatusCode(cmd.getFilingRecordStatusCode());
        entity.setFilingRecordStatusName(cmd.getFilingRecordStatusName());
        entity.setAttachmentUrls(cmd.getAttachmentUrls());

        OrgInfoEntity result = orgInfoDomainService.modify(entity);
        return SingleResponse.success(toCO(result));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SingleResponse<Void> delete(Long id) {
        orgInfoDomainService.delete(id);
        return SingleResponse.success();
    }

    @Override
    public SingleResponse<Void> updateState(OrgInfoUpdateStateCmd cmd) {
        orgInfoDomainService.updateState(cmd.getId(), cmd.getState());
        return SingleResponse.success();
    }

    @Override
    public SingleResponse<Void> resetPassword(Long id) {
        OrgInfoEntity entity = orgInfoDomainService.get(id);
        if (entity == null) {
            throw new BizException(ErrorCode.ORG_INFO_NOT_FOUND);
        }
        // 联调阶段：密码重置占位，后续对接统一用户中心
        orgInfoDomainService.resetPassword(entity.getCreateId());
        return SingleResponse.success();
    }

    @Override
    public PageResponse<OrgInfoCO> page(OrgInfoPageQuery query) {
        OrgInfoQuery domainQuery = new OrgInfoQuery();
        domainQuery.setPageNum(query.getCurrent());
        domainQuery.setPageSize(query.getSize());
        domainQuery.setUnitName(query.getUnitName());
        domainQuery.setCreditCode(query.getCreditCode());
        domainQuery.setAuthStatusCode(query.getAuthStatusCode());
        // 管理员可跨租户查询机构信息，此处保留前端传入的tenantId
        domainQuery.setTenantId(query.getTenantId());
        domainQuery.setDistrictName(query.getDistrictName());
        domainQuery.setState(query.getState());
        domainQuery.setCreateTimeStart(query.getCreateTimeStart());
        domainQuery.setCreateTimeEnd(query.getCreateTimeEnd());
        domainQuery.setRegisterAddress(query.getRegisterAddress());
        domainQuery.setFilingTypeCode(query.getFilingTypeCode());
        domainQuery.setFilingRecordStatusCode(query.getFilingRecordStatusCode());

        PageResult<OrgInfoEntity> pageResult = orgInfoDomainService.page(domainQuery);

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

    @Override
    public SingleResponse<OrgInfoCO> getInfo() {
        OrgInfoEntity entity = orgInfoDomainService.getInfo();
        return SingleResponse.success(toCO(entity));
    }

    private OrgInfoCO toCO(OrgInfoEntity entity) {
        if (entity == null) {
            return null;
        }
        OrgInfoCO co = new OrgInfoCO();
        co.setId(entity.getId());
        co.setUnitName(entity.getUnitName());
        co.setCreditCode(entity.getCreditCode());
        co.setSafetyIndustryCategoryCode(entity.getSafetyIndustryCategoryCode());
        co.setSafetyIndustryCategoryName(entity.getSafetyIndustryCategoryName());
        co.setDistrictCode(entity.getDistrictCode());
        co.setDistrictName(entity.getDistrictName());
        co.setTownStreet(entity.getTownStreet());
        co.setVillageCommunity(entity.getVillageCommunity());
        co.setLongitude(entity.getLongitude());
        co.setLatitude(entity.getLatitude());
        co.setRegisterAddress(entity.getRegisterAddress());
        co.setBusinessAddress(entity.getBusinessAddress());
        co.setOwnershipTypeCode(entity.getOwnershipTypeCode());
        co.setOwnershipTypeName(entity.getOwnershipTypeName());
        co.setLegalRepresentative(entity.getLegalRepresentative());
        co.setLegalRepresentativePhone(entity.getLegalRepresentativePhone());
        co.setPrincipalName(entity.getPrincipalName());
        co.setPrincipalPhone(entity.getPrincipalPhone());
        co.setSafetyDeptManager(entity.getSafetyDeptManager());
        co.setSafetyDeptManagerPhone(entity.getSafetyDeptManagerPhone());
        co.setSafetyDeputyPhone(entity.getSafetyDeputyPhone());
        co.setProductionDate(entity.getProductionDate());
        co.setBusinessStatusCode(entity.getBusinessStatusCode());
        co.setBusinessStatusName(entity.getBusinessStatusName());
        co.setInfoDisclosureUrl(entity.getInfoDisclosureUrl());
        co.setWorkplaceArea(entity.getWorkplaceArea());
        co.setArchiveRoomArea(entity.getArchiveRoomArea());
        co.setFulltimeEvaluatorCount(entity.getFulltimeEvaluatorCount());
        co.setRegisteredEngineerCount(entity.getRegisteredEngineerCount());
        co.setEconomyIndustryCode(entity.getEconomyIndustryCode());
        co.setEconomyIndustryName(entity.getEconomyIndustryName());
        co.setAuthStatusCode(entity.getAuthStatusCode());
        co.setAuthStatusName(entity.getAuthStatusName());
        co.setEnterpriseStatusCode(entity.getEnterpriseStatusCode());
        co.setEnterpriseStatusName(entity.getEnterpriseStatusName());
        co.setEnterpriseScaleCode(entity.getEnterpriseScaleCode());
        co.setEnterpriseScaleName(entity.getEnterpriseScaleName());
        co.setFilingTypeCode(entity.getFilingTypeCode());
        co.setFilingTypeName(entity.getFilingTypeName());
        co.setFilingRecordStatusCode(entity.getFilingRecordStatusCode());
        co.setFilingRecordStatusName(entity.getFilingRecordStatusName());
        co.setAttachmentUrls(entity.getAttachmentUrls());
        co.setState(entity.getState());
        co.setTenantId(entity.getTenantId());
        co.setCreateTime(entity.getCreateTime());
        return co;
    }
}
