
'use strict';

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

class OnlineService extends Service {
  // 获取在线课程选项
  async getOption() {
    const { ctx } = this;
    // 分类
    let cats = await ctx.classModel.V4.CourseOnlineCat.findAll({ where: { status: 'online', is_deleted: 0 }, attributes: [ 'id', 'name' ], raw: true });
    cats = [{ id: 0, name: '全部' }].concat(cats);
    // 年龄段
    let ages = await ctx.classModel.V4.CourseOnlineAge.findAll({ where: { status: 'online', is_deleted: 0 }, attributes: [ 'id', 'name' ], raw: true });
    ages = [{ id: 0, name: '全部' }].concat(ages);
    // 课程状态
    const mode = [{ id: 0, name: '全部' }, { id: 1, name: '直播' }, { id: 2, name: '录播' }, { id: 3, name: '直播+录播' }];
    // 课程班型
    // let type = await ctx.classModel.V4.CourseOnlineType.findAll({ where: { status: 'online', is_deleted: 0 }, attributes: [ 'id', 'name' ], raw: true });
    // type = [{ id: 0, name: '全部' }].concat(type);
    // 课程类型
    const price_type = [{ id: 0, name: '全部' }, { id: 2, name: '免费公益课' }, { id: 1, name: '低价体验课' }, { id: 3, name: '正价课' }];

    const options = {
      cats,
      ages,
      mode,
      // type,
      price_type,
    };
    return options;
  }

  // 获取课程详情
  async getClass(input) {
    const { ctx } = this;
    const { id, lng, lat } = input;
    const classInfo = await ctx.classModel.V4.CourseOnlineClass.findOne({ where: { id, status: 'online', is_deleted: 0 } });
    if (ctx.isEmpty(classInfo)) {
      ctx.failed('课程不存在');
    }

    // 缩略图
    const imageInfo = await ctx.classModel.V4.CourseImages.findAll({ where: { type: 5, type_id: id, status: 'online', is_deleted: 0 } });
    const images = [];
    for (const v of imageInfo) {
      const image = v.is_video > 0 ? { url: v.video_url, type: 1 } : { url: v.image_url, type: 0 };
      images.push(image);
    }

    // 机构信息
    const institution = await ctx.classModel.V4.CourseOnlineInstitution.findOne({ where: { id: classInfo.institution_id } });
    // 校区信息
    let area = await ctx.classModel.V4.CourseOnlineArea.findOne({ where: { institution_id: classInfo.institution_id, status: 'online', is_deleted: 0 }, raw: true });
    area = ctx.isEmpty(area) ? area : await this.service.course.v4.institution.formatArea(area, { lng, lat });

    // 分类
    const classCats = await ctx.classModel.V4.CourseOnlineClassToCat.findAll({ where: { class_id: id, status: 'online', is_deleted: 0 }, attributes: [ 'cat_id' ] });
    const catIds = R.pluck('cat_id', classCats);
    const cats = await ctx.classModel.V4.CourseOnlineCat.findAll({ where: { id: { $in: catIds } }, attributes: [ 'id', 'name' ] });

    // 年龄段
    const classAges = await ctx.classModel.V4.CourseOnlineClassToAge.findAll({ where: { class_id: id, status: 'online', is_deleted: 0 }, attributes: [ 'age_id' ] });
    const ageIds = R.pluck('age_id', classAges);
    const ages = await ctx.classModel.V4.CourseOnlineAge.findAll({ where: { id: { $in: ageIds } }, attributes: [ 'id', 'name' ] });

    // 班型
    const classTypes = await ctx.classModel.V4.CourseOnlineClassToType.findAll({ where: { class_id: id, status: 'online', is_deleted: 0 }, attributes: [ 'type_id' ] });
    const typeIds = R.pluck('type_id', classTypes);
    const type = await ctx.classModel.V4.CourseOnlineType.findAll({ where: { id: { $in: typeIds } }, attributes: [ 'id', 'name' ] });

    // 收藏信息
    const uuid = ctx.headers.uuid || '';
    const userCollect = await ctx.classModel.V4.CourseUserCollection.findOne({ where: { user_uuid: uuid, type: 3, type_id: id, is_deleted: 0 } });

    const ret = {
      id,
      images,
      name: classInfo.name,
      institution_name: ctx.isEmpty(institution) ? '' : institution.name,
      institution_id: classInfo.institution_id,
      institution_logo: ctx.isEmpty(institution) ? '' : institution.logo,
      relation_institution_id: ctx.isEmpty(institution) ? 0 : institution.relation_id,
      address: ctx.isEmpty(area) ? '' : area.address,
      phone: ctx.isEmpty(area) ? '' : area.phone,
      travel_tips: ctx.isEmpty(area) ? '' : area.travel_tips,
      price: classInfo.price,
      price_type: this.getClassModelPriceType(classInfo.price_type),
      type,
      ages,
      mode: await this.getClassModelInfo(classInfo.mode),
      time: classInfo.time,
      channel: classInfo.channel,
      description: classInfo.description,
      cats: ctx.isEmpty(cats) ? [] : cats,
      is_collected: ctx.isEmpty(userCollect) ? 0 : 1,
    };

    return ret;
  }


