
'use strict';

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

class InstitutionSubService extends Service {
  // 课程列表
  async getClassList(input) {
    const { ctx } = this;
    const page = Number(input.page) || 1;
    const page_size = Number(input.page_size) || 10;
    const offset = (page - 1) * page_size;
    const attributes = [ 'id', 'institution_id', 'name', 'logo', 'age', 'price', 'price_type', 'mode', 'time', 'class_amount', 'multi_classes', 'cycle', 'description', 'sort' ];
    const filter = { where: { status: 1, is_deleted: 0 }, order: [[ 'sort', 'asc' ], [ 'id', 'desc' ]], page_size, offset, attributes, raw: true };
    let filterIds = [];
    let flag = false;
    // 年龄筛选
    if (!ctx.isEmpty(input.age)) {
      const filterByAge = await ctx.classModel.V5.CourseV5ClassToAge.findAll({ where: { age_id: input.age, status: 1, is_deleted: 0 }, attributes: [ 'class_id' ] });
      filterIds = R.pluck('class_id', filterByAge);
      flag = true;
    }
    // 科目类型
    if (!ctx.isEmpty(input.category)) {
      const filterByCategory = await ctx.classModel.V5.CourseV5ClassToCat.findAll({ where: { cat_id: input.category, status: 1, is_deleted: 0 }, attributes: [ 'class_id' ] });
      filterIds = flag ? _.intersection(filterIds, R.pluck('class_id', filterByCategory)) : R.pluck('class_id', filterByCategory);
      flag = true;
    }
    // 课程状态
    if (!ctx.isEmpty(input.mode)) {
      filter.where.mode = input.mode;
    }
    // 课程类型
    if (!ctx.isEmpty(input.price_type)) {
      filter.where.price_type = input.price_type;
    }
    if (flag) {
      filter.where.id = { $in: filterIds };
    }

    const classList = await ctx.classModel.V5.CourseV5Class.findAndCountAll(filter);
    if (classList.count === 0) {
      return { list: [], total_count: 0, page, page_size };
    }

    // 用户收藏的课程
    const userCollection = await ctx.classModel.V5.CourseUserCollection.findAll({ where: { user_uuid: ctx.userUuid, is_deleted: 0, type: 3 }, raw: true });
    const collectedIds = R.pluck('type_id', userCollection);
    for (const i in classList.rows) {
      classList.rows[i].is_collected = collectedIds.includes(classList.rows[i].id) ? 1 : 0;
    }

    // 获取课程类型
    let classToCategory = await ctx.classModel.V5.CourseV5ClassToCat.findAll({ where: { class_id: { $in: R.pluck('id', classList.rows) } }, attributes: [ 'cat_id', 'class_id' ] });
    let categoryList = await ctx.classModel.V5.CourseV5Category.findAll({ where: { id: { $in: R.pluck('cat_id', classToCategory) } }, attributes: [ 'id', 'name' ] });
    classToCategory = _.groupBy(classToCategory, 'class_id');
    categoryList = _.groupBy(categoryList, 'id');

    // 获取机构
    let institutionList = await ctx.classModel.V5.CourseV5Institution.findAll({ where: { id: { $in: R.pluck('institution_id', classList.rows) } }, attributes: [ 'id', 'name' ] });
    institutionList = _.groupBy(institutionList, 'id');

    for (const i in classList.rows) {
      const classCategoryList = [];
      if (!ctx.isEmpty(classToCategory[classList.rows[i].id])) {
        for (const j of classToCategory[classList.rows[i].id]) {
          if (!ctx.isEmpty(categoryList[j.cat_id])) {
            classCategoryList.push({
              id: j.cat_id,
              name: categoryList[j.cat_id][0].name,
            });
          }
        }
      }
      classList.rows[i].category = classCategoryList;
      classList.rows[i].institution_name = ctx.isEmpty(institutionList[classList.rows[i].institution_id]) ? '' : institutionList[classList.rows[i].institution_id][0].name;
    }

    const ret = {
      list: classList.rows,
      total_count: classList.count,
      page,
      page_size,
    };
    return ret;
  }


