<?php

namespace app\common\service;

use app\common\model\BrokerIncome as BrokerIncomeModel;
use app\common\model\Broker as BrokerModel;
use app\common\model\Config;
use app\common\model\Worker as WorkerModel;
use app\common\model\Agent as AgentModel;

class IncomeService extends BaseService
{
    public function add($broker_id, $value, $title, $remark = '', $type = 1)
    {
        if (empty($value)) {
            return false;
        }

        if (empty($broker_id)) {
            $broker_id = Config::getConfigValue('default_broker');
        }

        $broker = BrokerModel::where('id', $broker_id)->find();
        $income = new BrokerIncomeModel();
        $income->save([
            'brokerid'     => $broker_id,
            'workerid'     => $broker['workerid'],
            'agentid'      => $broker['agentid'],
            'title'        => $title,
            'origin_value' => $broker['income'],
            'value'        => $value,
            'type'         => $type,
            'status'       => $type == 2 ? 1 : 2,
            'remark'       => $remark,
            'createtime'   => time(),
            'yeartime'     => date("Y"),
            'monthtime'    => date("Ym"),
        ]);

        //修改收益
        $broker->income += $value;

        //修改累计收益
        if ($value > 0) {
            $worker               = WorkerModel::where('id', $broker['workerid'])->find();
            $worker->income       += $value;
            $worker->income_total += $value;
            $worker->save();

            $agent                = AgentModel::where('id', $broker['agentid'])->find();
            $agent->income        += $value;
            $agent->income_total  += $value;
            $agent->save();

            $broker->income_total += $value;
        }
        $broker->save();
    }
}