  // 获取在线课程列表
  async getClasses(input) {
    const { ctx } = this;
    const page = Number(input.page) || 1;
    const limit = Number(input.limit) || 10;
    const offset = (page - 1) * limit;
    const { type, mode, age, cat, price_type } = input;
    const filter = { where: { status: 'online', is_deleted: 0 }, order: [[ 'institution_id', 'desc' ]], limit, offset, attributes: [ 'id', 'institution_id', 'name', 'price_type', 'price', 'mode', 'time', 'created_time' ] };
    // 年龄段筛选
    let ids = [];
    let flag = false;
    if (!ctx.isEmpty(age) && Number(age) > 0) {
      const classes = await ctx.classModel.V4.CourseOnlineClassToAge.findAll({ where: { age_id: age, status: 'online', is_deleted: 0 }, attributes: [ 'class_id' ] });
      if (flag) {
        ids = _.intersection(ids, R.pluck('class_id', classes));
      } else {
        flag = true;
        ids = R.pluck('class_id', classes);
      }
    }
    // 课程类型筛选
    if (!ctx.isEmpty(cat) && Number(cat) > 0) {
      const classes = await ctx.classModel.V4.CourseOnlineClassToCat.findAll({ where: { cat_id: cat, status: 'online', is_deleted: 0 }, attributes: [ 'class_id' ] });
      if (flag) {
        ids = _.intersection(ids, R.pluck('class_id', classes));
      } else {
        flag = true;
        ids = R.pluck('class_id', classes);
      }
    }
    // 课程状态筛选
    if (!ctx.isEmpty(mode) && Number(mode) > 0) {
      filter.where.mode = mode;
    }
    // 课程类型筛选
    if (!ctx.isEmpty(price_type) && Number(price_type) > 0) {
      filter.where.price_type = price_type;
    }
    // 课程班型筛选
    if (!ctx.isEmpty(type) && Number(type) > 0) {
      const classes = await ctx.classModel.V4.CourseOnlineClassToType.findAll({ where: { type_id: type, status: 'online', is_deleted: 0 }, attributes: [ 'class_id' ] });
      if (flag) {
        ids = _.intersection(ids, R.pluck('class_id', classes));
      } else {
        flag = true;
        ids = R.pluck('class_id', classes);
      }
    }
    if (flag) {
      filter.where.id = { $in: ids };
    }

    const classes = await ctx.classModel.V4.CourseOnlineClass.findAndCountAll(filter);
    const classIds = R.pluck('id', classes.rows);

    // 分类
    const classToCats = await ctx.classModel.V4.CourseOnlineClassToCat.findAll({ where: { class_id: { $in: classIds }, status: 'online', is_deleted: 0 }, attributes: [ 'class_id', 'cat_id' ] });
    const catIds = R.pluck('cat_id', classToCats);
    let cats = await ctx.classModel.V4.CourseOnlineCat.findAll({ where: { id: { $in: catIds } } });
    cats = _.groupBy(cats, 'id');
    let classCats = [];
    for (const v of classToCats) {
      const tmp = {
        id: v.cat_id,
        class_id: v.class_id,
        name: ctx.isEmpty(cats[v.cat_id]) ? '' : cats[v.cat_id][0].name,
      };
      classCats.push(tmp);
    }
    classCats = _.groupBy(classCats, 'class_id');

    // 年龄段
    const classToAge = await ctx.classModel.V4.CourseOnlineClassToAge.findAll({ where: { class_id: { $in: classIds }, status: 'online', is_deleted: 0 }, attributes: [ 'class_id', 'age_id' ] });
    const ageIds = R.pluck('age_id', classToAge);
    let ages = await ctx.classModel.V4.CourseOnlineAge.findAll({ where: { id: { $in: ageIds } } });
    ages = _.groupBy(ages, 'id');
    let classAge = [];
    for (const v of classToAge) {
      const tmp = {
        id: v.age_id,
        class_id: v.class_id,
        name: ctx.isEmpty(ages[v.age_id]) ? '' : ages[v.age_id][0].name,
      };
      classAge.push(tmp);
    }
    classAge = _.groupBy(classAge, 'class_id');

    // 班型
    const classToTypes = await ctx.classModel.V4.CourseOnlineClassToType.findAll({ where: { class_id: { $in: classIds }, status: 'online', is_deleted: 0 }, attributes: [ 'class_id', 'type_id' ] });
    const typeIds = R.pluck('type_id', classToTypes);
    let types = await ctx.classModel.V4.CourseOnlineType.findAll({ where: { id: { $in: typeIds } } });
    types = _.groupBy(types, 'id');
    let classTypes = [];
    for (const v of classToTypes) {
      const tmp = {
        id: v.type_id,
        class_id: v.class_id,
        name: ctx.isEmpty(types[v.type_id]) ? '' : types[v.type_id][0].name,
      };
      classTypes.push(tmp);
    }
    classTypes = _.groupBy(classTypes, 'class_id');

    // 机构
    const institutionIds = R.pluck('institution_id', classes.rows);
    let institutions = await ctx.classModel.V4.CourseOnlineInstitution.findAll({ where: { id: { $in: institutionIds } }, attributes: [ 'id', 'name', 'logo' ] });
    institutions = _.groupBy(institutions, 'id');

    const result = [];
    for (const v of classes.rows) {
      const tmp = {
        id: v.id,
        name: v.name,
        institution_id: v.institution_id,
        institution_name: ctx.isEmpty(institutions[v.institution_id]) ? '' : institutions[v.institution_id][0].name,
        logo: ctx.isEmpty(institutions[v.institution_id]) ? '' : institutions[v.institution_id][0].logo,
        type: ctx.isEmpty(classTypes[v.id]) ? [] : classTypes[v.id],
        mode: await this.getClassModelInfo(v.mode),
        price_type: this.getClassModelPriceType(v.price_type),
        price: v.price,
        time: v.time,
        created_time: v.created_time,
        cats: ctx.isEmpty(classCats[v.id]) ? [] : classCats[v.id],
        age: ctx.isEmpty(classAge[v.id]) ? [] : classAge[v.id],
      };
      result.push(tmp);
    }

    const ret = {
      results: result,
      count: classes.count,
      page,
    };
    return ret;
  }

