import { Provide, Inject } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, Equal } from 'typeorm';
import { Incubator } from '../../entity/users/incubator.entity';
import { BaseServiceV2 } from '../../frame/BaseServiceV2';
import { get } from 'lodash';
import { Cirelation } from '../../entity/users/cirelation.entity';
import { CompanyService } from './company.service';
import { CompanyYear } from '../../entity/users/companyYear.entity';
@Provide()
export class IncubatorService extends BaseServiceV2 {
  @InjectEntityModel(Incubator)
  model: Repository<Incubator>;

  @InjectEntityModel(Cirelation)
  cModel: Repository<Cirelation>;

  @InjectEntityModel(CompanyYear)
  cyModel: Repository<CompanyYear>;

  @Inject()
  companyService: CompanyService;

  getQueryColumnsOpera() {
    const obj = {
      name: this.Opera.Like,
      industry: this.Opera.In,
      tags: this.Opera.Json,
      area: this.Opera.Json,
    };
    return obj;
  }
  // 数据统计
  async statistics(query) {
    const info: any = {};
    const { user, status } = query;
    const result = await this.model.findOne({ where: { user: Equal(user), status: Equal(status) } });
    if (result) {
      // 查询关联企业信息统计总数
      const companyList = await this.cModel.find({ where: { incubator: Equal(get(result, 'id')), status: Equal(status) } });
      let person = 0;
      let tech_num = 0;
      let new_num = 0;
      let tech_noum = 0;
      let new_noum = 0;
      for (const val of companyList) {
        const company = await this.companyService.fetch({ id: get(val, 'company') });
        person = person + parseInt(company.person);
        if (company.is_tech === '0') tech_num = tech_num + 1;
        else tech_noum = tech_noum + 1;
        if (company.is_new === '0') new_num = new_num + 1;
        else new_noum = new_noum + 1;
      }
      info.total_num = companyList.length;
      info.person = person;
      info.show = true;
      info.tech_num = tech_num;
      info.new_num = new_num;
      info.tech_noum = tech_noum;
      info.new_noum = new_noum;
      // 查询孵化器信息
      info.name = get(result, 'name');
      info.id = get(result, 'id');
      info.file = get(result, 'file');
      const list = [
        { num: '0', name: '是否是中试场地', value: 'is_have', type: '0' },
        { num: 0, name: '运营单位人数', value: 'unit_num' },
        { num: 0, name: '省级导师数', value: 'teacher_num' },
        { num: 0, name: '活动人次数', value: 'activity_num' },
        { num: 0, name: '活动企业数量', value: 'actCompany_num' },
        { num: 0, name: '市级以上活动数', value: 'actCity_num' },
        { num: 0, name: '投资机构活动数', value: 'actInstitution_num' },
        { num: 0, name: '入驻企业数', value: 'company_num' },
        { num: '0', name: '是否有合作', value: 'cooperate', type: '0' },
      ];
      for (const val of list) {
        if (val.type === '0') {
          if (get(result, val.value) === '0') val.num = '是';
          else val.num = '否';
        } else val.num = get(result, val.value) || 0;
      }
      info.list = list;
    }
    return info;
  }
  // 查询所有孵化器关联企业的营业收入
  async allList(query) {
    const { year, incubator, is_use, status } = query;
    const builder = await this.cModel.createQueryBuilder('cirelation').select(['cirelation.company']).setFindOptions({ where: { incubator, status } });
    const data = await builder.getMany();
    const list1 = [];
    const list2 = [];
    const list3 = [];
    const nameList = [];
    for (const val of data) {
      const companyYear = await this.cyModel.findOne({ where: { company: Equal(get(val, 'company')), year: Equal(year), status: Equal(status), is_use: Equal(is_use) } });
      const company = await this.companyService.fetch({ id: get(val, 'company') });
      if (company) {
        nameList.push(get(company, 'name') || '');
        list1.push(get(companyYear, 'esincome_money') || 0);
        list2.push(get(companyYear, 'esprofit_money') || 0);
        list3.push(get(companyYear, 'estax_money') || 0);
      }
    }
    return { nameList, list: [list1, list2, list3] };
  }

  // 查询有关孵化企业的领域数量
  async field(query) {
    const { incubator, status } = query;
    const builder = await this.cModel.createQueryBuilder('cirelation').select(['cirelation.company']).setFindOptions({ where: { incubator, status } });
    const data = await builder.getMany();
    let list = [];
    const companyList = [];
    const nameList = ['生物医药', '化工新材料', '先进装备制造', '高端服务', '光电子', '电子信息'];
    for (const val of data) {
      const company = await this.companyService.fetch({ id: get(val, 'company') });
      if (get(company, 'industry')) {
        const info = { value: 0, name: get(company, 'industry') };
        for (const tags of nameList) {
          if (get(company, 'industry') === tags) info.value = info.value + 1;
        }
        companyList.push(info);
      }
    }
    list = companyList.reduce((accumulator, currentItem) => {
      const existingItem = accumulator.find(item => item.name === currentItem.name);
      if (existingItem) {
        existingItem.value += currentItem.value;
      } else {
        accumulator.push({ ...currentItem });
      }
      return accumulator;
    }, []);
    return { nameList, list };
  }

  // 孵化器专属企业查询
  async list(query) {
    const { skip = 0, limit = 0, is_tech, is_new, ...info } = query;
    const builder = await this.cModel
      .createQueryBuilder('cirelation')
      .select(['cirelation.company'])
      .setFindOptions({ where: { incubator: get(info, 'incubator'), status: get(info, 'status') } });
    const list = await builder.getMany();
    const companyids = list.map(i => i.company);
    const { data, total } = await this.companyService.query({ id: companyids, is_tech, is_new }, { skip, limit });
    return { data, total };
  }
}
