@extends('layouts.app')

@section('title','列表')

@section('content')
    <div id="nav2">
        @component('station.menu')@endcomponent
        @component('station.cachingShelf.menu')@endcomponent
    </div>
    <div class="container-fluid d-none" id="list">
        @include('station.cachingShelf.list._table')
        @include('station.cachingShelf.list._fillBox')
    </div>
@endsection

@section('lastScript')
    <script>
        new Vue({
            el: '#list',
            data: {
                stations: {!! $stations->toJson() !!}['data'],
                selectTr: null,
                currentEcho:null,
                materialBoxCode: null,      // 料箱编码
                currentStation: {           // 当前Station
                    id: null,               // Station->id
                    code:'',
                    grids: {},     // 格口
                    gridCodes:new Array(9),
                },
                boxClass: 'modal-sm',
                fontSize: {},
                broadcastName: null,
                channelName: ".App\\Events\\BroadcastToStation",

            },
            mounted() {
                this.initCacheShelfBox();
                this.initModalBox();
                $('#list').removeClass('d-none');
            },
            methods: {
                /** 1初始化缓存架格口 */
                initCacheShelfBox() {
                    let code = this.currentStation.code;
                    this.currentStation.grids = {};
                    this.currentStation.gridCodes = new Array(9);
                    if(code === null)return;
                    for (let index = 0; index < this.currentStation.gridCodes.length; index++) {
                        let row = Math.ceil( (index+1) / 3);
                        let col = (index+1) % 3 === 0 ? 3 : (index+1) % 3 ;
                        let stationCode =  'HAI'+code+'-0'+col+'-0'+row;
                        this.currentStation.gridCodes[index] = stationCode;
                        this.currentStation.grids[stationCode] = {
                            index:index+1,
                            parentStationCode:code,
                            stationCode:stationCode,
                            materialBoxCode:null,
                            row:row,
                            col:col,
                            type:null
                        }
                    }
                },
                /** 2初始化modal大小 */
                initModalBox() {
                    if (window.screen.width >= 520) {
                        this.boxClass = 'modal-sm';
                        this.fontSize = {'font-size': '25px'}
                    }
                    if (window.screen.width >= 720){
                        this.boxClass = 'modal-md';
                        this.fontSize = {'font-size': '25px'}
                    }
                    if (window.screen.width >= 960){
                        this.boxClass = 'modal-lg';
                        this.fontSize = {'font-size': '30px'}
                    }
                    if (window.screen.width >= 1200) {
                        this.boxClass = 'modal-xl';
                        this.fontSize = {'font-size': '35px'}
                    }
                },
                /** 展示modal */
                showFeedBox(station) {
                    this.currentStation.id = station.id;
                    this.currentStation.code = station.code;
                    this.initCacheShelfBox()
                    this.broadcastName = "{{config('database.redis.options.prefix')}}" + 'station-' + station['id'];
                    this.initCacheGrid();
                    this._listenBroadcast();
                    $('#box').modal('show');
                },
                /** 清空格口号 */
                // clearCurrentStation() {
                //     this.currentStation.data.forEach(function (item, index, items) {
                //         items[index].forEach(function (item, index, self) {
                //             self[index]['code'] = null;
                //         })
                //     });
                //     this.$forceUpdate();
                // },
                /** 初始化格口 */
                initCacheGrid() {
                    let url = '{{url('apiLocal/station/cacheShelf/getTasks')}}'+'/'+this.currentStation.id;
                    window.tempTip.setIndex(1099);
                    window.tempTip.setDuration(3000);
                    $('#alert-box').show();
                    window.axios.get(url).then(res => {
                        if (res.data.data) {
                            for (let index = 0; index < res.data.data.length; index++) {
                                let stationCode = res.data.data[index]['code'];
                                if(!res.data.data[index]['pending_station_task'])continue;
                                if(!res.data.data[index]['pending_station_task']['station_task_material_boxes'])continue;
                                if(!res.data.data[index]['pending_station_task']['station_task_material_boxes'][0])continue;
                                if(!res.data.data[index]['pending_station_task']['station_task_material_boxes'][0]['material_box'])continue;
                                let materialBoxCode = res.data.data[index]['pending_station_task']['station_task_material_boxes'][0]['material_box']['code'] ?? null;
                                this.$set(this.currentStation.grids[stationCode],'materialBoxCode',materialBoxCode);
                            }
                            $('#alert-box').hide();
                            this.$forceUpdate();
                            return;
                        }
                        window.tempTip.show('获取缓存货架信息失败');
                        $('#alert-box').hide();
                    }).catch(err => {
                        window.tempTip.show('获取缓存货架信息异常:' + err);
                        $('#alert-box').hide();
                    });
                },
                /** 扫码 1、料箱扫码 */
                pushMaterialBox(grid = null,$e = null) {
                    // 从格口输入
                    if($e) {
                        let materialBoxCode = $($e.target).val();
                        let stationCode = grid['stationCode'];

                        if(materialBoxCode.trim()!=='')this.lightOn(stationCode,materialBoxCode);
                        else this.clearTask(stationCode);
                        return;
                    }
                    for (const key in this.currentStation.grids) {
                        if(this.currentStation.grids[key]['materialBoxCode'] === null){
                            this.lightOn(this.currentStation.grids[key]['stationCode'],this.materialBoxCode);
                            return ;
                        }
                    }
                },
                /** 扫码 2、亮灯 */
                lightOn(stationCode,materialBoxCode) {
                    if(!stationCode || !materialBoxCode)return ;
                    let url = '{{url('apiLocal/station/cacheShelf/lightOn')}}';
                    let data = {stationCode:stationCode, materialBoxCode:materialBoxCode};

                    window.tempTip.setDuration(2000);
                    window.tempTip.setIndex(1999);

                    if(this.checkMaterialBoxCodeExist(materialBoxCode,stationCode)){
                        window.tempTip.show('料箱已被占用');
                        return ;
                    }
                    window.axios.post(url,data).then(res=>{
                        if(res.data.success){
                            window.tempTip.showSuccess(res.data.message ? res.data.message : '成功');
                            this.$set(this.currentStation.grids[stationCode],'materialBoxCode',materialBoxCode);
                            this.materialBoxCode = null;
                            this.$forceUpdate();
                            $('#material-box').focus();
                            return ;
                        }
                        window.tempTip.show('亮灯异常：'+res.data.message);
                    }).catch(err=>{
                        window.tempTip.show(err);
                    });
                },
                clearTask(stationCode){
                    let url = '{{url('apiLocal/station/cacheShelf/clearTask')}}';
                    let data = {station:stationCode};
                    window.tempTip.setDuration(2000);
                    window.tempTip.setIndex(1999);
                    window.axios.post(url,data).then(res=>{
                        if(res.data.success){
                            window.tempTip.showSuccess(res.data.message ? res.data.message : '取消任务成功');
                            this.$set(this.currentStation.grids[stationCode],'materialBoxCode',null);
                            this.$forceUpdate();
                            $('#material-box').focus();
                            return ;
                        }
                        window.tempTip.show('取消任务异常：'+res.data.message);
                    }).catch(err=>{
                        window.tempTip.show(err);
                    });
                },
                /** 校验是否存在 */
                checkMaterialBoxCodeExist(materialBoxCode,stationCode) {
                    for (const key in this.currentStation.grids) {
                        if(this.currentStation.grids[key]['materialBoxCode'] === materialBoxCode && key !== stationCode )return true;
                    }
                    return false;
                },
                /** 监听 【灭灯】 */
                _listenBroadcast() {
                    initEcho();
                    this.currentEcho = window.Echo.channel(this.broadcastName).listen(this.channelName, (msg) => {
                        let json = JSON.parse(msg.json);
                        if (!json || json.length === 0) return;
                        if(json['code'] !== this.currentStation.code)return ;
                        if(json['grid_code']){
                            if(json['type'] === 'success') this.$set(this.currentStation.grids[json['grid_code']],'materialBoxCode',null);
                            if(json['type'] === 'error') this.$set(this.currentStation.grids[json['grid_code']],'type','error');
                            this.$forceUpdate();
                        }
                    });
                },
            }
        })
    </script>
@endsection

