/*
 * @Author: YKH
 * @Date: 2022-04-06 10:43:33
 * @LastEditTime: 2022-04-08 13:53:33
 * @Description: 
 * @FilePath: \cool-admin\cool-admin-midway-master\src\app\modules\shuyou\controller\admin\file_list.ts
 */
import { Provide, Post, Inject, Body, ALL } from '@midwayjs/decorator';
import { CoolController, BaseController } from 'midwayjs-cool-core';
import { ShuyouFileListEntity } from '../../entity/file_list';
import { ShuyouFileListService } from '../../service/file_list';
import { ILogger } from '@midwayjs/logger';
import { Utils } from '../../../../comm/utils';
import * as qiNiu from 'qiniu';

//私人测试
// const aKey = '7_ZqHdxygi4b2rDfeYlRGcNzAotKIHny4Pw7FlrH';  //七牛云ak,sk,bucket
// const sKdy = 'LHkKpphENfKFMooSwptLo18xySESdS-EdY1yI59_';
// const bucket0 = 'qiniu-cool';
// const CName = 'http://r9ns9ktet.hn-bkt.clouddn.com/'; //七牛云外链
//公司七牛
const aKey = 'B81Gsvry2StqKVE3txS-7v9GBBfqykC9zhebmxnW';  //七牛云ak,sk,bucket
const sKdy = 'YEZJuYcdeF7vRvzffxpopAVR-jMPZg9pZ-4IKTVW';
const bucket0 = 'pinaishop';
const CName = 'http://cdn.pinaishop.kfzs.com/'; //七牛云外链
/**
 * 文件操作
 */
@Provide()
@CoolController({
  // 添加通用CRUD接口
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  // 设置表实体
  entity: ShuyouFileListEntity,
  service: ShuyouFileListService,

  before: ctx => {
    //前段数据转JSON格式
    const data = ctx.request.body;
    ctx.request.body.data = JSON.stringify(data);
  },
  // 分页查询配置
  pageQueryOp: {
    // 让字段支持模糊查询
    keyWordLikeFields: ['id'],
    // 让字段支持筛选
    fieldEq: ['id'],
    // 添加排序
    addOrderBy: {
      // 排序字段及排序方式
      updateTime: 'desc',
    },
  },
})
export class ShuyouAdminFileListController extends BaseController {

  @Inject()
  logger: ILogger;

  @Inject()
  utils: Utils;

  @Inject()
  ShuyouFileListService: ShuyouFileListService;


