'use strict';
const Base = require('../base');
const { setInterval } = require('timers');

// 商品接口控制器
module.exports = class RelInviterController extends Base {

  /**
   * 接口测试函数
   * http://ysjj.sizhijie.com/oneshop/api/test
   * @return {Promise<*>}
   */
  async test() {
    const that = this;
    // const stateStr = that.app.szjcomo.base64_encode('http://test.enroll.sizhijie.com/#/shop/category?category_id=11');
    // const hh = that.app.szjcomo.base64_decode(stateStr);

    // const stateStr = that.app.szjcomo.base64_encode('http://ysjj.sizhijie.com/#/shop/officeHome');
    // console.log(stateStr);

    // https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7713e08a353ffcd7&redirect_uri=http%3A%2F%2Fysjj.sizhijie.com%2F%23%2Fshop%2Fwxauth&response_type=code&scope=snsapi_userinfo&state=aHR0cDovL3lzamouc2l6aGlqaWUuY29tLyMvc2hvcC9vZmZpY2VIb21l#wechat_redirect

    // 2023/2/21 获取当前待发的佣金总额
    const commissionResult = await that.getCurrentCommission();

    // 2023/2/21 替换更新openid
    // await that.changOpenid();

    // 2023/3/5 分佣发放
    // that.service.commission.orderCommissionDispatchAfterPay(17);

    // 2023/3/5 餐币发放
    // const dispatchResult = that.service.diningCoin.orderDiningCoinDispatchAfterPay(362);

    // const bodyData = {};
    // const response = await that.app.curl('http://127.0.0.1:8105/oneshop/api/redEnvelopeProducts', {
    //   method: 'GET', dataType: 'json', contentType: 'json', data: bodyData,
    // });


    // const response = await that.getCouldCashCommission(10);

    return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', { commissionResult }, false));
  }

  async changOpenid() {
    const that = this;
    const page = 4;
    const limit = 100;
    const users = await that.app.model.Users.findAll({
      offset: (page - 1) * limit, limit,
      attributes: [ 'nickname', 'openid' ],
      order: [[ 'user_id', 'asc' ]],
    });
    const openids = [];
    for (let i = 0; i < users.length; i++) {
      openids.push(users[i].openid);
    }
    let index = 0;
    const interval = setInterval(() => {
      const that = this;
      const data = [];
      data.push(openids[index]);
      console.log('openids:');
      console.log(data);
      that.service.wechat.changeOpenid(data, '');
      index += 1;
      if (index >= openids.length) {
        clearInterval(interval);
      }
    }, 350);
  }

  async getCurrentCommission() {
    const that = this;
    const seq = that.app.Sequelize;
    const selectBean = await that.app.comoBean.instance({}, {
      where: { user_id: 10 }, // type-1提现失败类型
      include: [ {
        model: that.app.model.Orders,
        where: { order_status: { [seq.Op.lte]: 2 } },
        attributes: [ 'order_id', 'order_status', 'order_amount', ],
        as: 'order'
      } ],
      // attributes: [ 'user_id', [ seq.fn('sum', seq.col('commission')), 'all_cash' ] ],
    });
    return await that.service.base.select(selectBean, that.app.model.UsersCommissionLogs, '查询佣金失败,请稍候重试', false, true);
  }

  async selectInfo(order_id) {
    const that = this;
    const options = {
      where: { order_id }, include: [
        { model: that.app.model.PaysConfig, attributes: [ 'pay_name' ], as: 'pays_config' },
        { model: that.app.model.Users, as: 'users', attributes: [ 'account_name', 'nickname' ] },
        {
          model: that.app.model.OrdersProducts, as: 'orders_products', attributes: {
            exclude: [ 'product_id', 'create_time', 'order_id', 'activity_name', 'activity_id', 'activity_desc' ],
          },
        },
        { model: that.app.model.Payments, as: 'payments', attributes: [ 'create_time' ], required: false },
      ], attributes: {
        exclude: [ 'seller_remarks', 'province_id', 'city_id', 'county_id', 'shipping_id',
          'shipping_fee', 'activity_id', 'activity_name', 'activity_desc' ],
      },
    };
    const selectBean = await that.app.comoBean.instance({}, options);
    return await that.service.base.select(selectBean, that.app.model.Orders, '查询订单详情失败,请稍候重试', false, false);
  }

  /**
   * 手动执行一次每日定时任务(完成订单分佣)
   * http://test.enroll.sizhijie.com/oneshop/api/executeTask
   * @return {Promise<void>}
   */
  async executeSchedule() {
    const that = this;
    await that.service.inviter.executeSchedule();
    return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', { msg: '手动执行每日定时任务(完成订单分佣)一次' }, false));
  }
};