<?php

namespace app\admin\model;

use app\BaseModel;

class KefuWork extends BaseModel
{
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    
    public static function addNum($admin_id, $field) {
        $info = self::where('admin_id', $admin_id)->where("created_at", '>=', date("Y-m-d"))->find();
        if (!$info) {
            $info = self::create([
                'admin_id' => $admin_id,
                $field => 1,
            ]);
        } else {
            $info->$field += 1;
            $info->save();
        }

        $type = 0;
        if ($field == 'busy_num') {
            $type = 1;
            $time_field = 'busy_time';
        } else if ($field == 'online_num') {
            $type = 2;
            $time_field = 'online_time';
        }else if ($field == 'sign_num') {
            $type = 4;
            $time_field = 'service_time';
        } elseif ($field == 'chat_num') {
            $type = 3;
            $time_field = 'chat_time';
        }

        if ($type) {
            $exits = KefuTime::where('admin_id', $admin_id)->where('type', $type)->where("created_at", '>=', date("Y-m-d"))->order('id', 'desc')->find();
            if ($exits && $exits->status == 0) {
                $exits->status = 1;
                $exits->end_time = time();
                $exits->save();

                $info->$time_field += $exits->end_time - $exits->start_time;
            }

            KefuTime::addData($admin_id, $type);
        }
        return true;
    }
}