  /**
   * 获取上传token
   * @return {*} 
   * @memberof ShuyouAdminFileListController
   */
  @Post('/getQiniuToken')
  async getQiniuToken() {
    var accessKey = aKey;
    var secretKdy = sKdy;
    var mac = new qiNiu.auth.digest.Mac(accessKey, secretKdy);
    var options = {
      scope: bucket0
    };
    var putPolicy = new qiNiu.rs.PutPolicy(options);
    var uploadToken = putPolicy.uploadToken(mac);

    // this.logger.warn(uploadToken)

    let data = {
      token: uploadToken,
      CName: CName
    };
    return await this.ok({ code: 1, data: data });

  }
  /**
   * 删除单个文件
   * @param {*} queryObject
   * @memberof ShuyouAdminFileListController
   */
  @Post('/deleteFile')
  async deleteFile(@Body(ALL) queryObject) {
    const { fileUrl } = queryObject
    var accessKey = aKey;
    var secretKdy = sKdy;
    var mac = new qiNiu.auth.digest.Mac(accessKey, secretKdy);
    var config = new qiNiu.conf.Config();
    // 空间对应的机房
    // config.zone = qiNiu.zone.Zone_z2; //华南机房
    var bucketManager = new qiNiu.rs.BucketManager(mac, config);
    //===============================
    var bucket = bucket0;
    var key = fileUrl;
    bucketManager.delete(bucket, key, (err, respBody, respInfo) => {
      if (err) {
        console.log(err);
        //throw err;
      } else {
        // console.log(respInfo);
        // console.log(respInfo.statusCode);
        // console.log(respBody);
        return this.ok({ code: 1 });
      }
    });
  }
  /**
   * 从七牛云删除文件并且清除数据库记录
   * @param {*} queryObject
   * @memberof ShuyouAdminFileListController
   */
  @Post('/deleteFileAndRecord')
  async deleteFileAndRecord(@Body(ALL) queryObject) {
    const { id, fileUrl } = queryObject
    var accessKey = aKey;
    var secretKdy = sKdy;
    var mac = new qiNiu.auth.digest.Mac(accessKey, secretKdy);
    var config = new qiNiu.conf.Config();
    // 空间对应的机房
    // config.zone = qiNiu.zone.Zone_z2; //华南机房
    var bucketManager = new qiNiu.rs.BucketManager(mac, config);
    //===============================
    var bucket = bucket0;
    var key = fileUrl;
    bucketManager.delete(bucket, key, async (err, respBody, respInfo) => {
      if (err) {
        console.log(err);
        //throw err;
      } else {
        // console.log(respInfo);
        // console.log(respInfo.statusCode);
        // console.log(respBody);
        if (respInfo.statusCode == 200) {
          const deleteResult = await this.ShuyouFileListService.deleteById(id);
          // console.log(deleteResult)
          if (deleteResult == 1000) {
            return await this.ok({ code: 1, message: '文件已删除' });
          }
        }
        return await this.ok({ code: 1 });
      }
    });

  }
  /**
   * 查询某task_id下某一类型文件最新一个渠道号
   * @param {*} queryObject
   * @return {*} 
   * @memberof ShuyouAdminFileListController
   */
  @Post('/queryVersionByType')
  async queryVersionByType(@Body(ALL) queryObject) {
    const { task_id, type } = queryObject
    const shuyouFileListEntity = await this.ShuyouFileListService.queryVersionByType(task_id, type);
    if (shuyouFileListEntity) {
      return this.ok({ code: 1, fileVersion: shuyouFileListEntity.fileVersion });
    } else {
      return this.ok({ code: 1, fileVersion: 0 });
    }
  }
  /**
   *
   * //停止任务时批量删除文件（前端询问是否删除该任务下文件，让用户自己选择是否删除）
   * @param {*} queryObject
   * @memberof ShuyouAdminFileListController
   */
  @Post('/deleteAllByTaskId')
  async deleteAllByTaskId(@Body(ALL) queryObject) {
    const { task_id } = queryObject
    const exists = await this.ShuyouFileListService.deleteAllByTaskId(task_id)
    if (exists.code == 1) {
      let deleteOperations = []
      var accessKey = aKey;
      var secretKdy = sKdy;
      var mac = new qiNiu.auth.digest.Mac(accessKey, secretKdy);
      var config = new qiNiu.conf.Config();
      // 空间对应的机房
      // config.zone = qiNiu.zone.Zone_z2; //华南机房
      var bucketManager = new qiNiu.rs.BucketManager(mac, config);
      //===============================
      var bucket = bucket0;
      await ykhForeach(exists.data, async (item, index) => {
        deleteOperations.push(qiNiu.rs.deleteOp(bucket, item.qiniuKey))
      })
      //批量删除七牛云文件
      bucketManager.batch(deleteOperations, function (err, respBody, respInfo) {
        if (err) {
          console.log(err);
          //throw err;
        } else {
          // 200 is success, 298 is part success
          if (parseInt(respInfo.statusCode) / 100 == 2) {
            respBody.forEach(function (item) {
              // if (item.code == 200) {
              //   // console.log(item.code + "\tsuccess");
              // } else {
              //   // console.log(item.code + "\t" + item.data.error);
              // }
            });
          } else {
            // console.log(respInfo.deleteusCode);
            // console.log(respBody);
          }
        }
      });
    }
  }



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


