<?php
namespace app\model;

class LiveRoomWorks extends base {
    public function zhubo() {
        return $this->hasOne(Admins::class, 'id', 'zhubo_id')->field(['id', 'name', 'mobile']);
    }

    public function zhongkong() {
        return $this->hasOne(Admins::class, 'id', 'zhongkong_id')->field(['id', 'name', 'mobile']);
    }

    /**
     * @param $day
     * @return LiveRoom[]|array|\think\Collection|\think\db\Query[]|\think\model\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getDayWork($day, $liveRoomId) {
        $end = date('Y-m-d', strtotime($day) + 24*60*60);
        return self::where([
            ['start', '>', $day],
            ['end', '<', $end],
            'live_room_id' => $liveRoomId,
        ])->with(['zhubo', 'zhongkong'])
         ->order('start', 'desc')
         ->select();
    }

    /**
     * @param $id
     * @param $roomId
     * @param $start
     * @param $end
     * @return bool
     */
    public static function dayWorkIsExists($id, $roomId, $start, $end) {
        return self::where([
            ['start', '>', $start],
            ['end', '<', $end],
            'live_room_id' => $roomId,
            ['id', '!=', $id]
        ])->find();
    }

    /**
     * @param $id
     * @param $zhuboId
     * @param $day
     * @return bool
     */
    public static function zhuboWorkIsExists($id, $zhuboId, $day) {
        return self::where([
            'day' => $day,
            'zhubo_id' => $zhuboId,
            ['id', '!=', $id]
        ])->find();
    }

    /**
     * @param $day
     * @return LiveRoomWorks[]|array|\think\Collection|\think\db\Query[]|\think\model\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function inWorkAdmin($day) {
        return self::where(['day' => $day,])->field(['zhubo_id'])->select();
    }

    /**
     * @param $type
     * @param $adminId
     * @param $start
     * @param $end
     */
    public static function staticOrder($type, $adminId, $start, $end) {
        $field = $type == 3 ? 'zhongkong_id' : 'zhubo_id';
        return self::where([
            ['start', '>', $start],
            ['end', '<', $end],
            [$field, '=', $adminId]
        ])->fieldRaw('ifnull(sum(orders), 0) as orders')
            ->fieldRaw('ifnull(sum(total), 0) as total')
            ->fieldRaw('ifnull(sum(asset_total), 0) as asset_total')
            ->fieldRaw('ifnull(sum(TIMESTAMPDIFF(HOUR, `start`, `end`)), 0) as work_time')
            ->find();
    }
}