/*
 * @Author: YKH
 * @Date: 2021-12-08 10:26:27
 * @LastEditTime: 2022-10-08 14:44:52
 * @Description:
 * @FilePath: \cool-admin-3.x\cool-admin-midway-master\src\app\modules\shuyou\controller\admin\rent_computer.ts
 */
import { ALL, Body, Inject, Post, Provide } from '@midwayjs/decorator';
import {
  CoolController,
  BaseController,
  CoolCommException,
} from 'midwayjs-cool-core';
import { ShuyouRentComputerEntity } from '../../entity/rent_computer';
import { ShuyouRentComputerService } from '../../service/rent_computer';
import { ILogger } from '@midwayjs/logger';
import { Utils } from '../../../../comm/utils';
// import xlsx from 'node-xlsx';
// import fs from 'fs';

import xlsx = require('node-xlsx');
// import fs = require('fs');
var path = require('path');

/**
 * 租机
 */
@Provide()
@CoolController({
  // 添加通用CRUD接口
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  // 设置表实体
  entity: ShuyouRentComputerEntity,
  service: ShuyouRentComputerService,
  // // 向表插入当前登录用户ID
  // insertParam: async (ctx: Context) => {
  //   return {
  //     userId: ctx.admin.userId,
  //   };
  // },
  // // info接口忽略价格字段
  // infoIgnoreProperty: ['price'],

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

  @Inject()
  ShuyouRentComputerService: ShuyouRentComputerService;

  @Inject()
  utils: Utils;

  // 换编
  @Post('/replaceNum')
  async replaceNum(@Body(ALL) queryObject) {
    // this.logger.info(queryObject);
    let reqmsg = await this.ShuyouRentComputerService.replaceNum(queryObject);
    if (reqmsg.code == 1000) {
      return await this.ok({ code: 1, message: reqmsg.data });
    } else {
      return await this.fail(reqmsg.data, -1);
    }
  }

  // 退租
  @Post('/rentingOut')
  async rentingOut(@Body(ALL) queryObject) {
    // this.logger.info(queryObject);
    let reqmsg = await this.ShuyouRentComputerService.rentingOut(queryObject);
    if (reqmsg.code == 1000) {
      return await this.ok({ code: 1, message: reqmsg.data });
    } else {
      return await this.fail(reqmsg.data, -1);
    }
  }

  // 获取租机列表
  @Post('/rentComputerList')
  async rentComputerList() {
    let list = await this.ShuyouRentComputerService.rentComputerList();
    return await this.ok({ code: 1, data: list });
  }
  // 租机续费
  @Post('/renew')
  async renew(@Body(ALL) queryObject) {
    // this.logger.info(queryObject);
    let reqmsg = await this.ShuyouRentComputerService.renew(queryObject);
    if (reqmsg.code == 1000) {
      return await this.ok({ code: 1, message: reqmsg.data });
    } else {
      return await this.fail(reqmsg.data, -1);
    }
  }
  // 租机下架
  @Post('/offShelf')
  async offShelf(@Body(ALL) queryObject) {
    this.logger.info(queryObject);
    let reqmsg = await this.ShuyouRentComputerService.offShelf(queryObject);
    if (reqmsg.code == 1000) {
      return await this.ok({ code: 1, message: reqmsg.data });
    } else {
      return await this.fail(reqmsg.data, -1);
    }
  }
  @Post('/batchImport')
  async batchImport(@Body(ALL) queryObject) {
    console.log(queryObject);

    const { fileaddress, rent_person_id, shop_id } = queryObject;
    // console.log(fileaddress._value);
    // const filename = fileaddress._value.split('uploads')[1];
    // console.log(filename);

    const filename = fileaddress.split('uploads')[1];
    // 解析文件
    // const data = xlsx.parse(filename);
    // console.log(data);

    // 读取xlsx，此处可以按照需求更改自己要读的表格
    var abcpath = path.join(
      __dirname,
      '../../../../../../public/uploads/' + filename
    );
    const sheets = xlsx.parse(abcpath);
    // console.log(sheets);
    let info_text;
    await ykhForeach(sheets, async (element, index) => {
      const name = element.name;
      const sheetData = element.data;
      await ykhForeach(sheetData, async (item, order) => {
        if (order == 0) {
          return;
        }
        // console.log(item[0]);
        const price_type_text = item[4];
        let price_type;
        let rent_price;
        let rent_price_day = 0;
        const array_price_type_text = price_type_text.split('元/');
        if (
          array_price_type_text.length < 2 &&
          !isNaN(parseFloat(array_price_type_text[0])) &&
          isFinite(array_price_type_text[0])
        ) {
          throw new CoolCommException('[收费标准]有错误项~');
        }
        if (array_price_type_text[1] == '月') {
          price_type = 2;
          rent_price = array_price_type_text[0];
          rent_price_day = parseInt(rent_price) / 30;
        } else if (array_price_type_text[1] == '周') {
          price_type = 1;
          rent_price = array_price_type_text[0];
          rent_price_day = parseInt(rent_price) / 7;
        } else {
          price_type = 0;
          rent_price = array_price_type_text[0];
          rent_price_day = parseInt(rent_price);
        }
        const set_meal = name + item[1];
        let pay_method = 0;
        if (name == '逍遥') {
          pay_method = 1;
        }
        // this.logger.info(item[2]);
        // this.logger.info(this.utils.excelFormatDate(item[2], '/'));
        // throw new CoolCommException(this.utils.excelFormatDate(item[2], '/'));
        // pc_num,pc_name,rent_person_id,shop_id,set_meal,rent_start,rent_duration,rent_end,price_type,rent_price,rent_price_day,pay_method,is_expire
        if (index == 0 && order == 1) {
          info_text =
            `('` +
            item[0] +
            `',` +
            `'` +
            item[0] +
            `',` +
            `'` +
            rent_person_id +
            `',` +
            `'` +
            shop_id +
            `',` +
            `'` +
            set_meal +
            `',` +
            `'` +
            this.utils.excelFormatDate(item[2], '/') +
            `',` +
            `'` +
            item[5] +
            `',` +
            `'` +
            this.utils.excelFormatDate(item[3], '/') +
            `',` +
            `'` +
            price_type +
            `',` +
            `'` +
            rent_price +
            `',` +
            `'` +
            rent_price_day +
            `',` +
            `'` +
            pay_method +
            `',` +
            `'0')`;
        } else {
          info_text +=
            `,('` +
            item[0] +
            `',` +
            `'` +
            item[0] +
            `',` +
            `'` +
            rent_person_id +
            `',` +
            `'` +
            shop_id +
            `',` +
            `'` +
            set_meal +
            `',` +
            `'` +
            this.utils.excelFormatDate(item[2], '/') +
            `',` +
            `'` +
            item[5] +
            `',` +
            `'` +
            this.utils.excelFormatDate(item[3], '/') +
            `',` +
            `'` +
            price_type +
            `',` +
            `'` +
            rent_price +
            `',` +
            `'` +
            rent_price_day +
            `',` +
            `'` +
            pay_method +
            `',` +
            `'0')`;
        }
      });
    });
    // this.logger.warn(info_text);
    let reqmsg = await this.ShuyouRentComputerService.batchAdd(info_text);
    // this.logger.info('本次导入成功' + reqmsg.affectedRows + '条');
    return this.ok({
      code: 1,
      message: '本次导入成功' + reqmsg.affectedRows + '条',
    });
  }
}
// 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++;
  }
};
