<?php

namespace app\common\service;

use app\common\model\AgentMoney as AgentMoneyModel;
use app\common\model\Agent as AgentModel;
use app\common\model\Broker as BrokerModel;
use app\common\model\Config;

class AgentMoneyService extends BaseService
{
    public function add($broker_id, $value, $title, $remark = '', $type = 1)
    {
        if (empty($value)) {
            return $this->error('金额必填');
        }

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

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

        //修改收益
        $agent->money += $value;

        //修改累计收益
        if ($value > 0) {
            $agent->money_total += $value;
        }
        $agent->save();

        return $this->success('成功');
    }

    public function settle($id, $value, $title, $remark = '')
    {
        if (empty($value)) {
            return false;
        }

        $agent   = AgentModel::where('id', $id)->find();
        $money = new AgentMoneyModel();
        $money->save([
            'workerid'     => $agent['workerid'],
            'agentid'     => $id,
            'title'        => $title,
            'origin_value' => $agent['money'],
            'value'        => $value,
            'remark'       => $remark,
            'createtime'   => time(),
            'yeartime'     => date("Y"),
            'monthtime'    => date("Ym"),
        ]);

        //修改收益
        $agent->money += $value;
        if ($value > 0) {
            $agent->money_total += $value;
        }
        $agent->save();
    }
}