  // 判断课程状态（直播录播）
  async getClassModelInfo(mode) {
    let ret = '';
    switch (mode) {
      case 1:
        ret = '直播';
        break;
      case 2:
        ret = '录播';
        break;
      case 3:
        ret = '直播+录播';
        break;
      default:
        break;
    }
    return ret;
  }

  // 判断课程类型
  getClassModelPriceType(price_type) {
    let ret = '';
    switch (price_type) {
      case 1:
        ret = '低价体验课';
        break;
      case 2:
        ret = '免费公益课';
        break;
      case 3:
        ret = '正价课';
        break;
      default:
        break;
    }
    return ret;
  }

  // 收藏在线课程
  async collectClass(id) {
    const { ctx } = this;
    const userUuid = ctx.userUuid;

    const data = {
      user_uuid: userUuid,
      type: 3,
      type_id: id,
      is_deleted: 0,
      created_time: moment().format('YYYY-MM-DD HH:mm:ss'),
    };

    const check = await ctx.classModel.V4.CourseUserCollection.findOne({ where: { user_uuid: userUuid, type: 3, type_id: id, is_deleted: 0 } });
    if (!ctx.isEmpty(check)) {
      ctx.failed('请勿重复收藏');
    }

    const ret = await ctx.classModel.V4.CourseUserCollection.create(data);
    return { result: ret.id };
  }


