
'use strict';

const Service = require('egg').Service;
const moment = require('moment');
const R = require('ramda');

const MODE = [
  {
    id: 0,
    name: '全部',
    value: 0,
  }, {
    id: 1,
    name: '直播',
    value: 1,
  }, {
    id: 2,
    name: '录播(动画)',
    value: 2,
  }, {
    id: 3,
    name: '录播(真人)',
    value: 3,
  }, {
    id: 4,
    name: 'APP',
    value: 4,
  }, {
    id: 5,
    name: '小程序',
    value: 5,
  },
];

const PRICE_TYPE = [
  {
    id: 0,
    name: '全部',
    value: 0,
  }, {
    id: 1,
    name: '免费公益课',
    value: 1,
  }, {
    id: 2,
    name: '低价体验课',
    value: 2,
  }, {
    id: 3,
    name: '正价课',
    value: 3,
  },
];

class OptionService extends Service {
  async getOptions() {
    const { ctx } = this;
    // 分类
    const categoryList = await ctx.classModel.V5.CourseV5Category.findAll({ where: { type: 1, status: 1, is_deleted: 0 }, order: [[ 'sort', 'asc' ]], attributes: [ 'id', 'name' ], raw: true });
    categoryList.forEach(e => {
      e.value = e.id;
    });
    categoryList.unshift({ id: 0, name: '全部', value: 0 });
    // 年龄段
    const ageList = await ctx.classModel.V5.CourseV5Age.findAll({ where: { status: 1, is_deleted: 0 }, order: [[ 'sort', 'asc' ]], attributes: [ 'id', 'name' ], raw: true });
    ageList.forEach(e => {
      e.value = e.id;
    });
    ageList.unshift({ id: 0, name: '全部', value: 0 });
    // // 课程班型
    // const typeList = await ctx.classModel.V5.CourseV5Type.findAll({ where: { status: 1, is_deleted: 0 }, order: [ ['sort', 'asc'] ], attributes: [ 'id', 'name' ], raw: true });
    // typeList.forEach(e => {
    //   e.value = e.id;
    // });
    // typeList.push({ id: 0, name: '全部', value: 0 });
    // // 授课频次
    // const frequencyList = await ctx.classModel.V5.CourseV5Frequency.findAll({ where: { status: 1, is_deleted: 0 }, order: [ ['sort', 'asc'] ], attributes: [ 'id', 'name' ], raw: true });
    // frequencyList.forEach(e => {
    //   e.value = e.id;
    // });
    // frequencyList.push({ id: 0, name: '全部', value: 0 });

    const options = [
      { title: '所在班级', value: ageList, alias: 'age' },
      { title: '科目类型', value: categoryList, alias: 'category' },
      { title: '课程状态', value: MODE, alias: 'mode' },
      { title: '课程类型', value: PRICE_TYPE, alias: 'price_type' },
    ];

    const ret = {
      list: options,
    };
    return ret;
  }

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

    const banners = await ctx.classModel.V5.CourseBanner.findAll({ where: { type_id: bannerType.id, status: 1, is_deleted: 0 }, order: [[ 'sort', 'asc' ]], row: true });

    const results = [];
    for (const v of banners) {
      results.push({
        id: v.id,
        title: v.title,
        url: v.url,
        link: v.link,
        created_time: v.created_time,
      });
    }
    const ret = {
      list: results,
    };

    return ret;
  }


  // 获取分类
  async getCategoryList(input) {
    const { ctx } = this;
    const parentId = Number(input.parent_id) || 0;
    const type = Number(input.type) || 1;

    const filter = { where: { type, is_deleted: 0, status: 1 }, order: [[ 'sort', 'asc' ], [ 'id', 'asc' ]] };
    if (type === 2) {
      filter.where.parent_id = parentId;
    }

    const categoryList = await ctx.classModel.V5.CourseV5Category.findAll(filter);

    const filterIds = [];
    // 智能选课要判断年龄
    if (type === 3) {
      const userBabyInfo = await ctx.classModel.V5.CourseV5UserBaby.findOne({ where: { user_uuid: ctx.userUuid, status: 1, is_deleted: 0 } });
      if (!ctx.isEmpty(userBabyInfo)) {
        switch (userBabyInfo.baby_age) {
          case 1:
            filterIds.push(17);
            break;
          case 2:
            filterIds.push(17);
            break;
          default:
            break;
        }
      }
    }
    // 智能选课要判断是否有报告
    let reportFilterIds = [];
    let userReportList = [];
    if (type === 3) {
      userReportList = await ctx.classModel.V5.CourseUserReport.findAll({ where: { user_uuid: ctx.userUuid, status: 1, is_deleted: 0 }, attributes: [ 'id', 'cat_id' ], raw: true });
      reportFilterIds = R.pluck('cat_id', userReportList);
      userReportList = _.groupBy(userReportList, 'cat_id');
    }

    const results = [];
    for (const v of categoryList) {
      results.push({
        id: v.id,
        type: v.type,
        parent_id: v.parent_id,
        name: v.name,
        selected_icon: v.selected_icon,
        unselected_icon: v.unselected_icon,
        is_open: v.is_open,
        url: v.url,
        is_valid: filterIds.includes(v.id) ? 0 : 1,
        report_id: reportFilterIds.includes(v.id) ? (ctx.isEmpty(userReportList[v.id]) ? 0 : userReportList[v.id][0].id) : 0,
        sort: v.sort,
      });
    }

    const ret = {
      list: results,
    };

    return ret;
  }


  // 获取反馈类型列表
  async getFeedbackTypeList() {
    const ret = {
      list: [
        { id: 1, name: '使用疑问' },
        { id: 2, name: '功能故障' },
        { id: 3, name: '数据错误' },
        { id: 4, name: '投诉' },
        { id: 5, name: '提建议' },
      ],
    };

    return ret;
  }

  // 提交反馈
  async addFeedback(input) {
    const { ctx } = this;

    const data = {
      user_uuid: ctx.userUuid,
      type: input.type,
      content: input.content,
      images: input.images,
      status: 1,
      is_deleted: 0,
      created_time: moment().format('YYYY-MM-DD HH:mm:ss'),
    };

    await ctx.classModel.V5.CourseFeedback.create(data);

    return { result: true };
  }

  // 获取分类提示（年龄不符合）
  async getCategoryTip(input) {
    const { ctx } = this;
    const catId = Number(input.cat_id) || 0;

    const tip = await ctx.classModel.V5.CourseV5CategoryTip.findOne({ where: { cat_id: catId, status: 1, is_deleted: 0 } });
    if (ctx.isEmpty(tip)) {
      return {};
    }
    const category = await ctx.classModel.V5.CourseV5Category.findOne({ where: { id: catId }, attributes: [ 'name' ] });
    const userBabyInfo = await ctx.classModel.V5.CourseV5UserBaby.findOne({ where: { user_uuid: ctx.userUuid, status: 1, is_deleted: 0 } });
    let age = ctx.isEmpty(userBabyInfo) ? 0 : userBabyInfo.baby_age;
    age = await ctx.classModel.V5.CourseV5Age.findOne({ where: { id: age }, attributes: [ 'name' ] });
    age = ctx.isEmpty(age) ? '' : age.name;

    const ret = ctx.isEmpty(tip) ? {} : {
      id: tip.id,
      category: ctx.isEmpty(category) ? '' : category.name,
      content: `您的孩子当前处于【${age}】阶段，` + tip.content,
      advice: tip.advice,
      button_text: tip.button_text,
      button_url: tip.button_url,
    };

    return ret;
  }
}

module.exports = OptionService;
