
'use strict';

const Service = require('egg').Service;
const moment = require('moment');
const R = require('ramda');
const GENDER = {
  boy: '小王子',
  girl: '小公主',
};

class UserService extends Service {


  async getBabyInfo() {

    const { ctx } = this;
    const user_uuid = ctx.userUuid;
    const where = { user_uuid, is_deleted: 0 };
    const babys_info = await ctx.classModel.V1.CourseUserBaby.all({ where, order: [[ 'id', 'desc' ]] });
    const babys = [];
    for (const i in babys_info) {
      const baby_info = babys_info[i];
      babys.push({
        id: baby_info.id,
        gender: baby_info.gender,
        birth: baby_info.birth,
        address: baby_info.address,
        lat: baby_info.lat,
        lng: baby_info.lng,
        gender_text: GENDER[baby_info.gender],
        age: moment().format('YYYY') - baby_info.birth.substr(0, 4),
      });

    }
    if (babys.length === 0) {
      return {};
    }
    const user_info = { address: babys[0].address, lat: babys[0].lat, lng: babys[0].lng };
    return { user_info, babys };
  }

  async saveBabyInfo(input) {

    const { ctx } = this;
    const user_uuid = ctx.userUuid;
    const { id, gender, birth, address, lat, lng } = input;
    const where = { id, user_uuid, is_deleted: 0 };
    if (id) {
      await ctx.classModel.V1.CourseUserBaby.edit({ params: { gender, birth, address, lat, lng }, where });
    } else {
      await ctx.classModel.V1.CourseUserBaby.add({ user_uuid, gender, birth, address, lat, lng });
    }

    return true;
  }

  async delBabyInfo() {

    const { ctx } = this;
    const user_uuid = ctx.userUuid;
    await ctx.classModel.V1.CourseUserBaby.edit({ params: { is_deleted: 1 }, where: { user_uuid } });

    return true;
  }

  async collectInstitution(institution_id) {

    const { ctx } = this;
    const user_uuid = ctx.userUuid;
    const where = { user_uuid, is_deleted: 0, institution_id };
    let ret = await ctx.classModel.V1.CourseUserCollection.one({ where });
    if (ret && ret.id) {
      return ret.id;
    }
    ret = await await ctx.classModel.V1.CourseUserCollection.add({ user_uuid, institution_id });

    return ret;
  }

  async delCollectInstitution(institution_id) {

    const { ctx } = this;
    const user_uuid = ctx.userUuid;
    const where = { user_uuid, is_deleted: 0, institution_id };
    let ret = await ctx.classModel.V1.CourseUserCollection.one({ where });
    if (!ret || !ret.id) {
      return true;
    }
    ret = await await ctx.classModel.V1.CourseUserCollection.edit({ params: { is_deleted: 1 }, where });

    return true;
  }

  async getCollectInstitutions(input) {
    const { ctx } = this;
    const user_uuid = ctx.userUuid;
    const { page, limit } = input;
    const lat = ctx.isEmpty(input.lat) ? 0 : input.lat;
    const lng = ctx.isEmpty(input.lng) ? 0 : input.lng;
    const where = { user_uuid, is_deleted: 0 };
    const collect_institution_rows = await ctx.classModel.V1.CourseUserCollection.list({ page, limit, where });
    const institution_ids = R.pluck('institution_id', collect_institution_rows.rows);
    if (institution_ids.length === 0) {
      return { page: collect_institution_rows.page, count: collect_institution_rows.count, rows: [] };
    }
    const include = [{ model: ctx.classModel.V1.CourseArea, where: { status: 1, is_deleted: 0 }, attributes: [ 'id', 'institution_id', 'name', 'address', 'lat', 'lng' ] }];
    const attributes = [ 'id', 'name', 'type', 'establishment_time', 'class_type', 'teacher_count', 'teacher_experience', 'corner', 'min_age', 'max_age', 'price', 'characteristic'  ];
    const institutions = await ctx.classModel.V1.CourseInstitution.findAll({ attributes, include, where: { id: { $in: institution_ids }, status: 1, is_deleted: 0 } });
    const institution_area_list = await ctx.service.course.institution.getInstitutionAreaList(institutions);
    const area_lbs = (lat > 0 || lng > 0) ? await ctx.service.course.institution.computeDistance(institution_area_list, { lat, lng }) : [];// 计算距离
    const institution_areas = await ctx.service.course.institution.findShortestDistanceAreas(institution_area_list, area_lbs);
    const ret = await ctx.service.course.institution.formatInstitutions(institution_areas);

    return { page: collect_institution_rows.page, count: collect_institution_rows.count, rows: ret };
  }

  async requestWxAuth(code) {

    const { ctx } = this;
    const APPID = 'wx07a5f0ed5bdf4751';
    const SECRET = 'a1b2d32b018988176181497bd74a0b7d';
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET}&js_code=${code}&grant_type=authorization_code`;

    const result = await ctx.helper.send_request(url, {}, { method: 'GET' });
    // const result = {"data":{"session_key":"Ce7HE1+MXfyZpWLYmkP0Iw==","openid":"oSjKI5LlG6AF7_vdV5Qb_DsbHcf4"},"status":200,"headers":{"connection":"keep-alive","content-type":"text/plain","date":"Tue, 24 Sep 2019 06:18:58 GMT","content-length":"82"},"res":{"status":200,"statusCode":200,"statusMessage":"OK","headers":{"connection":"keep-alive","content-type":"text/plain","date":"Tue, 24 Sep 2019 06:18:58 GMT","content-length":"82"},"size":82,"aborted":false,"rt":113,"keepAliveSocket":false,"data":{"session_key":"Ce7HE1+MXfyZpWLYmkP0Iw==","openid":"oSjKI5LlG6AF7_vdV5Qb_DsbHcf4"},"requestUrls":["https://api.weixin.qq.com/sns/jscode2session?appid=wx4769ebba9b91f8ec&secret=680440637b4e38c9b66529cfd5dc590e&js_code=021678ss18NNAk0Fohps1oA6ss1678sT&grant_type=authorization_code"],"timing":{"queuing":15,"dnslookup":15,"connected":27,"requestSent":57,"waiting":111,"contentDownload":113},"remoteAddress":"101.227.162.120","remotePort":443,"socketHandledRequests":1,"socketHandledResponses":1}};
    ctx.logger.info(JSON.stringify({ course_mini_auth_ret: result }));
    if (result.status !== 200) {
      ctx.failed('授权失败');
    }

    const ret = result.data;
    if (!ret.session_key && !ret.openid && ret.errcode !== 0) {
      ctx.failed(ret.errmsg);
    }

    const openid = ret.openid;
    const session_key = ret.session_key;

    return { openid, session_key };

  }


}

module.exports = UserService;
