<?php
namespace app\admin\controller;
use app\common\model\DeviceLog;
use app\common\model\Group;
use app\temperature\controller\Push;
use think\App;
use think\Db;

require_once $_SERVER['DOCUMENT_ROOT'] . '/../vendor/wenkong/TemperatureDevice.php';

class TemperatureDevice extends Auth
{
    protected $abnormal = [
        '正常',
        '设备离线',
        '传感器异常',
        '传感器未连接',
    ];
    public function __construct(App $app) {
        parent::__construct($app);
        $this->api = new Push();
    }
    public function index() {
        if (request()->isAjax()) {
            //分页参数
            $length = input('rows', 10, 'intval');   //每页条数
            $page = input('page', 1, 'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx', 'id', 'trim');      //排序列
            $sort = input('sord', 'desc', 'trim');        //排序方式
            $order = $sortRow . ' ' . $sort;
            $title = input('title', '', 'trim');
            if ($title) {
                $map[] = ['dev_name|snaddr', 'like', '%' . $title . '%'];
            }
            $enable = input('enable', '', 'trim');
            if ($enable != '') {
                $map[] = ['enable', '=', $enable];
            }
            $group = input('group_id', '', 'trim');

            if($group!=''){
                $iiDs = Db::name('group_device')
                    ->where('org_id',$this->orgId)
                    ->where('group_id',$group)
                    ->column('device_id');
                if(empty($iiDs)){
                    $map[] = ['id', '=', -1];
                }else{
                    $map[] = ['id', 'in', $iiDs];

                }
            }else{
                $groupList = (new Group())->getList();
                if(!empty($groupList)){
                    $iiDs = Db::name('group_device')
                        ->where('org_id',$this->orgId)
                        ->where('group_id',$groupList[0]['id'])
                        ->column('device_id');
                    if(empty($iiDs)){
                        $map[] = ['id', '=', -1];
                    }else{
                        $map[] = ['id', 'in', $iiDs];

                    }
                }
            }
            $map[] = ['org_id', '=', $this->orgId];
            $map[] = ['del', '=', 0];

            if($this->userId!==1){
                $ids = Db::name('temperature_auth')
                    ->where('user_id',$this->userId)
                    ->where('org_id',$this->orgId)
                    ->column('temperature_id');
                if(!empty($ids)){
                    $map[] = ['id', 'in',$ids];
                }else{
                    $map[] = ['id', '=',-1];

                }

            }
            $map = empty($map) ? true : $map;
            //数据查询
            $this->api->getDeviceData();
            $lists = Db::name('temperature_device')
                ->where($map)->limit($start, $length)->order($order)->select();
            foreach ($lists as $k => &$v) {
                $v['tj'] = '';
                $v['abnormal_name'] = $this->abnormal[$v['abnormal']];
                $gd = Db::name('group_device')
                    ->where('org_id',$this->orgId)
                    ->where('device_id',$v['id'])
                    ->column('group_id');
                if(empty($gd)){
                    $t = '';
                }else{
                    $x = Db::name('group')
                        ->where('id','in',$gd)
                        ->column('title');
                    $t = implode(',',$x);
                }
                $v['gName'] = $t;
            }

            //数据返回
            $totalCount = Db::name('temperature_device')->where($map)->count();
            $totalPage = ceil($totalCount / $length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }
        else {
            $group = (new Group())->getList();

            $this->assign('group', $group);
            return $this->fetch();
        }
    }
    /**
     * 新增/编辑
     */
    public function add($id = 0) {
        if (request()->isPost()) {
            $model = new \app\common\model\TemperatureDevice();
            $post = request()->post();
            $data = [
                'snaddr'=>trim($post['snaddr']),
                'dev_name'=>$post['dev_name'],
                'remark'=>$post['remark'],
                'enable'=>$post['enable'],
                'org_id'=>$this->orgId,
                'id'=>$id,
            ];

            $validate = new \app\common\validate\TemperatureDevice();
            $result = $validate->scene('')->check($data,[]);
            if(true !== $result){
                $this->error($validate->getError());
            }
            $log =Db::name('device_log')
                ->where('type',DeviceLog::TYPE5)
                ->where('sn',$data['snaddr'])
                ->where('del',0)
                ->find();
            if(empty($log)){
                $this->error('该设备无法添加');
            }
            unset($data['id']);
            if($id <=0){
                $data['create_time'] = date('Y-m-d H:i:s');
                $res = Db::name('temperature_device')
                    ->insertGetId($data);
                $id = $res;
            }else{
                $data['update_time'] = date('Y-m-d H:i:s');
                $res = Db::name('temperature_device')
                    ->where('id',$id)
                    ->update($data);
            }
            if ($res) {
                Db::name('group_device')
                    ->where('org_id',$this->orgId)
                    ->where('device_id',$id)
                    ->delete();
                $data = request()->post();
                if(isset($data['group_id']) && !empty($data['group_id'])){
                    $ids = $data['group_id'];
                    $a = [
                        'org_id'=>$this->orgId,
                        'device_id'=>$id,
                        'group_id'=>$ids,
                    ];
                    Db::name('group_device')
                        ->insertGetId($a);

                }
                $this->success('操作成功', url('index'));
            }
            else {
                $this->error($model->getError());
            }
        }
        else {
            $meta_title = '新增设备';
            if ($id) {
                $info = Db::name('temperature_device')->where('id', $id)->find();
                $info['gd'] = Db::name('group_device')
                    ->where('org_id',$this->orgId)
                    ->where('device_id',$id)
                    ->value('group_id');
                $this->assign('info', $info);

                $meta_title = '编辑设备';
            }
            $group = (new Group())->getList();
            $this->assign('meta_title', $meta_title);
            $this->assign('group', $group);
            return $this->fetch();
        }
    }
    /**
     * 删除记录
     * @param int $id
     */
    public function del($id = 0) {
        if (!$id) {
            $this->error('参数错误');
        }
        $res = Db::name('temperature_device')->where('id', $id)->update(['del' => 1]);
        Db::name('group_device')
            ->where('device_id',$id)
            ->where('org_id',$this->orgId)
            ->delete();
        if ($res) {
            $this->success('删除成功');
        }
        else {
            $this->error('删除失败');
        }
    }
    /**
     * 改变字段值
     * @param int $fv
     * @param string $fn
     * @param int $fv
     */
    public function changeField($id = 0, $fn = '', $fv = 0) {
        if (!$fn || !$id) {
            $this->error('参数错误');
        }
        $res = Db::name('temperature_device')->where('id', $id)->update([$fn => $fv]);
        if ($res) {
            $this->success('操作成功');
        }
        else {
            $this->error('操作失败');
        }
    }
    /**
     * 24小时温度图
     *
     * @author wst
     * @date   2021/6/9 10:59
     */
    public function tj1($id) {
        $time = time();
        $timeData = [];
        for ($i = 0; $i <= 23; $i++) {
            if (strlen($i) <= 1) {
                $i = '0' . $i;
            }
            $timeData[] = date('Ymd', $time) . $i;
        }
        $data = [];
        foreach ($timeData as $k => $v) {
            $info = Db::name('temperature_device_data')
                ->where('snaddr', $id)
                ->where('create_ymdh', $v)
                ->where('abnormal', 0)
                ->avg('temp');
            $a = [
                'name' => substr($v, -2) . ':00',
                'value' => round($info, 2)
            ];
            $data[] = $a;
        }
        $this->assign('key', array_column($data, 'name'));
        $this->assign('value', array_column($data, 'value'));
        $i = array_chunk($data, 16);
        $this->assign('data', $i);
        return $this->fetch();
    }
    /**
     * 最近七日温度显示
     *
     * @author wst
     * @date   2021/6/9 14:16
     */
    public function tj2($id) {
        $time = time();
        $timeData = [];
        for ($i = 6; $i >= 0; $i--) {
            $timeData[] = date('Ymd', $time - ($i * 86400));
        }
        $data = [];
        foreach ($timeData as $k => $v) {
            $info = Db::name('temperature_device_data')
                ->where('snaddr', $id)
                ->where('create_ymd', $v)
                ->where('abnormal', 0)
                ->avg('temp');
            $a = [
                'name' => substr($v, 0, 4) . '-' . substr($v, 4, 2) . '-' . substr($v, -2),
                'value' => round($info, 2)
            ];
            $data[] = $a;
        }
        $this->assign('key', array_column($data, 'name'));
        $this->assign('value', array_column($data, 'value'));
        $this->assign('data', $data);
        return $this->fetch();
    }
    /**
     * 最近30日温度显示
     *
     * @author wst
     * @date   2021/6/9 14:16
     */
    public function tj3($id) {
        $time = time();
        $timeData = [];
        for ($i = 29; $i >= 0; $i--) {
            $timeData[] = date('Ymd', $time - ($i * 86400));
        }
        $data = [];
        foreach ($timeData as $k => $v) {
            $info = Db::name('temperature_device_data')
                ->where('snaddr', $id)
                ->where('create_ymd', $v)
                ->where('abnormal', 0)
                ->avg('temp');
            $a = [
                'name' => substr($v, 0, 4) . '-' . substr($v, 4, 2) . '-' . substr($v, -2),
                'value' => round($info, 2)
            ];
            $data[] = $a;
        }
        $this->assign('key', array_column($data, 'name'));
        $this->assign('value', array_column($data, 'value'));
        $i = array_chunk($data, 10);
        $this->assign('data', $i);
        return $this->fetch();
    }
    public function auth() {
        if (request()->isAjax()) {
            //分页参数
            $length = input('rows', 10, 'intval');   //每页条数
            $page = input('page', 1, 'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx', 'id', 'trim');      //排序列
            $sort = input('sord', 'desc', 'trim');        //排序方式
            $order = $sortRow . ' ' . $sort;
            $title = input('title', '', 'trim');
            if ($title) {
                $map1[] = ['dev_name|snaddr', 'like', '%' . $title . '%'];
                $map1[] = ['org_id', '=', $this->orgId];
                $deviceIds = Db::name('temperature_device')
                    ->where($map1)
                    ->column('id');
                if (!empty($deviceIds)) {
                    $map[] = ['temperature_id', 'in', $deviceIds];
                }
                else {
                    $map[] = ['temperature_id', '=', -1];
                }
            }
            $title1 = input('name', '', 'trim');
            if ($title1) {
                $map2[] = ['a.org_id', '=', $this->orgId];
                $map2[] = ['b.real_name', 'like', '%' . $title1 . '%'];
                $userIds = Db::name('user')
                    ->alias('b')
                    ->join('user_org a', 'b.id=a.user_id')
                    ->where($map2)
                    ->column('b.id');
                if (!empty($deviceIds)) {
                    $map[] = ['user_id', 'in', $userIds];
                }
                else {
                    $map[] = ['user_id', '=', -1];
                }
            }
            $map[] = ['org_id', '=', $this->orgId];
            $map = empty($map) ? true : $map;
            //数据查询
            $lists = Db::name('temperature_auth')
                ->where($map)
                ->limit($start, $length)
                ->field('user_id,count(*) as num')
                ->group('user_id')
                ->distinct(true)
                ->order($order)->select();

            foreach ($lists as $k => &$v) {
                $v['nickName'] = Db::name('user')
                    ->where('id', $v['user_id'])
                    ->value('real_name');

            }
            //数据返回
            $totalCount = Db::name('temperature_auth')
                ->group('user_id')
                ->where($map)->count();
            $totalPage = ceil($totalCount / $length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }
        else {
            return $this->fetch();
        }
    }
    public function add_auth() {
        if (request()->isPost()) {
            $data = request()->post();

            if(!isset($data['user_id']) || empty($data['user_id'])){
                $this->error('用户不能为空');
            }
            if(!isset($data['temperature_id']) || empty($data['temperature_id'])){
                $this->error('设备不能为空');
            }
            $ids = explode(',',$data['temperature_id']);
            $ii = [];
            foreach ($ids as $k=>$v) {
                if (strpos($v, 'p') === false && !empty($v)) {
                    $aa = explode('-',$v);
                    $ii[] = $aa[0];
                }
            }
            $ids = $ii;
            $a = [];
            foreach ($ids as $k=>$v){
                $check = Db::name('temperature_auth')
                    ->where('user_id',$data['user_id'])
                    ->where('temperature_id',$v)
                    ->find();
                if($check){
                    $info = Db::name('temperature_device')
                        ->where('id',$v)
                        ->find();
                    $this->error($info['dev_name'].'('.$info['snaddr'].')设备已绑定');

                }
                $a[] = [
                    'user_id'=>$data['user_id'],
                    'temperature_id'=>$v,
                    'org_id'=>$this->orgId
                ];
            }
            $res = Db::name('temperature_auth')
                ->insertAll($a);
            if($res){
                Db::name('user')
                    ->where('id',$data['user_id'])
                    ->update(['group'=>$data['temperature_id']]);
                $this->success('添加成功', url('auth'));

            }
            $this->error('添加失败');

        }
        else {
            $meta_title = '新增';
            $map[] = ['uo.org_id', '=', $this->orgId];
            $map[] = ['u.del', '=', 0];
            //数据查询
            $lists = Db::name('user')
                ->alias('u')
                ->join('user_org uo', 'uo.user_id = u.id')
                ->join('user_dep ud', 'ud.user_id = u.id', 'left')
                ->join('user_roles ur', 'ur.user_id = u.id', 'left')
                ->where($map)
                ->field('u.id as id,real_name as title')
                ->select();


            $group = Db::name('group')
                ->where('org_id',$this->orgId)
                ->field('id,title as label')
                ->where('enable',1)
                ->select();

            foreach ($group as $k=>$v){
                $group[$k]['children'] = [];
                $deviceId = Db::name('group_device')
                    ->where('org_id',$this->orgId)
                    ->where('group_id',$v['id'])
                    ->column('device_id');

                if($deviceId){
                    $device = Db::name('temperature_device')
                        ->where('id','in',$deviceId)
                        ->where('del', 0)
                        ->field('id,dev_name as label,snaddr')
                        ->select();
                    foreach ($device as $k1 => $v1) {
                        $device[$k1]['label'] = $v1['label'] . '(' . $v1['snaddr'] . ')';
                    }
                    $group[$k]['children'] =$device;
                }

            }
            foreach ($group as $k=>$v){
                $group[$k]['id'] = $v['id'].'-p';
                foreach ($v['children'] as $k1=>$v1){
                    $group[$k]['children'][$k1]['id'] = $v1['id'].'-c';
                }
            }
            $this->assign('group', $group);
            $this->assign('user', $lists);
            $this->assign('meta_title', $meta_title);
            return $this->fetch();
        }
    }
    /**
     * 新增/编辑
     */
    public function edit_auth($id = 0) {
        if (request()->isPost()) {
            $data = request()->post();
            if(!isset($data['user_id']) || empty($data['user_id'])){
                $this->error('用户不能为空');
            }
            if(!isset($data['temperature_id']) || empty($data['temperature_id'])){
                $this->error('设备不能为空');
            }
            $ids = explode(',',$data['temperature_id']);

            $ii = [];
            foreach ($ids as $k=>$v) {
                if (strpos($v, 'p') === false && !empty($v)) {
                    $aa = explode('-',$v);
                    $ii[] = $aa[0];
                }
            }

            $ids = $ii;
            $a = [];
            Db::name('temperature_auth')
                ->where('user_id',$data['user_id'])
                ->delete();
            foreach ($ids as $k=>$v){
                $a[] = [
                    'user_id'=>$data['user_id'],
                    'temperature_id'=>$v,
                    'org_id'=>$this->orgId
                ];
            }
            $res = Db::name('temperature_auth')
                ->insertAll($a);
            if ($res) { Db::name('user')
                ->where('id',$data['user_id'])
                ->update(['group'=>$data['temperature_id']]);
                $this->success('操作成功', url('auth'));
            }
            else {
                $this->error('修改失败');
            }
        }
        else {
            $meta_title = '新增';
            if ($id) {
//                $info = Db::name('temperature_auth')
//                    ->where('user_id', $id)->column('temperature_id');
                $iii = Db::name('user')
                    ->where('id',$id)
                    ->find();
                $info = $iii?explode(',',$iii['group']):[];
                $this->assign('info', $info);
                $meta_title = '编辑';
            }
            $map[] = ['uo.org_id', '=', $this->orgId];
            $map[] = ['u.del', '=', 0];
            //数据查询
            $lists = Db::name('user')
                ->alias('u')
                ->join('user_org uo', 'uo.user_id = u.id')
                ->join('user_dep ud', 'ud.user_id = u.id', 'left')
                ->join('user_roles ur', 'ur.user_id = u.id', 'left')
                ->where($map)
                ->field('u.id as id,real_name as title')
                ->select();
            $group = Db::name('group')
                ->where('org_id',$this->orgId)
                ->field('id,title as label')
                ->where('enable',1)
                ->select();

            foreach ($group as $k=>$v){
                $group[$k]['children'] = [];
                $deviceId = Db::name('group_device')
                    ->where('org_id',$this->orgId)
                    ->where('group_id',$v['id'])
                    ->column('device_id');

                if($deviceId){
                    $device = Db::name('temperature_device')
                        ->where('id','in',$deviceId)
                        ->where('del', 0)
                        ->field('id,dev_name as label,snaddr')
                        ->select();
                    foreach ($device as $k1 => $v1) {
                        $device[$k1]['label'] = $v1['label'] . '(' . $v1['snaddr'] . ')';
                    }
                    $group[$k]['children'] =$device;
                }

            }
            foreach ($group as $k=>$v){
                $group[$k]['id'] = $v['id'].'-p';
                foreach ($v['children'] as $k1=>$v1){
                    $group[$k]['children'][$k1]['id'] = $v1['id'].'-c';
                }
            }
            $this->assign('group', $group);
            $this->assign('user', $lists);
            $this->assign('meta_title', $meta_title);
            $this->assign('user_id',$id);
            return $this->fetch();
        }
    }
    /**
     * 删除记录
     * @param int $id
     */
    public function del_auth($id = 0) {
        if (!$id) {
            $this->error('参数错误');
        }
        $res = Db::name('temperature_auth')->where('user_id', $id)->delete();
        if ($res) {
            $this->success('删除成功');
        }
        else {
            $this->error('删除失败');
        }
    }
    public function detail_auth($id){
        $info = Db::name('temperature_auth')
            ->where('user_id', $id)->column('temperature_id');
        $d = Db::name('temperature_device')
            ->where('id','in',$info)
            ->select();
        $this->assign('list',$d);
        return $this->fetch();

    }


}