import { DataSource, Repository } from 'typeorm';
import { DisabledPerson } from '../entities/disabled-person.entity';
import { DisabledBankCard } from '../entities/disabled-bank-card.entity';
import { DisabledPhoto } from '../entities/disabled-photo.entity';
import { DisabledRemark } from '../entities/disabled-remark.entity';
import { DisabledVisit } from '../entities/disabled-visit.entity';
import { File } from '@d8d/file-module';
import { DisabledPersonService } from './disabled-person.service';

export class AggregatedService {
  private readonly personRepository: Repository<DisabledPerson>;
  private readonly bankCardRepository: Repository<DisabledBankCard>;
  private readonly photoRepository: Repository<DisabledPhoto>;
  private readonly remarkRepository: Repository<DisabledRemark>;
  private readonly visitRepository: Repository<DisabledVisit>;
  private readonly fileRepository: Repository<File>;
  private readonly disabledPersonService: DisabledPersonService;

  constructor(dataSource: DataSource) {
    this.personRepository = dataSource.getRepository(DisabledPerson);
    this.bankCardRepository = dataSource.getRepository(DisabledBankCard);
    this.photoRepository = dataSource.getRepository(DisabledPhoto);
    this.remarkRepository = dataSource.getRepository(DisabledRemark);
    this.visitRepository = dataSource.getRepository(DisabledVisit);
    this.fileRepository = dataSource.getRepository(File);
    this.disabledPersonService = new DisabledPersonService(dataSource);
  }

  /**
   * 聚合创建残疾人所有信息
   */
  async createDisabledPersonWithAllData(data: {
    personInfo: Partial<DisabledPerson>;
    bankCards?: Partial<DisabledBankCard>[];
    photos?: Partial<DisabledPhoto>[];
    remarks?: Partial<DisabledRemark>[];
    visits?: Partial<DisabledVisit>[];
  }): Promise<{
    personInfo: DisabledPerson;
    bankCards: DisabledBankCard[];
    photos: DisabledPhoto[];
    remarks: DisabledRemark[];
    visits: DisabledVisit[];
    message: string;
    success: boolean;
  }> {
    const { personInfo, bankCards = [], photos = [], remarks = [], visits = [] } = data;

    // 检查身份证号是否已存在
    if (personInfo.idCard) {
      const existingPerson = await this.personRepository.findOne({
        where: { idCard: personInfo.idCard }
      });
      if (existingPerson) {
        throw new Error('该身份证号已存在');
      }
    }

    // 检查残疾证号是否已存在
    if (personInfo.disabilityId) {
      const existingPerson = await this.personRepository.findOne({
        where: { disabilityId: personInfo.disabilityId }
      });
      if (existingPerson) {
        throw new Error('该残疾证号已存在');
      }
    }

    // 验证照片中的文件ID
    for (const photo of photos) {
      if (photo.fileId) {
        const fileExists = await this.fileRepository.findOne({ where: { id: photo.fileId } });
        if (!fileExists) {
          throw new Error(`照片文件ID ${photo.fileId} 不存在`);
        }
      } else {
        throw new Error('照片必须包含有效的文件ID');
      }
    }

    // 验证银行卡中的文件ID
    for (const bankCard of bankCards) {
      if (bankCard.fileId) {
        const fileExists = await this.fileRepository.findOne({ where: { id: bankCard.fileId } });
        if (!fileExists) {
          throw new Error(`银行卡照片文件ID ${bankCard.fileId} 不存在`);
        }
      } else {
        throw new Error('银行卡必须包含有效的文件ID');
      }
    }

    // 创建残疾人基本信息
    const person = this.personRepository.create(personInfo);
    const savedPerson = await this.personRepository.save(person);

    // 准备关联数据
    const personId = savedPerson.id;

    // 处理银行卡信息，确保只有一个默认银行卡
    const processedBankCards = [...bankCards];
    const defaultCardsCount = processedBankCards.filter(card => card.isDefault === 1).length;
    if (defaultCardsCount > 1) {
      // 只保留第一个默认银行卡
      let defaultSet = false;
      processedBankCards.forEach(card => {
        if (card.isDefault === 1 && !defaultSet) {
          defaultSet = true;
        } else if (card.isDefault === 1) {
          card.isDefault = 0;
        }
      });
    }

    // 创建银行卡信息
    let savedBankCards: DisabledBankCard[] = [];
    if (processedBankCards.length > 0) {
      const cardsToSave = processedBankCards.map(card =>
        this.bankCardRepository.create({ ...card, personId })
      );
      savedBankCards = await this.bankCardRepository.save(cardsToSave);
    }

    // 创建照片信息
    let savedPhotos: DisabledPhoto[] = [];
    if (photos.length > 0) {
      const photosToSave = photos.map(photo =>
        this.photoRepository.create({ ...photo, personId, uploadTime: new Date() })
      );
      savedPhotos = await this.photoRepository.save(photosToSave);
    }

    // 创建备注信息
    let savedRemarks: DisabledRemark[] = [];
    if (remarks.length > 0) {
      const remarksToSave = remarks.map(remark =>
        this.remarkRepository.create({ ...remark, personId, remarkTime: new Date() })
      );
      savedRemarks = await this.remarkRepository.save(remarksToSave);
    }

    // 创建回访记录
    let savedVisits: DisabledVisit[] = [];
    if (visits.length > 0) {
      const visitsToSave = visits.map(visit =>
        this.visitRepository.create({ ...visit, personId })
      );
      savedVisits = await this.visitRepository.save(visitsToSave);
    }


    // 返回创建的所有信息
    return {
      personInfo: savedPerson,
      bankCards: savedBankCards,
      photos: savedPhotos,
      remarks: savedRemarks,
      visits: savedVisits,
      message: '残疾人所有信息创建成功',
      success: true
    };
  }

