
'use strict';

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

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: '录播(AI)',
    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: MODE, alias: 'mode' },
      { title: '课程类型', value: PRICE_TYPE, alias: 'price_type' },
      { title: '科目类型', value: categoryList, alias: 'category' },
    ];

    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 || type === 1) {
      filter.where.parent_id = parentId;
    }

    const categoryList = await ctx.classModel.V5.CourseV5Category.findAll(filter);
    let categoryAll = await ctx.classModel.V5.CourseV5Category.findAll({ where: {}, attributes: [ 'id', 'name' ], raw: true });
    categoryAll = _.groupBy(categoryAll, 'id');

    let 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 = [ 17, 19, 21 ];
            break;
          case 2:
            filterIds = [ 17, 19 ];
            break;
          case 5:
            filterIds = [ 19 ];
            break;
          case 6:
            filterIds = [ 19 ];
            break;
          case 7:
            filterIds = [ 19 ];
            break;
          case 8:
            filterIds = [ 19, 21 ];
            break;
          case 9:
            filterIds = [ 19, 22, 21 ];
            break;
          case 10:
            filterIds = [ 19, 22, 21 ];
            break;
          case 11:
            filterIds = [ 19, 20, 22, 21 ];
            break;
          case 12:
            filterIds = [ 19, 20, 22, 21 ];
            break;
          case 13:
            filterIds = [ 19, 20, 22, 21 ];
            break;
          case 14:
            filterIds = [ 19, 20, 22, 21 ];
            break;
          case 15:
            filterIds = [ 19, 20, 22, 21 ];
            break;
          case 16:
            filterIds = [ 19, 20, 22, 21 ];
            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,
        parent_name: v.parent_id > 0 ? (ctx.isEmpty(categoryAll[v.parent_id]) ? '' : categoryAll[v.parent_id][0].name) : '',
        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,
        bind: v.bind,
        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;
  }


  // 填写问卷
  async addQuestionnaire(input) {
    const { ctx } = this;
    if (ctx.isEmpty(ctx.userUuid)) {
      ctx.failed('用户异常');
    }

    const data = {
      user_uuid: ctx.userUuid,
      cat_id: input.cat_id || 0,
      answer_1: input.answer_1 || '',
      answer_2: input.answer_2 || '',
      answer_3: input.answer_3 || '',
      created_time: moment().format('YYYY-MM-DD HH:mm:ss'),
    };
    await ctx.classModel.V5.CourseV5Questionnaire.create(data);

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


  // 获取问卷
  async getQuestionnaire() {
    const results = [
      {
        id: 1,
        question: '报告对于孩子的描述是否准确？',
        answers: [{ id: 1, value: '不准确' }, { id: 2, value: '部分准确' }, { id: 3, value: '很准确' }],
      },
      {
        id: 2,
        question: '报告建议对你选课有没有参考帮助？',
        answers: [{ id: 1, value: '不会参考' }, { id: 2, value: '部分参考' }, { id: 3, value: '值得信任' }],
      },
      {
        id: 3,
        question: '选课工具体验感，请打分？',
        answers: [{ id: 1, value: '体验较差' }, { id: 2, value: '体验一般' }, { id: 3, value: '体验很好' }],
      },
    ];

    const ret = {
      results,
    };

    return ret;
  }

  // 保存渠道小程序码
  async addUnlimitedCodeByChannel(input) {
    const { ctx } = this;
    const data = {
      channel: input.channel || '',
      image: input.image || '',
      is_deleted: 0,
      created_time: moment().format('YYYY-MM-DD HH:mm:ss'),
    };

    await ctx.classModel.V5.CourseV5QRCode.update({ is_deleted: 1 }, { where: { channel: input.channel } });
    await ctx.classModel.V5.CourseV5QRCode.create(data);

    return { result: true };
  }


  // 获取渠道小程序码
  async getUnlimitedCodeByChannel(input) {
    const { ctx } = this;
    const image = await ctx.classModel.V5.CourseV5QRCode.findOne({ where: { channel: input.channel, is_deleted: 0 } });

    const result = ctx.isEmpty(image) ? '' : image.image;
    return { result };
  }


  // 获取配置项
  async getSetting(input) {
    const { ctx } = this;
    const key = input.key || '';

    const setting = await ctx.classModel.V5.CourseSetting.findOne({ where: { key, status: 1, is_deleted: 0 } });

    const result = ctx.isEmpty(setting) ? '' : setting.value;
    return { result };
  }


  // 获取礼品页
  async getActImageList() {
    const { ctx } = this;

    const giftList = await ctx.classModel.CourseActImage.findAll({ where: { status: 1, is_deleted: 0 }, attributes: [ 'id', 'selected_image', 'unselected_image', 'type' ], order: [[ 'sort', 'asc' ]] });
    const ret = {
      list: giftList,
    };

    return ret;
  }
}

module.exports = OptionService;