  // 获取收藏课程列表
  async getCollectionClasses(input) {
    const { ctx } = this;
    const page = Number(input.page) || 1;
    const limit = Number(input.limit) || 10;
    const offset = (page - 1) * limit;
    const userUuid = ctx.userUuid;

    const userCollection = await ctx.classModel.V4.CourseUserCollection.findAndCountAll({ where: { user_uuid: userUuid, is_deleted: 0, type: 3 }, raw: true, limit, offset });
    let classIds = R.pluck('type_id', userCollection.rows);

    const filter = { where: { id: { $in: classIds }, status: 'online', is_deleted: 0 }, order: [[ 'institution_id', 'desc' ]], limit, offset, attributes: [ 'id', 'institution_id', 'name', 'price', 'mode', 'time', 'created_time' ] };
    const classes = await ctx.classModel.V4.CourseOnlineClass.findAll(filter);
    classIds = R.pluck('id', classes);

    // 分类
    const classToCats = await ctx.classModel.V4.CourseOnlineClassToCat.findAll({ where: { class_id: { $in: classIds }, status: 'online', is_deleted: 0 }, attributes: [ 'class_id', 'cat_id' ] });
    const catIds = R.pluck('cat_id', classToCats);
    let cats = await ctx.classModel.V4.CourseOnlineCat.findAll({ where: { id: { $in: catIds } } });
    cats = _.groupBy(cats, 'id');
    let classCats = [];
    for (const v of classToCats) {
      const tmp = {
        id: v.cat_id,
        class_id: v.class_id,
        name: ctx.isEmpty(cats[v.cat_id]) ? '' : cats[v.cat_id][0].name,
      };
      classCats.push(tmp);
    }
    classCats = _.groupBy(classCats, 'class_id');

    // 年龄段
    const classToAge = await ctx.classModel.V4.CourseOnlineClassToAge.findAll({ where: { class_id: { $in: classIds }, status: 'online', is_deleted: 0 }, attributes: [ 'class_id', 'age_id' ] });
    const ageIds = R.pluck('age_id', classToAge);
    let ages = await ctx.classModel.V4.CourseOnlineAge.findAll({ where: { id: { $in: ageIds } } });
    ages = _.groupBy(ages, 'id');
    let classAge = [];
    for (const v of classToAge) {
      const tmp = {
        id: v.age_id,
        class_id: v.class_id,
        name: ctx.isEmpty(ages[v.age_id]) ? '' : ages[v.age_id][0].name,
      };
      classAge.push(tmp);
    }
    classAge = _.groupBy(classAge, 'class_id');

    // 班型
    const classToTypes = await ctx.classModel.V4.CourseOnlineClassToType.findAll({ where: { class_id: { $in: classIds }, status: 'online', is_deleted: 0 }, attributes: [ 'class_id', 'type_id' ] });
    const typeIds = R.pluck('type_id', classToTypes);
    let types = await ctx.classModel.V4.CourseOnlineType.findAll({ where: { id: { $in: typeIds } } });
    types = _.groupBy(types, 'id');
    let classTypes = [];
    for (const v of classToTypes) {
      const tmp = {
        id: v.type_id,
        class_id: v.class_id,
        name: ctx.isEmpty(types[v.type_id]) ? '' : types[v.type_id][0].name,
      };
      classTypes.push(tmp);
    }
    classTypes = _.groupBy(classTypes, 'class_id');

    // 机构
    const institutionIds = R.pluck('institution_id', classes);
    let institutions = await ctx.classModel.V4.CourseOnlineInstitution.findAll({ where: { id: { $in: institutionIds } }, attributes: [ 'id', 'name', 'logo' ] });
    institutions = _.groupBy(institutions, 'id');

    // 缩略图
    const imageInfo = await ctx.classModel.V4.CourseImages.findAll({ where: { type: 5, type_id: { $in: classIds }, status: 'online', is_deleted: 0 } });
    let images = [];
    for (const v of imageInfo) {
      const image = v.is_video > 0 ? { url: v.video_url, type: 1 } : { url: v.image_url, type: 0 };
      image.type_id = v.type_id;
      images.push(image);
    }
    images = _.groupBy(images, 'type_id');

    const result = [];
    for (const v of classes) {
      const tmp = {
        id: v.id,
        name: v.name,
        images: ctx.isEmpty(images[v.id]) ? [] : images[v.id],
        institution_id: v.institution_id,
        institution_name: ctx.isEmpty(institutions[v.institution_id]) ? '' : institutions[v.institution_id][0].name,
        logo: ctx.isEmpty(institutions[v.institution_id]) ? '' : institutions[v.institution_id][0].logo,
        type: ctx.isEmpty(classTypes[v.id]) ? [] : classTypes[v.id],
        mode: await this.getClassModelInfo(v.mode),
        price: v.price,
        time: v.time,
        created_time: v.created_time,
        cats: ctx.isEmpty(classCats[v.id]) ? [] : classCats[v.id],
        age: ctx.isEmpty(classAge[v.id]) ? [] : classAge[v.id],
      };
      result.push(tmp);
    }

    const ret = {
      results: result,
      count: userCollection.count,
      page,
    };

    return ret;
  }


  // 取消在线课程收藏
  async delCollectClass(id) {
    const { ctx } = this;
    const userUuid = ctx.userUuid;

    // 是否已收藏
    const check = await ctx.classModel.V4.CourseUserCollection.findOne({ where: { user_uuid: userUuid, type: 3, type_id: id, is_deleted: 0 } });
    if (ctx.isEmpty(check)) {
      ctx.failed('尚未收藏');
    }

    await ctx.classModel.V4.CourseUserCollection.update({ is_deleted: 1 }, { where: { id: check.id } });
    return;
  }
}

module.exports = OnlineService;
