import { InjectDataSource, InjectEntityModel } from '@midwayjs/typeorm';
import { DataSource, Repository } from 'typeorm';
import { Inject, Provide } from '@midwayjs/core';
import { ExportConfig } from '../entity/exportConfig.entity';
import { cloneDeep, get } from 'lodash';
import * as fs from 'fs';
import * as path from 'path';
import { AsyncExportService } from './asyncExport.service';
@Provide()
export class ExportConfigService {
  @InjectEntityModel(ExportConfig)
  model: Repository<ExportConfig>;
  @Inject()
  aeService: AsyncExportService;
  /**创建 */
  async create(data: object) {
    // 设置 创建数据的人
    const result = await this.model.insert(data);
    const id = get(result, 'identifiers.0.id');
    // 没有id估计是出错了
    if (!id) return;
    const createData = await this.fetch({ id });
    // 没有查出数据,也是有问题
    if (!createData) return;
    return createData;
  }
  async fetch(query: object) {
    const builder = this.model.createQueryBuilder();
    if (get(query, 'id')) builder.where(`"id"=:id`, { id: get(query, 'id') });
    else if (get(query, 'table')) builder.where(`"table"=:table`, { table: get(query, 'table') });
    const result = await builder.getOne();
    return result;
  }

  /**修改，单修改/多修改是统一修改为 */
  async update(query: object, data: object) {
    const result = await this.model.update(query, data);
    return result;
  }

  /**删除，单删多删都行 */
  async delete(query: object) {
    const result = await this.model.delete(query);
    return result;
  }

  /**
   * 导出设置字典
   */
  getDict_type() {
    const typeList = [
      { label: '字符串', value: 'string', dbType: 'character varying' },
      { label: '数字', value: 'integer', dbType: 'integer' },
      { label: '时间', value: 'date', dbType: 'timestamp without time zone' },
      { label: '文本', value: 'text', dbType: 'text' },
      { label: 'json', value: 'jsonb', dbType: 'jsonb' },
    ];
    return typeList;
  }

  getDict_source() {
    const sourceList = [
      { label: '填写', value: 'write' },
      { label: '字典', value: 'dict' },
      { label: '关联表', value: 'relation' },
    ];
    return sourceList;
  }
  
  getModelColumns(modelName, filters = []) {
    if (!modelName.includes('_model_')) {
      modelName = `_model_${modelName}`;
    }
    const model = this.aeService[modelName];
    // model
    const typeList = this.getDict_type();
    const column = model.metadata.columns;
    const ncols = [];
    for (const i of column) {
      const table = get(i, 'propertyName');
      const inFilter = filters.find(f => f === table);
      if (inFilter) continue;
      let type = get(i, 'type');
      const useType = typeList.find(f => f.dbType === type);
      if (useType && get(useType, 'value')) type = get(useType, 'value');
      const zh = get(i, 'comment');
      ncols.push({ type, column: table, zh });
    }
    return ncols;
  }

  async initData() {
    const p = path.resolve(__dirname, '../../importData', 'exportConfig.json');
    const file = fs.readFileSync(p, { encoding: 'utf8' });
    if (!file) return;
    await this.clearTable('exportConfig');
    let list = JSON.parse(file);
    list = list.map(i => {
      const obj = cloneDeep(i);
      obj.config = obj.config.map(c => {
        const co = cloneDeep(c);
        co.is_use = '0';
        const source = get(co, 'source');
        if (!source) co.source = 'write';
        return co;
      });
      return obj;
    });
    await this.model.insert(list);
  }

  @InjectDataSource('default')
  defaultDataSource: DataSource;
  /**
   * 清空表与id序列
   * @param tableName 表名 小驼峰
   */
  private async clearTable(tableName: string) {
    await this.defaultDataSource.query(`TRUNCATE TABLE "public"."${tableName}" RESTART IDENTITY RESTRICT;`);
    await this.defaultDataSource.query(`SELECT setval('"${tableName}_id_seq"', (SELECT max(id) FROM "${tableName}"));`);
  }
}
