<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\device;


use app\common\model\device\Device;
use app\common\logic\BaseLogic;
use think\facade\Config;
use think\facade\Db;

/**
 * Device逻辑
 * Class DeviceLogic
 * @package app\adminapi\logic\device
 */
class DeviceLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2023/11/24 15:30
     */
    public static function add(array $params): bool
    {
        if (is_array($params['monitor_item'])) {
            $params['monitor_item'] = implode(',', $params['monitor_item']);
        } else {
            $params['monitor_item'] = trim($params['monitor_item']);
        }
        $userId = (request()->adminInfo)['user_id'];
        if (!empty($params['product_id'])) {
            $userId = Db::name('product')->where('id', $params['product_id'])->value('user_id');
        }
        Db::startTrans();
        try {
            $device = Device::create([
                'user_id' => $userId,
                'code' => $params['code'],
                'iccid' => $params['iccid'],
                'name' => $params['name'],
                'type' => $params['type'],
                'image' => $params['image'],
                'monitor_item' => $params['monitor_item'],
                'video_url' => $params['video_url'],
                'status' => $params['status'],
                'is_online' => $params['is_online']
            ]);
            if (!empty($params['product_id'])) {
                Db::name('product_device')->insert([
                    'product_id' => $params['product_id'],
                    'device_id' => $device['id'],
                    'device_type' => $params['type'],
                    'create_time' => time(),
                    'update_time' => time()
                ]);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2023/11/24 15:30
     */
    public static function edit(array $params): bool
    {
        if (is_array($params['monitor_item'])) {
            $params['monitor_item'] = implode(',', $params['monitor_item']);
        } else {
            $params['monitor_item'] = trim($params['monitor_item']);
        }
        $userId = (request()->adminInfo)['user_id'];
        if (!empty($params['product_id'])) {
            $userId = Db::name('product')->where('id', $params['product_id'])->value('user_id');
        }
        Db::startTrans();
        try {
            $device = Device::where('id', $params['id'])->update([
                'user_id' => $userId,
                'code' => $params['code'],
                'iccid' => $params['iccid'],
                'name' => $params['name'],
                'type' => $params['type'],
                'image' => $params['image'],
                'monitor_item' => $params['monitor_item'],
                'video_url' => $params['video_url'],
                'status' => $params['status'],
                'is_online' => $params['is_online']
            ]);
            Db::name('product_device')->where('device_id', $params['id'])->delete();
            if (!empty($params['product_id'])) {
                Db::name('product_device')->insert([
                    'product_id' => $params['product_id'],
                    'device_id' => $params['id'],
                    'device_type' => $params['type'],
                    'create_time' => time(),
                    'update_time' => time()
                ]);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    public function datas($params): array
    {

        $queryWhere = [];
        if (!empty($params['name'])) {
            $queryWhere[] = ['d.name', 'like', '%' . $params['name'] . '%'];
        }
        $deviceIdArray = Db::name('product_device')->column('device_id');
        if (!empty($params['all'])) {
            $deviceIdArray= [];
        }
        $lists = Db::name('device')->alias('d')
            ->where($queryWhere)->whereNotIn('d.id', $deviceIdArray)
            ->leftJoin('product_device pd','pd.device_id = d.id')
            ->leftJoin('product p','p.id = pd.product_id')
            ->leftJoin('user u','u.id = p.user_id')
            ->field('d.*')
            ->limit(0, 100)
            ->order(['d.id' => 'desc'])
            ->select()->toArray();
        foreach ($lists as &$item) {
            $item['deviceinfo'] = 'ID：' . $item['id'] . ' / 名称：' . $item['name'];
        }
        return $lists;
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2023/11/24 15:30
     */
    public static function delete(array $params): bool
    {
        Db::name('product_device')->where('device_id', $params['id'])->delete();
        Db::name('device_monitor_data')->where('device_id', $params['id'])->delete();
        Db::name('monitor_alarm')->where('device_id', $params['id'])->delete();
        return Device::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2023/11/24 15:30
     */
    public static function detail($params): array
    {
        $detail = Db::name('device')->alias('d')
            ->where('d.id', $params['id'])
            ->leftJoin('user u','u.id = d.user_id')
            ->leftJoin('product_device pd','pd.device_id = d.id')
            ->leftJoin('product p','p.id = pd.product_id')
            ->leftJoin('land_product lp','lp.product_id = pd.product_id')
            ->leftJoin('land l','l.id = lp.land_id')
            ->field('d.*, u.account, pd.product_id, p.name as product_name, lp.land_id, l.title as land_title')
            ->findOrEmpty();

        $monitorItemArray = [];
        if (!empty($detail['monitor_item'])) {
            $monitorItemArray = explode(',', $detail['monitor_item']);
        }

        $dictTypeId = Db::name('dict_type')->where('type', 'monitor_item')->value('id');
        $monitorItemArray = Db::name('dict_data')->where('type_id', $dictTypeId)->whereIn('value', $monitorItemArray)->field(['name', 'value'])->select()->toArray();
        foreach($monitorItemArray as $k=>$v) {
            $monitorItemArray[$k]['device_id'] = $params['id'];
            $monitorItemArray[$k]['monitor_value'] = '-';
            $monitorItemArray[$k]['last_time'] = '-';
            $monitorData = Db::name('land_collection')->where('device_id', $params['id'])->order(['id' => 'desc'])->find();
            if (!empty($monitorData)) {
                $monitorItemArray[$k]['monitor_value'] = $monitorData[$v['value']];
                $monitorItemArray[$k]['last_time'] =$monitorData['create_time'];
            }
        }
        $detail['monitor_item'] = $monitorItemArray;
        return $detail;
    }

    public static function monitorData($params): array
    {
        $pageSizeMax = Config::get('project.lists.page_size_max');
        $pageSize = Config::get('project.lists.page_size');
        $pageNo = $page_no = request()->get('page_no', 1) ?: 1;
        $pageSize = $page_size = request()->get('page_size', $pageSize) ?: $pageSize;

        $limitOffset = ($pageNo - 1) * $pageSize;
        $limitLength = $pageSize;
        $where['device_id'] = $params['id'];
        $lists = Db::name('land_collection')
            ->where($where)
            ->field(["{$params['monitor_type']} as monitor_value", 'id', 'create_time'])
            ->limit($limitOffset, $limitLength)
            ->order(['id' => 'desc'])
            ->select()
            ->toArray();
        $count = Db::name('land_collection')->where($where)->count();
        return  compact('lists', 'count', 'page_no', 'page_size');
    }
}