<?php
?>
<style type="text/css">

</style>
<div class="layui-form-item {{ $errors->has('project_id') ? 'has-error' : '' }}">
    <label class="layui-form-label" style="padding: 0px;">在用项目</label>
    <div class="layui-input-block">
        <select name="project_id" lay-filter="project_id">
            @foreach($options as $option)
                <option value="{{$option->value}}" {{$option->value == $project_id ? 'selected' : ''}}>{{$option->text}}</option>
            @endforeach
        </select>
        @if($errors->has('project_id'))
            <span class="help-block">{{ $errors->first('project_id') }}</span>
        @endif
    </div>
    @if($errors->has('project_id'))
        <span class="help-block">{{ $errors->first('project_id') }}</span>
    @endif
</div>

@if(!isset($hide_spec))
<div class="layui-form-item {{ $errors->has('work_point_id') ? 'has-error' : '' }}">
    <label class="layui-form-label" style="padding: 0px;">目前工点</label>
    <div class="layui-input-block">
        <select name="work_point_id" lay-filter="work_point_id">
        </select>
        @if($errors->has('work_point_id'))
            <span class="help-block">{{ $errors->first('work_point_id') }}</span>
        @endif
    </div>
</div>
@endif
<script>
    $(function() {
        layui.use(['form'], function() {
            let form = layui.form;
            let projects = JSON.parse('{!! $options !!}');
            let work_points = [];
            let project_id = '{{ $project_id }}';
            let work_point_id = '{{ $work_point_id }}';
            let hide_spec = '{{ isset($hide_spec) ? "yes" : "no" }}';
            // console.log(hide_spec)

            form.on('select(project_id)', function(data) {
                project_id = data.value;
                work_point_id = '';
                updateWorkPoint()
            });

            updateWorkPoint();

            function updateWorkPoint() {
                let name_index = getIndex(projects, project_id);
                work_points = projects[name_index].work_points;
                let options = '';
                for(let i = 0; i < work_points.length; ++i) {
                    options += '<option value=' + work_points[i].value + (parseInt(work_points[i].value) === parseInt(work_point_id) ? ' selected' : '') + '>' + work_points[i].text + '</option>'
                }
                $("select[name='work_point_id']").html(options);
                form.render('select');
            }

            function getIndex(list, id) {
                id = parseInt(id);
                for(var i = 0; i < list.length; ++i) {
                    if(list[i].value === id) return i;
                }
                return 0;
            }
        })
    })
</script>
