<?php

namespace app\admin\model;

use app\BaseModel;
use \think\facade\Db;

class KefuTime extends BaseModel
{
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    public static function addData($admin_id, $type) {
        if ($type == 3 || $type == 4) {
            $info = self::where('admin_id', $admin_id)->where('type', $type)->where('status', 0)->find();
            if ($info) {
                return $info;
            }
        }
        return self::create([
            'admin_id' => $admin_id,
            'type' => $type,
            'start_time' => time(),
            'status' => 0,
        ]);
    }

    //结束服务时间
    public static function endData($admin_id, $type, $cs_uid = 0) {
        //结束接线（需要判断当前没有任何接线的用户，才结束接线时间）
        if ($type == 3) {
            //更新客服接线数量
            User::where('user_id', $cs_uid)->where('chat_num', '>', 0)->update(['chat_num'=>Db::raw('chat_num-1')]);

            $count = User::where('cs_uid', $cs_uid)->whereIn('service_status', [1,2])->count();
            if ($count == 0) {
                return false;
            }
        }
        $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 = KefuWork::where('admin_id', $admin_id)->where("created_at", '>=', date("Y-m-d"))->find();
            if ($type == 1) { 
                $info->busy_time += $exits->end_time - $exits->start_time;
                $info->save();
            } elseif ($type == 2) { 
                $info->online_time += $exits->end_time - $exits->start_time;
                $info->save();
            } elseif ($type == 3) { 
                $info->chat_time += $exits->end_time - $exits->start_time;
                $info->save();
            } elseif ($type == 4) { 
                $info->service_time += $exits->end_time - $exits->start_time;
                $info->save();
            }
            return true;
        }
        return false;
    }

}