<?php

namespace app\common\service;

use app\common\model\UserBalance;
use app\common\model\UserParam as UserParamModel;
use app\common\model\User as UserModel;

class BalanceService extends BaseService
{

    const REGISTER      = 0;
    const IMPROVERESUME = 1;
    const CERTIFICATION = 2;
    const ENTRY         = 3;

    private $_type = [
        ['title' => '新用户注册奖励', 'remark' => '邀请新用户注册奖励'],
        ['title' => '首次完善简历奖励', 'remark' => '首次完善简历奖励'],
        ['title' => '首次实名认证通过奖励', 'remark' => '首次实名认证通过奖励'],
        ['title' => '对接成功奖励', 'remark' => '对接成功并入职奖励'],
    ];

    private $_field = [
        ['user' => 'balance_register_user', 'broker' => 'balance_register_broker'],
        ['user' => 'balance_improve_resume_user', 'broker' => 'balance_improve_resume_broker'],
        ['user' => 'balance_certification_user', 'broker' => 'balance_certification_broker'],
        ['user' => 'balance_entry_user', 'broker' => 'balance_entry_broker'],
    ];

    public function add($user_id, $type_index)
    {
        //获取配置
        $param      = UserParamModel::where(1)->findOrEmpty();
        $commission = $param['commission'];
        $type       = $this->_type[$type_index];
        $field      = $this->_field[$type_index];
        $user       = UserModel::where('id', $user_id)->find();

        //用户奖励
        if (!empty($commission[$field['user']])) {
            $balance = new UserBalance();
            $balance->save([
                'userid'       => $user_id,
                'title'        => $type['title'],
                'origin_value' => $user['balance'],
                'value'        => $commission[$field['user']],
                'remark'       => $type['remark'],
                'createtime'   => time(),
                'yeartime'     => date("Y"),
                'monthtime'    => date("Ym"),
            ]);

            $user->balance += $commission[$field['user']];
            $user->balance_total += $commission[$field['user']];
            $user->save();
        }

        //经纪人收益
        if (!empty($commission[$field['broker']])) {
            $incomeService = new IncomeService();
            $incomeService->add($user['broker_id'], $commission[$field['broker']], $type['title'], $type['remark']);
        }
    }
}