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

    return true;
  }

  async delBabyInfo() {

    const { ctx } = this;
    const user_uuid = ctx.userUuid;
    await ctx.classModel.V4.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, type: 1, type_id: institution_id };
    let ret = await ctx.classModel.V4.CourseUserCollection.one({ where });
    if (ret && ret.id) {
      ctx.failed('请勿重复收藏');
    }
    ret = await await ctx.classModel.V4.CourseUserCollection.add({ user_uuid, type: 1, type_id: institution_id });

    return ret;
  }

  async delCollectInstitution(institution_id) {

    const { ctx } = this;
    const user_uuid = ctx.userUuid;
    const where = { user_uuid, is_deleted: 0, type: 1, type_id: institution_id };
    let ret = await ctx.classModel.V4.CourseUserCollection.one({ where });
    if (!ret || !ret.id) {
      ctx.failed('尚未收藏');
    }
    ret = await await ctx.classModel.V4.CourseUserCollection.edit({ params: { is_deleted: 1 }, where });

    return true;
  }

  async collectClass(class_id) {

    const { ctx } = this;
    const user_uuid = ctx.userUuid;
    const where = { user_uuid, is_deleted: 0, type: 2, type_id: class_id };
    let ret = await ctx.classModel.V4.CourseUserCollection.one({ where });
    if (ret && ret.id) {
      ctx.failed('请勿重复收藏');
    }
    ret = await await ctx.classModel.V4.CourseUserCollection.add({ user_uuid, type: 2, type_id: class_id });

    return ret;
  }

  async delCollectClass(class_id) {

    const { ctx } = this;
    const user_uuid = ctx.userUuid;
    const where = { user_uuid, is_deleted: 0, type: 2, type_id: class_id };
    let ret = await ctx.classModel.V4.CourseUserCollection.one({ where });
    if (!ret || !ret.id) {
      ctx.failed('尚未收藏');
    }
    ret = await await ctx.classModel.V4.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 };

  }

  // 获取用户信息
  async getUserInfo(input) {
    const { ctx } = this;
    const userUuid = ctx.userUuid;
    const userInfo = await ctx.classModel.V4.CourseUser.findOne({ where: { uuid: userUuid, is_deleted: 0 } });
    const type = Number(input.type) || 0;
    if (ctx.isEmpty(userInfo)) {
      ctx.failed('用户不存在');
    }

    let need_bind_phone = 0;
    if (ctx.isEmpty(userInfo.phone) && type > 0) {
      const userLog = await ctx.classModel.V4.CourseLogUser.findOne({ where: { user_uuid: userUuid, type }, order: [[ 'id', 'desc' ]], limit: 1 });
      if ((!ctx.isEmpty(userLog) && moment(userLog.created_time, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD') !== moment().format('YYYY-MM-DD')) || ctx.isEmpty(userLog)) {
        need_bind_phone = 1;
        await ctx.classModel.V4.CourseLogUser.create({ user_uuid: userUuid, type, created_time: moment().format('YYYY-MM-DD HH:mm:ss') });
      }
    }

    const ret = {
      bind_phone: ctx.isEmpty(userInfo.phone) ? 0 : 1,
      need_bind_phone,
    };

    return ret;
  }

  // 保存用户信息
  async registerUserInfo(input) {
    const { ctx } = this;
    const userUuid = ctx.userUuid;
    const { avatar, nickname, province, country, sex, city, encryptedData, iv } = input;
    // 查找用户是否存在并更新
    const user = await ctx.classModel.V4.CourseUser.findOne({ where: { uuid: userUuid, is_deleted: 0 } });
    if (ctx.isEmpty(user)) {
      ctx.failed('用户不存在');
    }

    const data = {};
    let bind_phone = ctx.isEmpty(user.phone) ? 0 : 1;
    if (!ctx.isEmpty(avatar)) {
      data.avatar = avatar;
    }
    if (!ctx.isEmpty(nickname)) {
      data.nickname = nickname;
    }

    if (!ctx.isEmpty(encryptedData) && !ctx.isEmpty(iv)) {
      const decoded = await ctx.service.course.v4.wechat.decodeData(encryptedData, iv);
      if (!ctx.isEmpty(decoded) && !ctx.isEmpty(decoded.phoneNumber)) {
        data.phone = decoded.phoneNumber;
        bind_phone = 1;
      }
    }

    await ctx.classModel.V4.CourseUser.update(data, { where: { id: user.id } });

    const ret = {
      result: {
        bind_phone,
      },
    };
    return ret;
  }
}

module.exports = UserService;
