const Controller = require('./base')
const Param = require('../util/param')
const Rule = require('../util/rule')
const Response = require('../util/response')
const { UserService } = require('../service/index')

class UserController extends Controller {
  async find (ctx) {
    if (!await this.authUser(ctx)) return

    let res = {}
    let response = new Response(ctx)

    try {
      let data = await UserService.find({
        id: ctx.request.query.userId
      })
      response.success(data)
    } catch (e) {
      res.msg = e.message
      res.code = CODE_NORMAL_ERROR
      response.error(res)
    }
  }

  async preview (ctx) {
    let response = new Response(ctx)
    let query = ctx.request.query
    let res = {}

    try {
      let checkRightRes = await UserService.checkRight({
        userId: query.userId
      })
      
      console.log('checkRightRes', checkRightRes.data)

      if (checkRightRes.data.code === 0) {
        let data = await UserService.find({
          id: query.id
        })
        response.success(data)
        return
      } else {
        res.msg = checkRightRes.data.msg
        res.code = CODE_NORMAL_ERROR
        response.error(res)
      }
    } catch (e) {
      console.log('checkRightRes e', e.message)
      res.msg = e.message
      res.code = CODE_NORMAL_ERROR
      response.error(res)
    }
  }

  async create (ctx) {
    if (!await this.authUser(ctx)) return

    let query = ctx.request.query

    let rules = {
      sallary: [query.sallary, 'require'], // 期望薪资
      name: [query.name, 'require'], // 姓名
      idPhoto: [query.idPhoto, 'require'], // 证件照
      lifePhoto: [query.lifePhoto], // 生活照
      department: [query.department, 'require'], // 应聘岗位
      identity: [query.identity, 'require'], // 身份证号
      personalInfo: [query.description, 'require'], // 个人信息
      email: [query.email, 'require', Rule.Reg_Email], // 个人邮箱
      phone: [query.phone, 'require', Rule.Reg_Phone], // 手机号码
      urgentPhone: [query.urgentPhone], // 紧急联系人[姓名_电话_关系]
      plan: [query.plan, 'require'], // 三年内职业规划
      eduExperience: [query.eduExperience, 'require'], // 教育经历
      workExperience: [query.workExperience, 'require'], // 工作经历
      description: [query.description, 'require'], // 自我评价
      resume: [query.resume]// 上传简历
    }

    let param = new Param(ctx, rules)
    if (!param.checkParams()) return

    let response = new Response(ctx)
    let res = {}
    try {
      let userId = query.userId

      query.id = userId
      let data = await UserService.find({ id: userId })

      if (data) await UserService.update(query, { 'id': userId })
      else await UserService.create(query)

      response.success()
    } catch (e) {
      res.msg = e.message
      res.code = CODE_NORMAL_ERROR
      response.error(res)
    }
  }
}

module.exports = UserController