  // 课程详情
  async getClassInfo(id) {
    const { ctx } = this;
    const attributes = [ 'id', 'institution_id', 'name', 'logo', 'age', 'price', 'price_type', 'mode', 'time', 'class_amount', 'multi_classes', 'cycle', 'description', 'sort' ];
    const classInfo = await ctx.classModel.V5.CourseV5Class.findOne({ where: { id, status: 1, is_deleted: 0 }, attributes, raw: true });
    if (ctx.isEmpty(classInfo)) {
      ctx.failed('数据不存在');
    }


    const isCollected = await ctx.classModel.V5.CourseUserCollection.findOne({ where: { user_uuid: ctx.userUuid, type: 3, type_id: id, is_deleted: 0 } });
    classInfo.is_collected = ctx.isEmpty(isCollected) ? 0 : 1;

    // 额外字段
    const classColumns = await ctx.classModel.V5.CourseV5ClassToColumn.findAll({ where: { class_id: id, status: 1, is_deleted: 0 } });
    let columnList = await ctx.classModel.V5.CourseV5Column.findAll({ where: { id: { $in: R.pluck('column_id', classColumns) }, status: 1, is_deleted: 0 }, attributes: [ 'id', 'name' ], raw: true });
    columnList = _.groupBy(columnList, 'id');
    for (const i in columnList) {
      columnList[i][0].value = [];
    }

    // 机构数据
    const institution = await ctx.classModel.V5.CourseV5Institution.findOne({ where: { id: classInfo.institution_id } });

    // 学员成果
    const studentWorks = await ctx.classModel.V5.CourseV5StudentWorks.findAll({ where: { class_id: id, status: 1, is_deleted: 0 }, order: [[ 'sort', 'asc' ]], attributes: [ 'id', 'name', 'sub_title', 'description', 'video_url', 'cover_image' ] });

    // 顶部图片
    const imageList = await ctx.classModel.V5.CourseImages.findAll({ where: { type: 5, type_id: id, status: 'online', is_deleted: 0 }, order: [[ 'sort', 'asc' ]] });
    const images = [];
    for (const v of imageList) {
      images.push({
        id: v.id,
        url: v.is_video > 0 ? v.video_url : v.image_url,
        is_video: v.is_video,
      });
    }

    // 课程分类
    const categoryList = await ctx.classModel.V5.CourseV5ClassToCat.findAll({ where: { class_id: id, status: 1, is_deleted: 0 }, attributes: [ 'cat_id' ] });
    const category = await ctx.classModel.V5.CourseV5Category.findAll({ where: { id: { $in: R.pluck('cat_id', categoryList) } }, attributes: [ 'id', 'name' ] });


    const columns = [];
    for (const v of classColumns) {
      if (!ctx.isEmpty(columnList[v.column_id])) {
        columnList[v.column_id][0].value.push({
          id: v.id,
          value: v.value,
        });
      }
    }
    for (const i in columnList) {
      if (columnList[i][0].value.length > 0) {
        columns.push(columnList[i][0]);
      }
    }
    classInfo.columns = columns;

    classInfo.student_works = studentWorks;
    classInfo.images = images;
    classInfo.category = category;
    classInfo.institution_name = ctx.isEmpty(institution) ? '' : institution.name;
    classInfo.institution_logo = ctx.isEmpty(institution) ? '' : institution.logo;
    classInfo.institution_description = ctx.isEmpty(institution) ? '' : institution.description;

    return classInfo;
  }

  // 用户收藏课程列表
  async getCollectionClassList(input) {
    const { ctx } = this;
    const page = Number(input.page) || 1;
    const page_size = Number(input.page_size) || 10;
    const offset = (page - 1) * page_size;
    const attributes = [ 'id', 'institution_id', 'name', 'logo', 'age', 'price', 'price_type', 'mode', 'time', 'class_amount', 'multi_classes', 'cycle', 'description', 'sort' ];

    // 用户收藏的课程
    const userCollection = await ctx.classModel.V5.CourseUserCollection.findAndCountAll({ where: { user_uuid: ctx.userUuid, is_deleted: 0, type: 3 }, raw: true });
    const collectedIds = R.pluck('type_id', userCollection.rows);
    const filter = { where: { id: { $in: collectedIds }, status: 1, is_deleted: 0 }, page_size, offset, attributes, raw: true };
    const classList = await ctx.classModel.V5.CourseV5Class.findAll(filter);

    const ret = {
      list: classList,
      total_count: userCollection.count,
      page,
      page_size,
    };
    return ret;
  }

  // 收藏课程
  async collectClass(id) {
    const { ctx } = this;
    // 先检查课程是否存在
    const classInfo = await ctx.classModel.V5.CourseV5Class.findOne({ where: { id, is_deleted: 0 }, attributes: [ 'id' ] });
    if (ctx.isEmpty(classInfo)) {
      ctx.failed('课程不存在');
    }

    // 检查是否已收藏
    const collectInfo = await ctx.classModel.V5.CourseUserCollection.findOne({ where: { user_uuid: ctx.userUuid, type: 3, type_id: id, is_deleted: 0 } });
    if (!ctx.isEmpty(collectInfo)) {
      ctx.failed('请勿重复收藏');
    }

    const data = {
      user_uuid: ctx.userUuid,
      institution_id: 0,
      type: 3,
      type_id: id,
      is_deleted: 0,
      created_time: moment().format('YYYY-MM-DD hh:mm:ss'),
    };
    await ctx.classModel.V5.CourseUserCollection.create(data);

    const ret = { result: true };
    return ret;
  }

  // 取消收藏
  async delCollectClass(class_id) {
    const { ctx } = this;
    let ret = await ctx.classModel.V5.CourseUserCollection.findOne({ where: { user_uuid: ctx.userUuid, is_deleted: 0, type: 3, type_id: class_id } });
    if (ctx.isEmpty(ret)) {
      ctx.failed('尚未收藏');
    }

    ret = await ctx.classModel.V5.CourseUserCollection.update({ is_deleted: 1 }, { where: { id: ret.id } });

    return { result: true };
  }

  // 获取科普文章
  async getArticleByCategory(catId) {
    const { ctx } = this;

    const article = await ctx.classModel.V5.CourseV5Article.findOne({ where: { cat_id: catId, status: 1, is_deleted: 0 } });
    if (ctx.isEmpty(article)) {
      return {};
    }

    // 问答
    const qa = await ctx.classModel.V5.CourseV5ArticleQA.findAll({ where: { article_id: article.id, status: 1, is_deleted: 0 }, order: [[ 'sort', 'asc' ]], attributes: [ 'id', 'question', 'answer' ] });

    const ret = {
      id: article.id,
      cat_id: article.cat_id,
      image: article.image,
      content: article.content,
      qa,
    };

    return ret;
  }
}

module.exports = InstitutionSubService;
