
'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.V2.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.V2.CourseUserBaby.edit({ params: { gender, birth, address, lat, lng }, where });
    } else {
      await ctx.classModel.V2.CourseUserBaby.add({ user_uuid, gender, birth, address, lat, lng });
    }

    return true;
  }

  async delBabyInfo() {

    const { ctx } = this;
    const user_uuid = ctx.userUuid;
    await ctx.classModel.V2.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.V2.CourseUserCollection.one({ where });
    if (ret && ret.id) {
      return ret.id;
    }
    ret = await await ctx.classModel.V2.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.V2.CourseUserCollection.one({ where });
    if (!ret || !ret.id) {
      return true;
    }
    ret = await await ctx.classModel.V2.CourseUserCollection.edit({ params: { is_deleted: 1 }, where });

    return true;
  }

  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;
