<?php namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\OpenWork\Corp\AuthCorp as AuthCorpModel;
use App\Models\Manager\ActivityAmountRecord;

/**
 *用户模型
 * 
 */
class CompanyChargingRefund extends Model
{
    use HasFactory;

    // 与模型关联的表名
    protected $table = 'company_charging_refund';
    // 是否主动维护时间戳
    public $timestamps = false;
    protected   $connection = 'mysql';
    // 定义时间戳字段名
    // const CREATED_AT = 'insert_time';
    // const UPDATED_AT = 'update_time';



    /**
     * 添加数据
     * 
     */
    public function add($data)
    {
        // 时间
        $data['insert_time']				= time();
        $data['update_time']				= time();
        // 写入数据表
        $id						            = $this->query()->insertGetId($data);
        // 如果操作失败
        if( !$id )                          return 0;

        // 返回结果
        return                              $id;
    }

    /**
     * 添加数据
     * 
     */
    public function edit($id,$data)
    {
        // 更新时间
        $data['update_time']                = time();
        // 写入数据表
        $result						        = $this->query()->where(['id'=>$id])->update($data);
        // 如果操作失败
        if( !$result )                      return 0;

        // 返回结果
        return                              $id;
    }
    /**
     * 获取账户数据
     *
     */
    public function get_data($company_id)
    {
        //获取总额
        $total_amount               = $this->query()->where([['company_id','=',$company_id],['status','=',3]])->sum('amount');
        $ActivityAmountRecord       = new ActivityAmountRecord();
        $budget_amount              = $ActivityAmountRecord::query()->where([['company_id','=',$company_id],['status','=',0]])->sum('budget_amount');
        $use_amount                 = $ActivityAmountRecord::query()->where([['company_id','=',$company_id],['status','=',1]])->sum('use_amount');
        $data['total_amount']       = $total_amount;
        $data['available_amount']   = bcsub(bcsub($total_amount , $use_amount,2) , $budget_amount,2);
        // 如果没有数据
        if( !$data )                return [];
        // 返回结果
        return                      $data;
    }



}