<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Device\Box;
use App\Admin\Actions\Device\getRule;
use App\Admin\Actions\Device\Lock;
use App\Admin\Actions\Device\Reflash;
use App\Admin\Actions\Device\sendRule;
use App\Admin\Actions\Device\testRule;
use App\Admin\Actions\Users\InRecords;
use App\Admin\Actions\Users\PutRecords;
use App\Admin\Actions\Users\WithDraw;
use App\Admin\Controllers\Sta;
use App\Model\DeviceInfo;
use App\Model\DeviceType;
use App\Model\UserInfo;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Echarts\Echarts;
use function foo\func;
use Zhusaidong\GridExporter\Exporter;

/**
 * @author pxwei
 * Class DeviceController
 * @package App\Admin\Controllers\Device
 */
class DeviceController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '设备管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {

        $grid = new Grid(new DeviceInfo());
        $status = DeviceInfo::getStatus();
        $grid->disableCreateButton(false);
//        $exporter = Exporter::get($grid);
//        $exporter->setFileName('设备导出.xlsx');
        $grid->disableCreateButton();
        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new Reflash());
        });
//        $grid->column('link','二维码')->qrcode()->default('http://www.baidu.com');
//        $grid->column('device_qrcode', __('二维码'))->display(function (){return '<i class="fa fa-qrcode"></i>';})
//            ->modal("设备二维码",function (){
//                $id = $this->id;
//                $path = "/vendor/laravel-admin/AdminLTE/dist/img/avatar.jpg";
//                if (file_exists(public_path('upload/DeviceQRCODE/'.$id.'.jpg')))
//                    $path = '/upload/DeviceQRCODE/'.$id.'.jpg?'.rand(1,99999);
//                $html = <<<HTML
//                <img id="show_$id" style="width: 300px;height: 350px;;" src="$path" alt="">
// <p>避免一次性从微信服务器加载多个造成缓慢，请手动点击: <a href="javascript:loadMiniAppQrcode($id,{$this->id})" class="">加载该设备小程序二维码</a>
//</p>
//HTML;
//
//                return $html;
//            });
        $grid->model()->orderBy('status','asc');
        $grid->header(function (){
            return "<script src='/js/loadMiniApp.js?24'></script><style>.dropdown-menu{}</style>";
        });
        $grid->column('id', __('ID'))->sortable();
        $grid->column('device_name', __('设备名称'))->editable();
        $grid->column('device_type', __('类型'))->display(function ($w){
            if(empty($w)) return '无';
            return DeviceInfo::getTypes()[$w];
        });

        $grid->column('query', __('刷新时间'));

        $grid->column('status', __('设备状态'))->using($status)->sortable();;
        $grid->column('runningStatus', __('运行状态'))->display(function ($s){
            $arr = [['name'=>'正常','color'=>'success'],['name'=>'故障','color'=>'danger'],['name'=>'故障','color'=>'danger'],['name'=>'故障','color'=>'danger'],['name'=>'故障','color'=>'danger'],['name'=>'正常','color'=>'success']];
            return "<span class='label label-{$arr[$s]['color']}'>{$arr[$s]['name']}</span>";
        });


        $grid->column('updated_at', __('更新时间'))->sortable();
        $grid->actions(function ($actions){
            $actions->disableDelete(false);
            $actions->add(new Lock());
            $actions->add(new sendRule());
            $actions->add(new getRule());
            $actions->add(new testRule());
        });
        $grid->filter(function (Grid\Filter $filter){
            $filter->column(1/2, function ($filter) {
                $filter->like('device_name','设备名称');
                $filter->equal('status','状态')->select(DeviceInfo::getStatus());
            });
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed   $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(DeviceInfo::findOrFail($id));
        $isLock = DeviceInfo::getLock();
        $status = DeviceInfo::getStatus();
        $breakDown = DeviceInfo::getBrakdown();

        $show->field('id', __('ID'));
        $show->field('device_name', __('阿里云设备编号'));
        $show->field('device_comment', __('微信中名称'));
        $show->field('device_type', __('型号'));
        $show->field('iot_id', __('iot_id'));
        $show->field('product_key', __('product_key'));
        $show->field('device_secret', __('设备密匙'));
        $show->field('imei', __('imei'));
        $show->field('status', __('运行状态'))->using($status);
        $show->field('runningStatus', __('设备状态'))->using($breakDown);
        $show->field('lock_switch', __('是否锁定'))->using($isLock);

        $show->field('device_position', __('详细位置'));
        $show->field('device_weight', __('累计重量/kg'))->as(function ($w){
            return round($w/1000,3);
        });
        $show->field('device_qrcode', __('二维码'))->image();
        $show->field('device_tem', __('温度'));
        $show->field('device_light_start', __('灯牌开始点亮时间'));
        $show->field('device_light_end', __('灯牌结束点亮时间'));
        $show->field('serial_number', __('海康卫视序列号'));
        $show->field('device_memo', __('设备备注'));
        $show->field('created_at', __('创建时间'));
        $show->field('updated_at', __('更新时间'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new DeviceInfo());
        if(Admin::user()->isAdministrator()){
            $form->text('id', __('ID'));
        } else {
            $form->display('id', __('ID'));
        }
        $form->select('device_type', __('设备类型'))->options(DeviceInfo::getTypes())->rules('required');
        $form->display('device_name', __('（阿里云）设备编号'))->rules('required');
        $form->display('iot_id', __('(阿里云)iot_id'))->rules('required');
        $form->display('product_key', __('(阿里云)product_key'))->help('阿里产品密匙')->rules('required');
        $form->display('device_secret', __('(阿里云)设备密匙'))->rules('required');
        $form->display('imei', __('（阿里云）设备唯一码'))->rules('required');
        $form->hidden('device_tem', __('设备温度'))->default(28)->rules('required');
        $form->text('query', '刷新时间')->help('单位秒')->rules('required');
//        $form->select('status', __('状态'))->options(['在营','离线','禁用','未激活']);
        //$form->hidden('runningStatus', __('运行状态'))->options(['满溢','修复','清空','未知']);
//        $form->latlong('device_latitude', 'device_longitude', '经纬度')->default(['lat' => 90, 'lng' => 90]);
        $form->textarea('remark', '设备备注');

        $form->display('created_at', __('创建时间'));
        $form->display('updated_at', __('更新时间'));

        return $form;
    }
}
