'use strict';
const Service = require('egg').Service;
const R = require('ramda');
class ProductNewService extends Service {
  //
  async getLoanChannelSuitOptions() {
    const { ctx } = this;
    const user_id = ctx.userId;
    const app_user_id = ctx.appUserId;
    const recommendSort = function(a, b) {
      if (a.sort === b.sort) {
        return b.business_id - a.business_id;
      }
      return a.sort - b.sort;
    };
    const credit_loans = await ctx.service.gjj.product.getAllProductsByType(1);
    const common_loans = await ctx.service.gjj.product.getAllProductsByType(4);
    const result_loans = R.sort(recommendSort)(credit_loans.concat(common_loans));
    const credit_loans_ids = R.pluck('business_id', credit_loans);
    const common_loans_ids = R.pluck('business_id', common_loans);
    const result_loans_ids = R.pluck('business_id', result_loans);
    const default_options = {
      id: -1,
      key: 'loan_all',
      title: '全部',
      description: '全部',
      _children: [],
    };
    const children = [
      {
        id: -2,
        title: '全部',
        quality: result_loans_ids,
      },
    ];
    if (app_user_id) {
      const userGjj = await ctx.helper.send_request(
        this.config.NODE_BASE_URL + '/cassandra-server/gjj/list/' + user_id,
        {},
        { method: 'GET' }
      );
      if (userGjj.status === 200 && !ctx.isEmpty(userGjj.data.ret)) {
        children.push({
          id: -3,
          title: '最适合您的',
          quality: await ctx.service.gjj.product.getSuitLoans(),
        });
      } else {
        children.push({
          id: -4,
          title: '51公积金贷',
          quality: credit_loans_ids.concat(common_loans_ids),
        });
        children.push({
          id: -5,
          title: '普通贷',
          quality: common_loans_ids,
        });
      }
    } else {
      children.push({
        id: -4,
        title: '51公积金贷',
        quality: credit_loans_ids.concat(common_loans_ids),
      });
      children.push({
        id: -5,
        title: '普通贷',
        quality: common_loans_ids,
      });
    }
    default_options._children = children;

    return default_options;
  }

  // 贷款频道首页热门推荐
  async getLoanHomeList() {
    const { ctx } = this;
    const recommendSort = function(a, b) {
      if (a.sort === b.sort) {
        return b.business_id - a.business_id;
      }
      return a.sort - b.sort;
    };
    const credit_loans = await ctx.service.gjj.product.getAllProductsByType(1);
    const common_loans = await ctx.service.gjj.product.getAllProductsByType(4);
    const result_loans = R.sort(recommendSort)(credit_loans.concat(common_loans));
    const ret = R.take(6)(result_loans);
    return ret;
  }

}

module.exports = ProductNewService;