  /**
   * 聚合查询残疾人所有信息
   */
  async findDisabledPersonWithAllData(personId: number): Promise<{
    personInfo: DisabledPerson;
    bankCards: DisabledBankCard[];
    photos: DisabledPhoto[];
    remarks: DisabledRemark[];
    visits: DisabledVisit[];
    success: boolean;
  }> {
    // 查询残疾人基本信息（包含关联数据）
    const person = await this.disabledPersonService.findOne(personId);
    if (!person) {
      throw new Error('未找到该残疾人信息');
    }


    return {
      personInfo: person,
      bankCards: person.bankCards || [],
      photos: person.photos || [],
      remarks: person.remarks || [],
      visits: person.visits || [],
      success: true
    };
  }

  /**
   * 更新残疾人所有信息
   */
  async updateDisabledPersonWithAllData(personId: number, data: {
    personInfo?: Partial<DisabledPerson>;
    bankCards?: Partial<DisabledBankCard>[];
    photos?: Partial<DisabledPhoto>[];
    remarks?: Partial<DisabledRemark>[];
    visits?: Partial<DisabledVisit>[];
  }): Promise<{
    personInfo: DisabledPerson;
    bankCards: DisabledBankCard[];
    photos: DisabledPhoto[];
    remarks: DisabledRemark[];
    visits: DisabledVisit[];
    message: string;
    success: boolean;
  } | null> {
    const { personInfo = {}, bankCards = [], photos = [], remarks = [], visits = [] } = data;

    // 检查残疾人是否存在
    const existingPerson = await this.personRepository.findOne({
      where: { id: personId },
      relations: ['bankCards', 'bankCards.file', 'bankCards.file.uploadUser', 'photos', 'photos.file', 'photos.file.uploadUser', 'remarks', 'visits']
    });

    if (!existingPerson) {
      return null;
    }

    // 更新残疾人基本信息
    if (Object.keys(personInfo).length > 0) {
      // 如果更新了身份证号，检查唯一性
      if (personInfo.idCard && personInfo.idCard !== existingPerson.idCard) {
        const existingWithIdCard = await this.personRepository.findOne({
          where: { idCard: personInfo.idCard }
        });
        if (existingWithIdCard) {
          throw new Error('身份证号已存在');
        }
      }

      Object.assign(existingPerson, personInfo);
      await this.personRepository.save(existingPerson);
    }

    // 更新银行卡信息（先删除旧的，再创建新的）
    if (bankCards.length > 0) {
      await this.bankCardRepository.delete({ personId });
      const cardsToSave = bankCards.map(card =>
        this.bankCardRepository.create({ ...card, personId })
      );
      await this.bankCardRepository.save(cardsToSave);
    }

    // 更新照片信息（先删除旧的，再创建新的）
    if (photos.length > 0) {
      await this.photoRepository.delete({ personId });
      const photosToSave = photos.map(photo =>
        this.photoRepository.create({ ...photo, personId, uploadTime: new Date() })
      );
      await this.photoRepository.save(photosToSave);
    }

    // 更新备注信息（先删除旧的，再创建新的）
    if (remarks.length > 0) {
      await this.remarkRepository.delete({ personId });
      const remarksToSave = remarks.map(remark =>
        this.remarkRepository.create({ ...remark, personId, remarkTime: new Date() })
      );
      await this.remarkRepository.save(remarksToSave);
    }

    // 更新回访记录（先删除旧的，再创建新的）
    if (visits.length > 0) {
      await this.visitRepository.delete({ personId });
      const visitsToSave = visits.map(visit =>
        this.visitRepository.create({ ...visit, personId })
      );
      await this.visitRepository.save(visitsToSave);
    }

    // 获取更新后的完整数据
    const updatedPerson = await this.personRepository.findOne({
      where: { id: personId },
      relations: ['bankCards', 'bankCards.file', 'bankCards.file.uploadUser', 'photos', 'photos.file', 'photos.file.uploadUser', 'remarks', 'visits']
    });

    if (!updatedPerson) {
      return null;
    }


    return {
      personInfo: updatedPerson,
      bankCards: updatedPerson.bankCards || [],
      photos: updatedPerson.photos || [],
      remarks: updatedPerson.remarks || [],
      visits: updatedPerson.visits || [],
      message: '残疾人信息更新成功',
      success: true
    };
  }
}