import { Inject, Post, Provide, ALL, Body } from '@midwayjs/decorator';
// import { Context } from 'egg';
import { CoolController, BaseController } from 'midwayjs-cool-core';
import { ShuyouSpecialAccountEntity } from '../../entity/special_game_account';
import * as _ from 'lodash';
import { ILogger } from '@midwayjs/logger';
import { ShuyouSpecialAccountService } from '../../service/special_game_account';
const fs = require('fs')

/**
 * 特殊卡号
 */
@Provide()
@CoolController({
  // 添加通用CRUD接口
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  // 设置表实体
  entity: ShuyouSpecialAccountEntity,
  service: ShuyouSpecialAccountService,
  before: ctx => {
    //前段数据转JSON格式
    const data = ctx.request.body;
    if (data.card_text == "") {
      data.card_text = null
    }
    if (data.card_password == "") {
      data.card_password = null
    }
    ctx.request.body.data = JSON.stringify(data);
  },
  // 分页查询配置
  pageQueryOp: {
    // 让字段支持模糊查询
    keyWordLikeFields: ['card_text'],
    // 让字段支持筛选
    fieldEq: ['card_text'],
    // 添加排序
    addOrderBy: {
      // 排序字段及排序方式
      card_text: 'asc',
    },
  },
})
export class ShuyouAdminSpecialAccountController extends BaseController {

  @Inject()
  logger: ILogger;

  @Inject()
  ShuyouSpecialAccountService: ShuyouSpecialAccountService;

  /**
   *批量插入数据库
   */
  @Post('/batchAdd')
  async batchAdd(@Body(ALL) queryObject) {
    const { fileaddress, amount_all, type_id, remark } = queryObject;
    const filename = fileaddress._value.split("uploads")[1]
    let reqmsg
    // 定义读取文件函数
    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 = [];
          let amount = 0;
          chrom = data.toString();
          const accounts = chrom.split(/[\r\n]+/);//按照换行符分割成数组
          // console.log(accounts.length)
          accounts.forEach((item, index) => {
            if (item) {
              item = item.replace(/\s+/g, "");
              // 848608345----838541432479----60.00----查询成功
              var data1 = item.split('----')
              if (data1.length < 2) {
                resolve({ code: -1, message: index + '文件格式错误' })
              } else if (data1.length < 3) {
                amount = parseFloat(amount_all);
              } else {
                amount = parseFloat(data1[2]);
              }
              let obj = {
                card_text: data1[0],
                card_password: data1[1],
                amount: amount
              }
              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 card
    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.ShuyouSpecialAccountService.batchAdd(card);
          //   logger.info(reqmsg)
          // let str = reqmsg.message.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);
        }
        card = `('` + item.card_text + `',` + `'` + item.card_password + `',` + type_id + `,` + item.amount + `,`
          + item.amount + `,` + `'` + remark + `')`;
      } else {
        card += `,('` + item.card_text + `',` + `'` + item.card_password + `',` + type_id + `,` + item.amount + `,`
          + item.amount + `,` + `'` + remark + `')`;
        if (index == composeText.data.length - 1) {
          reqmsg = await this.ShuyouSpecialAccountService.batchAdd(card);
          // this.logger.info(reqmsg)
          // let str = reqmsg.message.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 + '条' });
    return this.ok({ code: 1, message: sumaccAll + '条记录新增、更新成功' });
  }




}

// 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++;
  }
};