import { Inject, Post, Provide, ALL, Body } from '@midwayjs/decorator';
// import { Context } from 'egg';
import { CoolController, BaseController } from 'midwayjs-cool-core';
// import { BaseSysUserEntity } from '../../../base/entity/sys/user';
import { ShuyouIdCardEntity } from '../../entity/idcard';
import * as _ from 'lodash';
import { ILogger } from '@midwayjs/logger';
import { ShuyouIdCardService } from '../../service/idcard';
// import { ShuyouIdCardUsageEntity } from '../../entity/idcard_usage';
const fs = require('fs');

/**
 * 商品
 */
@Provide()
@CoolController({
  // 添加通用CRUD接口
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  // 设置表实体
  entity: ShuyouIdCardEntity,
  service: ShuyouIdCardService,
  // // 向表插入当前登录用户ID
  // insertParam: async (ctx: Context) => {
  //   return {
  //     userId: ctx.admin.userId,
  //   };
  // },
  // // info接口忽略价格字段
  // infoIgnoreProperty: ['price'],
  before: ctx => {
    //前段数据转JSON格式
    const data = ctx.request.body;
    if (data.id_name == '') {
      data.id_name = null;
    }
    if (data.id_number == '') {
      data.id_number = null;
    }
    ctx.request.body.data = JSON.stringify(data);
  },
  // 分页查询配置
  pageQueryOp: {
    // 让字段支持模糊查询
    keyWordLikeFields: ['id_name', 'id_number'],
    // 让字段支持筛选
    fieldEq: ['id_name', 'id_number'],
    //   // 指定返回字段
    //   select: ['a.*', 'b.name'],
    //   // 关联表用户表
    // leftJoin: [
    //   {
    //     // 管理的表
    //     entity: ShuyouIdCardUsageEntity,
    //     // 别名
    //     alias: 'b',
    //     // 关联条件
    //     condition: 'a.userId = b.id',
    //   },
    // ],
    //   // 增加其他条件
    //   where: async (ctx: Context) => {
    //     return [
    //       // 价格大于90
    //       ['a.price > :price', { price: 90.0 }],
    //     ];
    //   },
    //   // 添加排序
    addOrderBy: {
      // 排序字段及排序方式
      id_name: 'asc',
    },
  },
})
export class ShuyouAdminIdCardController extends BaseController {
  @Inject()
  logger: ILogger;

  @Inject()
  ShuyouIdCardService: ShuyouIdCardService;

  /**
   *批量插入数据库
   */
  @Post('/batchAdd')
  async batchAdd(@Body(ALL) queryObject) {
    const { fileaddress, flag } = queryObject;
    // console.log(uploadtime)
    // console.log(fileaddress._value)
    const filename = fileaddress._value.split('uploads')[1];
    // console.log(filename)
    let flagstr = '';
    if (flag) {
      flagstr = flag;
    }
    let reqmsg;
    // var data =fs.readFileSync("public/uploads"+filename);
    // 定义读取文件函数
    var readFile = function (fileName) {
      return new Promise(function (resolve, reject) {
        fs.readFile(fileName, function (error, data) {
          if (error) return reject(error);
          var chrom = '';
          let idcardArr = [];
          chrom = data.toString();
          const accounts = chrom.split(/[\r\n]+/); //按照换行符分割成数组
          // console.log(accounts.length)
          accounts.forEach((item, index) => {
            if (item) {
              var data1 = item.split('----');
              if (data1.length < 2) {
                // console.log(item)
                console.log(index + '文件格式错误');
                resolve({ code: -1, message: index + '文件格式错误' });
              }
              // if (index == 0) {
              //   idcard_text = `('` + data1[0] + `',` + `'` + data1[1] + `',` + `'` + flagstr + `')`
              // } else {
              //   idcard_text += `,('` + data1[0] + `',` + `'` + data1[1] + `',` + `'` + flagstr + `')`
              // }
              let obj = {
                id_name: data1[0],
                id_number: data1[1],
                flag: flagstr,
              };
              idcardArr.push(obj);
            }
          });
          resolve({ code: 1, data: idcardArr });
        });
      });
    };
    let composeText;
    composeText = await readFile('public/uploads' + filename);
    if (composeText.code == -1) {
      return await this.ok({ code: -1, message: '文件格式错误' });
    }
    // 将文件拆分为1万一个，一次上传1万条，防止数据库报错
    let idcard_text;
    let sumaccAll = 0;
    let duplicatesAll = 0;
    let affectedRowsAll = 0;
    await ykhForeach(composeText.data, async (item, index) => {
      if (index % 10000 == 0) {
        if (index != 0) {
          reqmsg = await this.ShuyouIdCardService.batchAdd(idcard_text);
          //   logger.info(reqmsg)
          let str = reqmsg.info.toString();
          let duplicates;
          duplicates = str.substring(
            str.indexOf('Duplicates') + 12,
            str.indexOf('Warnings') - 1
          );
          let sumacc = parseInt(reqmsg.warningCount + reqmsg.affectedRows);
          sumaccAll += sumacc;
          duplicatesAll += parseInt(duplicates);
          affectedRowsAll += parseInt(reqmsg.affectedRows);
        }
        idcard_text = ``;
        idcard_text =
          `('` +
          item.id_name +
          `',` +
          `'` +
          item.id_number +
          `',` +
          `'` +
          item.flag +
          `')`;
      } else {
        idcard_text +=
          `,('` +
          item.id_name +
          `',` +
          `'` +
          item.id_number +
          `',` +
          `'` +
          item.flag +
          `')`;
      }
      if (index == composeText.data.length - 1) {
        reqmsg = await this.ShuyouIdCardService.batchAdd(idcard_text);
        //   logger.info(reqmsg)
        let str = reqmsg.info.toString();
        let duplicates;
        duplicates = str.substring(
          str.indexOf('Duplicates') + 12,
          str.indexOf('Warnings') - 1
        );
        let sumacc = parseInt(reqmsg.warningCount + reqmsg.affectedRows);
        sumaccAll += sumacc;
        duplicatesAll += parseInt(duplicates);
        affectedRowsAll += parseInt(reqmsg.affectedRows);
      }
    });
    //删除上传的txt
    //================
    if (fs.existsSync('public/uploads' + filename)) {
      fs.unlinkSync('public/uploads' + filename);
    }
    //================
    return this.ok({
      code: 1,
      message:
        '本次上传身份信息共计' +
        sumaccAll +
        '条, 成功上传' +
        affectedRowsAll +
        '条, 重复数据' +
        duplicatesAll +
        '条',
    });
  }

  /**
   * 其他接口
   */
  // @Get('/other')
  // async other() {
  //   return this.ok('hello, cool-admin!!!');
  // }
}

// foreach加上async/await
const ykhForeach = async (arr, callback) => {
  const length = arr.length;
  const O = Object(arr);
  let k = 0;
  while (k < length) {
    if (k in O) {
      // console.log('doing foreach...');
      const kValue = O[k];
      await callback(kValue, k, O);
    }
    k++;
  }
};
