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 { ShuyouGameAccountEntity } from '../../entity/game_account';
import * as _ from 'lodash';
import { ILogger } from '@midwayjs/logger';
import { ShuyouGameAccountService } from '../../service/game_account';
import { ShuyouGameAccountTempService } from '../../service/game_account_temp';
// import { ShuyouIdCardUsageEntity } from '../../entity/idcard_usage';
const fs = require('fs');

/**
 * 商品
 */
@Provide()
@CoolController({
  // 添加通用CRUD接口
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  // 设置表实体
  entity: ShuyouGameAccountEntity,
  service: ShuyouGameAccountService,
  // // 向表插入当前登录用户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: ['account_text', 'password_text'],
    // 让字段支持筛选
    fieldEq: ['account_text', 'password_text'],
    //   // 指定返回字段
    //   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: 'desc',
    },
  },
})
export class ShuyouAdminGameAccountController extends BaseController {
  @Inject()
  logger: ILogger;

  @Inject()
  ShuyouGameAccountService: ShuyouGameAccountService;

  @Inject()
  ShuyouGameAccountTempService: ShuyouGameAccountTempService;

  /**
   *批量插入数据库
   */
  @Post('/batchAdd')
  async batchAdd(@Body(ALL) queryObject) {
    const { fileaddress, type_id, status, remark } = queryObject;
    const filename = fileaddress._value.split('uploads')[1];
    // console.log(filename)
    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 = [];
          chrom = data.toString();
          const accounts = chrom.split(/[\r\n]+/); //按照换行符分割成数组
          accounts.forEach((item, index) => {
            if (item) {
              var data1 = item.split('----');
              if (data1.length < 2) {
                console.log(index + '文件格式错误');
                resolve({ code: -1, message: index + '文件格式错误' });
              }
              let obj = {
                account_text: data1[0],
                password_text: data1[1],
                vpn_text: data1[2],
                manufacturer: data1[3],
                model: data1[4],
                pnumber: data1[5],
                imei: data1[6],
                imsi: data1[7],
                simserial: data1[8],
                androidid: data1[9],
                mac: data1[10],
                type_id: type_id,
                status: status,
                remark: remark,
              };
              idcardArr.push(obj);
            }
          });
          resolve({ code: 1, data: idcardArr });
        });
      });
    };
    let composeText;
    composeText = await readFile('public/uploads' + filename);
    if (composeText.code == -1) {
      return this.ok({ code: -1, message: '文件格式错误' });
    }
    //======================================================插入临时表开始======================================================
    // 将文件拆分为1万一个，一次上传1万条，防止数据库报错
    let idcard_text_temp;
    await ykhForeach(composeText.data, async (item, index) => {
      if (index % 10000 == 0) {
        if (index != 0) {
          await this.ShuyouGameAccountTempService.batchAdd(idcard_text_temp);
        }
        idcard_text_temp =
          `('` +
          item.account_text +
          `',` +
          `'` +
          item.password_text +
          `',` +
          `'` +
          item.remark +
          `')`;
      } else {
        idcard_text_temp +=
          `,('` +
          item.account_text +
          `',` +
          `'` +
          item.password_text +
          `',` +
          `'` +
          item.remark +
          `')`;
        if (index == composeText.data.length - 1) {
          await this.ShuyouGameAccountTempService.batchAdd(idcard_text_temp);
        }
      }
    });
    //======================================================插入临时表结束======================================================
    //对比临时表和账号表，找出账号表中已存在的数据
    let repeat = await this.ShuyouGameAccountTempService.contrastData(type_id);
    this.logger.info(repeat.length);
    //清空临时表数据
    await this.ShuyouGameAccountTempService.deleteAll();
    // 将文件拆分为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.ShuyouGameAccountService.batchAdd(idcard_text);
          this.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) - parseInt(reqmsg.changedRows);
          // sumaccAll += sumacc;
          duplicatesAll += parseInt(duplicates);
          affectedRowsAll += parseInt(reqmsg.affectedRows);
        }
        idcard_text =
          `('` +
          item.account_text +
          `',` +
          `'` +
          item.password_text +
          `',` +
          `'` +
          item.vpn_text +
          `',` +
          `'` +
          item.manufacturer +
          `',` +
          `'` +
          item.model +
          `',` +
          `'` +
          item.pnumber +
          `',` +
          `'` +
          item.imei +
          `',` +
          `'` +
          item.imsi +
          `',` +
          `'` +
          item.simserial +
          `',` +
          `'` +
          item.androidid +
          `',` +
          `'` +
          item.mac +
          `',` +
          `'` +
          item.type_id +
          `',` +
          `'` +
          item.status +
          `',` +
          `'` +
          item.remark +
          `')`;
      } else {
        idcard_text +=
          `,('` +
          item.account_text +
          `',` +
          `'` +
          item.password_text +
          `',` +
          `'` +
          item.vpn_text +
          `',` +
          `'` +
          item.manufacturer +
          `',` +
          `'` +
          item.model +
          `',` +
          `'` +
          item.pnumber +
          `',` +
          `'` +
          item.imei +
          `',` +
          `'` +
          item.imsi +
          `',` +
          `'` +
          item.simserial +
          `',` +
          `'` +
          item.androidid +
          `',` +
          `'` +
          item.mac +
          `',` +
          `'` +
          item.type_id +
          `',` +
          `'` +
          item.status +
          `',` +
          `'` +
          item.remark +
          `')`;
        if (index == composeText.data.length - 1) {
          reqmsg = await this.ShuyouGameAccountService.batchAdd(idcard_text);
          this.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) - parseInt(reqmsg.changedRows);
          // sumaccAll += sumacc;
          duplicatesAll += parseInt(duplicates);
          affectedRowsAll += parseInt(reqmsg.affectedRows);
        }
      }
    });
    //删除上传的txt
    //================
    if (fs.existsSync('public/uploads' + filename)) {
      fs.unlinkSync('public/uploads' + filename);
    }
    //================
    sumaccAll = duplicatesAll + affectedRowsAll;
    return this.ok({
      code: 1,
      repeat: repeat,
      duplicatesAll: duplicatesAll,
      message:
        '本次上传账号共计' +
        sumaccAll +
        '条, 成功上传' +
        affectedRowsAll +
        '条, 重复数据' +
        duplicatesAll +
        '条',
    });
  }
}

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