import { Provide } from '@midwayjs/core';
import * as Excel from 'exceljs';
import * as path from 'path';
import { Region } from '../../entity/system/region.entity';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
@Provide()
export class InitRegionService {
  @InjectEntityModel(Region)
  regionModel: Repository<Region>;
  async index() {
    // this.initProvnices();
    // this.initNotProvnice('cities');
    // this.initNotProvnice('areas');
    // 街道数据量大,需要拆分
    // this.initNotProvnice('streets');
  }
  async initProvnices() {
    const p = path.resolve(__dirname, '../../../importData', 'area', 'CN_provinces_2023.csv');
    const workbook = new Excel.Workbook();
    const worksheet = await workbook.csv.readFile(p);
    const meta = {
      1: 'code',
      2: 'name',
    };
    const allData = [];
    worksheet.eachRow((row, ri) => {
      if (ri === 1) {
        // 不处理
      } else {
        const arr = row.values;
        const obj = { level: 'province' };
        for (const key in meta) {
          obj[meta[key]] = arr[key];
        }
        allData.push(obj);
      }
    });
    return await this.regionModel.insert(allData);
  }

  async initNotProvnice(type) {
    const p = path.resolve(__dirname, '../../../importData', 'area', `CN_${type}_2023.csv`);
    const workbook = new Excel.Workbook();
    const worksheet = await workbook.csv.readFile(p);
    const meta = {
      1: 'code',
      2: 'name',
      3: 'parent_code',
    };
    const allData = [];
    const levelObj = {
      cities: 'city',
      areas: 'area',
      streets: 'street',
    };
    worksheet.eachRow((row, ri) => {
      if (ri === 1) {
        // 不处理
      } else {
        const arr = row.values;
        const obj = { level: levelObj[type] };
        for (const key in meta) {
          obj[meta[key]] = arr[key];
        }
        allData.push(obj);
      }
    });
    return await this.regionModel.insert(allData);
  }
}
