<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 用户设备
 */
class Userdevice extends Api
{
    protected $noNeedLogin = ['device_list'];
    protected $noNeedRight = ['*'];

    //所有设备
    public function device_list(){
        $list = Db::name('device')->where('status',1)->select();
        $list = list_domain_image($list,['image']);

        $this->success(1,$list);
    }

    /**
     * 绑定新的
     */
    public function bind_device() {

        $sn = input('sn');
        $device_id = input('device_id');
        if (!$sn) {
            $this->error(__('Invalid parameters'));
        }

        if(mb_strlen($sn) != 15){
            $this->error('请输入15位长度正确编号');
        }

        $data = [
            'user_id'   => $this->auth->id,
            'device_id' => $device_id,
            'sn'        => $sn,
        ];
        $check = Db::name('user_device')->where($data)->find();
        if($check){
            $this->error('您已经绑定了该设备:'.$sn);
        }

        $res = Db::name('user_device')->insertGetId($data);

        $this->success('绑定成功');

    }

    //解绑
    public function unbind(){
        $id = input('id');
        Db::name('user_device')->where('id',$id)->delete();
        $this->success('解绑成功');
    }

    /**
     * 获取我的设备
     */
    public function my_device_list() {

        $mylist = Db::name('user_device')->field('user_device.*,device.name,device.info,device.image')
            ->join('device','user_device.device_id = device.id','LEFT')
            ->where(["user_id"=>$this->auth->id])->select();
        $mylist = list_domain_image($mylist,['image']);

        $this->success("获取成功！",$mylist);
    }

    //健康档案
    public function my_device_data(){
        $sn_arr = Db::name('user_device')->where(["user_id"=>$this->auth->id])->column('sn');

        $list = Db::name('device_sanheyi')->field('id,createtime,type,type_text,value')->where('sn','IN',$sn_arr)->autopage()->select();

        $result = [
            'number' => count($sn_arr),
            'list'   => $list,
        ];
        $this->success(1,$result);
    }



}
