
'use strict';

const Service = require('egg').Service;

const AGE_CATS = [
  { id: -2, name: '全部', value: 0 },
  { id: -3, name: '3岁以下', value: 3 },
  { id: -4, name: '4岁', value: 4 },
  { id: -5, name: '5岁', value: 5 },
  { id: -6, name: '6岁', value: 6 },
  { id: -7, name: '7岁', value: 7 },
  { id: -8, name: '8岁', value: 8 },
  { id: -9, name: '9岁', value: 9 },
  { id: -10, name: '10岁', value: 10 },
  { id: -11, name: '11岁', value: 11 },
  { id: -12, name: '12岁', value: 12 },
  { id: -13, name: '12岁以上', value: 13 },
];

const INSTITUTION_TYPE = [
  { id: -14, name: '全部', value: '' },
  { id: -15, name: '品牌', value: '品牌' },
];

const DISTANCES = [
  { id: -16, name: '全部', value: 0 },
  { id: -17, name: '500米以内', value: 500 },
  { id: -18, name: '1公里以内', value: 1000 },
  { id: -19, name: '2公里以内', value: 2000 },
  { id: -20, name: '3公里以内', value: 3000 },
  { id: -21, name: '5公里以内', value: 5000 },
];

class OptionService extends Service {


  /**
     * 我的信用首页
     */
  async getOptions() {

    const { ctx } = this;
    const cats = await ctx.classModel.V1.CourseCat.findAll({ where: { status: 1, is_deleted: 0 } });
    const tree_cats = this.getTrees(cats, 0); 

    const options = {
      cats: tree_cats,
      ages: AGE_CATS,
      institutions: INSTITUTION_TYPE,
      distances: DISTANCES,
    };
    return options;
  }

  getTrees(data, rootId) {
    const ret = [];
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      if (node.parent_id == rootId) {
        const newNode = {};
        // if (node.parent_id == 0) newNode._child.push({ id: 0, name: '全部', value: '' });
        newNode.id = node.id;
        newNode.name = node.name;
        newNode.tips = node.tips;
        newNode.image = node.image;
        newNode.color = node.color;
        newNode.level = node.level;
        newNode.value = node.id;
        newNode._child = this.getTrees(data, node.id);
        if (newNode._child.length !== 0) newNode._child.unshift({ id: 0, name: '全部', value: node.id });
        ret.push(newNode);
      }
    }
    return ret;
  }

  async getBanners(alias) {
    const { ctx } = this;
    const bannerType = await ctx.classModel.V1.CourseBannerType.findOne({ where: { alias, status: 'online', is_deleted: 0 }, row: true });
    if (ctx.isEmpty(bannerType)) {
      ctx.failed('数据不存在');
    }

    const banners = await ctx.classModel.V1.CourseBanner.findAll({ where: { type_id: bannerType.id, status: 'online', is_deleted: 0 }, order: [[ 'sort', 'asc' ]], row: true });
    const ret = {
      results: banners,
      count: banners.length,
    };

    return ret;
  }
}

module.exports = OptionService;
