import {
  Provide,
  Body,
  ALL,
  Inject,
  Post,
  Get,
  Query,
} from '@midwayjs/decorator';
import { Context } from 'egg';
import { CoolController, BaseController } from '@cool-midway/core';
import { LoginDTO } from '../../dto/login';
import * as fs from 'fs';
import { BaseSysLoginService } from '../../service/sys/login';
import { BaseSysParamService } from '../../service/sys/param';
import { DataService } from '../../service/dataapi/dataapi';
import { CommEntity } from '../../entity/app/commentity';

/**
 * 不需要登录的后台接口
 */
@Provide()
@CoolController({api: ['add', 'delete', 'update', 'info', 'list', 'page'],
entity: CommEntity})
export class BaseOpenController extends BaseController {
  @Inject()
  baseSysLoginService: BaseSysLoginService;

  @Inject()
  baseSysParamService: BaseSysParamService;

  @Inject()
  dataService: DataService;

  @Inject()
  ctx: Context;

  @Inject('cool:eps:open')
  eps;

  /**
   * 实体信息与路径
   * @returns
   */
  @Get('/eps', { summary: '实体信息与路径' })
  public async getEps() {
    return this.ok(this.eps);
  }

  /**
   * 根据配置参数key获得网页内容(富文本)
   */
  @Get('/html', { summary: '获得网页内容的参数值' })
  async htmlByKey(@Query() key: string) {
    this.ctx.body = await this.baseSysParamService.htmlByKey(key);
  }

  /**
   * 登录
   * @param login
   */
  @Post('/login', { summary: '登录' })
  async login(@Body(ALL) login: LoginDTO) {
    return this.ok(await this.baseSysLoginService.login(login));
  }

  /**
   * 获得验证码
   */
  @Get('/captcha', { summary: '验证码' })
  async captcha(
    @Query() type: string,
    @Query() width: number,
    @Query() height: number
  ) {
    return this.ok(await this.baseSysLoginService.captcha(type, width, height));
  }

  /**
   * 刷新token
   */
  @Get('/refreshToken', { summary: '刷新token' })
  async refreshToken(@Query() refreshToken: string) {
    return this.ok(await this.baseSysLoginService.refreshToken(refreshToken));
  }


  /**
   * 获得数据
   */
  @Get('/getdata', { summary: '数据接口' })
  async getData(@Query(ALL) params: any) {
    ``
    console.log('-------------------------------------------------------');
    console.log(params);
    return this.ok(await this.dataService.getData(params));
  }

  /**
   * 获得数据
   */
  @Post('/postdata', { summary: '数据接口' })
  async postData(@Query(ALL) params: any) {
    return this.ok(await this.dataService.getData(params));
  }

  @Get('/createEntity', {})
  async createEntity() {
    console.log('生成综合实体类任务开始执行');
    const startTime = Date.now();
    const columns = await this.dataService.getDataByNative({ "bid": "getColumns", "pageindex": "1", "pagesize": "300" })  //bid_obj_[0], query?.pageindex || null , query?.pagesize || null, query
    // console.log(columns)
    const columnstr = [];
    columnstr.push(`import { EntityModel } from '@midwayjs/orm';
    import { BaseEntity } from '@cool-midway/core';
    import { Column, Double } from 'typeorm';
    
    /**
     * 综合实体类
     */
    @EntityModel('t_sys_comm_column')
    export class CommEntity extends BaseEntity { \n`)
    columns.forEach(element => {  //{ column_name: 'avg_task_time', data_type: 'int' },
      //select table_name,column_name,data_type,column_type,is_nullable,column_default,ordinal_position,column_key,column_comment from view_columninfo order by table_name,column_name;
      columnstr.push(`@Column({ comment:'${element.column_comment}', type:'${element.data_type}', default:'${element.column_default}'})\n`)
      //varchar  int   text  double  datetime  bigint   enum  mediumtext  longtext  tinyint  decimal
      let fieldType = 'string';
      switch (element.data_type) {
        case 'varchar':
          fieldType = 'string'
          break;
        case 'text':
          fieldType = 'string'
          break;
        case 'int':
          fieldType = 'number'
          break;
        case 'bigint':
          fieldType = 'number'
          break;
        case 'tinyint':
          fieldType = 'number'
          break;
        case 'datetime':
          fieldType = 'Date'
          break;    
        case 'double':
          fieldType = 'Double'
          break;   
        case 'decimal':
          fieldType = 'Double'
          break;   
        default:
          break;
      }
      // let fieldType = element.data_type=='varchar' ? 'string' : element.data_type=='int' ? 'number' : element.data_type=='bigint' ? 'number' : element.data_type=='tinyint' ? 'number' 
      columnstr.push(`${element.tbname}_${element.column_name}: ${fieldType};\n`)
      columnstr.push(`\n`)
    });
    columnstr.push(`}`)
    if (fs.existsSync('../entity/app/commentity.ts')) {
      console.log(' file is exists')
    } else {
      console.log(' file is not exists')
      // API
      fs.writeFile('./src/app/modules/base/entity/app/commentity.ts',
        columnstr.join(''), (error) => {
          // 创建失败
          if (error) {
            console.log(`创建失败：${error}`)
          }
          // 创建成功
          console.log(`创建成功！`)

        })
    }
    //读取文件内容，并转化为Json对象
    // let userBugsJson = JSON.parse(fs.readFileSync("app/public/static/Data.json", "utf8"));
    // //获取Json里key为data的数据
    // const data = userBugsJson['data'];
    // return data;
    console.log(`生成综合实体类任务结束，耗时:${Date.now() - startTime}ms`);
  }

}
