/*
 * @Author: 倚楼听风雨 18408246387@163.com
 * @Date: 2022-09-22 14:50:54
 * @LastEditors: 倚楼听风雨 18408246387@163.com
 * @LastEditTime: 2022-09-27 18:03:18
 * @FilePath: \cool-admin-3.x\cool-admin-midway-master\src\app\modules\task\service\rent_computer.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Inject, Logger, Provide } from '@midwayjs/decorator';
import { BaseService } from 'midwayjs-cool-core';
import { ILogger } from '@midwayjs/logger';
import { Utils } from '../../../comm/utils';
import * as _ from 'lodash';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
// import { ShuyouUtilsService } from '../../shuyou/service/utils';
import { ShuyouRentComputerEntity } from '../../shuyou/entity/rent_computer';
import { ShuyouRentComputerService } from '../../shuyou/service/rent_computer';
import { ShuyouRentLedgerComputerEntity } from '../../shuyou/entity/rent_ledger_computer';
// import { ShuyouRentLedgerComputerService } from '../../shuyou/service/rent_ledger_computer';

/**
 * 租机定时任务
 */
@Provide()
export class RentComputerTaskService extends BaseService {
  @Logger()
  logger: ILogger;

  @Inject()
  utils: Utils;

  @InjectEntityModel(ShuyouRentComputerEntity)
  ShuyouRentComputerEntity: Repository<ShuyouRentComputerEntity>;

  @Inject()
  ShuyouRentComputerService: ShuyouRentComputerService;

  @InjectEntityModel(ShuyouRentLedgerComputerEntity)
  ShuyouRentLedgerComputerEntity: Repository<ShuyouRentLedgerComputerEntity>;

  // @Inject()
  // ShuyouRentLedgerComputerService: ShuyouRentLedgerComputerService;

  /**
   * 检查是否有电脑到期，修改租机状态
   * @memberof RentComputerTaskService
   */
  async checkIsExpire() {
    let updateTime = new Date();
    this.logger.info('checkIsExpire>>>' + updateTime);
    const sql = `
      SELECT pc_num,rent_start,rent_end,is_expire FROM shuyou_rent_computer
    `;
    // console.log(sql)
    const accList = await this.nativeQuery(sql);
    const overtime = 24 * 60 * 60 * 1000;
    let is_expire = 0;
    await ykhForeach(accList, async (item, index) => {
      if (Date.parse(item.rent_end) < updateTime.getTime()) {
        // console.log('已经到期');
        //已经到期
        is_expire = 1;
      } else if (Date.parse(item.rent_end) - updateTime.getTime() <= overtime) {
        //明日到期
        is_expire = 2;
      } else {
        //在租期中
        is_expire = 0;
      }
      const ShuyouRentComputerEntity =
        await this.ShuyouRentComputerEntity.findOne({ pc_num: item.pc_num });
      if (ShuyouRentComputerEntity) {
        ShuyouRentComputerEntity.is_expire = is_expire;
        await this.ShuyouRentComputerEntity.save(ShuyouRentComputerEntity);
      }
    });

    return 'checkIsExpire  SUCCESS>>>' + updateTime;
  }

  /***
   * 定时生成今日租机台账表（财务）
   */
  async updateRentLedger() {
    let updateTime = this.utils.formatDateTime(new Date());
    this.logger.info('updateRentLedger>>>' + updateTime);
    const sql = `
          SELECT
            a.pc_num,a.pc_name, a.shop_id,a.set_meal,a.rent_start,a.rent_duration,a.rent_end,a.price_type,a.rent_price,a.rent_price_day,
            a.pay_method,a.is_expire,a.rent_price_used,a.remark,
            b.name as shop_name
          FROM
            shuyou_rent_computer a
            LEFT JOIN shuyou_rent_computer_shop b ON a.shop_id = b.id
          WHERE
            a.is_expire != 1
            and a.is_offShelf = 0
          ORDER BY a.pc_num
  `;
    // console.log(sql)
    const computerList = await this.nativeQuery(sql);
    await ykhForeach(computerList, async (item, index) => {
      // this.logger.info(item.pc_num);
      let ledger_object = {
        new_date: this.utils.formatDate(new Date()),
        pc_num: item.pc_num,
        pc_name: item.pc_name,
        shop_id: item.shop_id,
        set_meal: item.set_meal,
        rent_start_then: item.rent_start,
        rent_duration_then: item.rent_duration,
        rent_end_then: item.rent_end,
        price_type: item.price_type,
        rent_price_then: item.rent_price,
        rent_price_day: item.rent_price_day,
        pay_method: item.pay_method,
        is_expire: item.is_expire,
        rent_price_used_then: 0,
        remark: item.remark,
      };
      const ShuyouRentLedgerComputerEntity =
        await this.ShuyouRentLedgerComputerEntity.findOne({
          pc_num: item.pc_num,
          new_date: this.utils.formatDate(new Date()),
          shop_id: item.shop_id,
        });
      if (!ShuyouRentLedgerComputerEntity) {
        const yesterdayInfo = await this.ShuyouRentLedgerComputerEntity.findOne(
          {
            pc_num: item.pc_num,
            new_date: this.utils.getNextDate(new Date(), -1),
            shop_id: item.shop_id,
          }
        );
        if (yesterdayInfo) {
          ledger_object.rent_price_used_then =
            parseFloat(yesterdayInfo.rent_price_used_then + '') +
            parseFloat(item.rent_price_day);
        } else {
          ledger_object.rent_price_used_then = parseFloat(item.rent_price_day);
        }
        await this.ShuyouRentLedgerComputerEntity.insert(ledger_object);
      }
    });
    return 'updateRentLedger  SUCCESS>>>' + updateTime;
  }
}

//==========================================================================================

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