@extends('layouts.app')
@section('title')入库预约@endsection

@section('content')
    <span id="nav2">
    @component('store.menu')@endcomponent
    @component('store.deliveryAppointment.menu')@endcomponent
    </span>
    <div class="container-fluid" id="container">
        <div class="card">
            <div class="card-body row">
                <div class="offset-2 col-8">
                    <div class="card">
                        <div class="card-header">
                            <div class="row">
                                <label class="col-2">
{{--                                    <label class="text-danger font-weight-bold ml-2 h4">*</label>--}}
                                </label>
                                <label class="col-2">车牌号</label>
                                <label class="col-2">车型</label>
                                <label class="col-2">司机姓名</label>
                                <label class="col-3">司机电话</label>
                                {{--<label class="col-1">
                                    <span class="fa fa-plus cursor-pointer text-primary" @click="addCar()">增加</span>
                                </label>--}}
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="row" v-for="(car,i) in model.cars">
                                <label class="col-2">车辆-@{{ i+1 }}</label>
                                <label class="col-2">
                                    <input type="text" class="form-control" v-model="car.license_plate_number" :class="errors['cars.'+i+'.license_plate_number'] ? 'is-invalid' : ''">
                                </label>
                                <label class="col-2">
                                    <div class="dropdown">
                                        <input type="text" class="form-control" v-model="car.car_name" :id="'car-'+i" @input="searchCar(car.car_name)"
                                               data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" @click="searchInit()">
                                        <div class="dropdown-menu" :aria-labelledby="'car-'+i" v-show="haystack.length>0">
                                            <span class="row offset-1 text-secondary" v-for="c in haystack" @click.stop="selectCar(c,i)">@{{ c.name }}<br></span>
                                        </div>
                                    </div>
                                </label>
                                <label class="col-2">
                                    <input type="text" class="form-control" v-model="car.driver_name">
                                </label>
                                <label class="col-3">
                                    <input type="text" class="form-control" v-model="car.driver_phone">
                                </label>
                                {{--<label class="col-1" v-if="i!==0">
                                    <span class="h4 font-weight-bold cursor-pointer text-danger" @click="delCar(i)">&times;</span>
                                </label>--}}
                                <label v-if="errors['cars.'+i+'.license_plate_number']" class="col-2 offset-2 text-danger font-weight-bold small">
                                    @{{ errors['cars.'+i+'.license_plate_number'][0] }}
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="row mt-4 ml-1">
                        <label class="col-2" for="ownerId"><b class="text-danger">*&nbsp;</b>货主</label>
                        <select id="ownerId" v-model="model.owner_id" class="col-4 form-control" :class="errors.owner_id ? 'is-invalid' : ''">
                            <option v-for="owner in owners" :value="owner.id">@{{ owner.name }}</option>
                        </select>
                        <label class="col-2"><input class="form-control rounded-pill" placeholder="搜索货主" @input="seekOwner($event)"></label>
                    </div>
                    <label class="row mt-0 mb-0 ml-1" v-if="errors.owner_id">
                        <label class="offset-2 text-danger font-weight-bold small">@{{ errors.owner_id[0] }}</label>
                    </label>
                    <div class="row mt-4 ml-1">
                        <label class="col-2" for="procurementNumber">采购单号</label>
                        <input class="col-6 form-control" type="text" id="procurementNumber" v-model="model.procurement_number" :class="errors.procurement_number ? 'is-invalid' : ''">
                    </div>
                    <div class="row mt-2 ml-1">
                        <label class="col-2" for="asnNumber">ASN单号</label>
                        <input class="col-6 form-control" placeholder="可以输入多个，使用空格或逗号分隔" @blur="verifyASN()"
                               type="text" id="asnNumber" v-model="model.asn_number" :class="errors.asn_number ? 'is-invalid' : ''">
                    </div>
                    <div class="row mt-2 ml-1">
                        <label class="col-2" for="logistic_number">快递单号</label>
                        <input class="col-6 form-control" type="text" id="logistic_number" v-model="model.logistic_number" :class="errors.logistic_number ? 'is-invalid' : ''">
                    </div>
                    <div class="row mt-2 ml-1">
                        <label class="col-2" for="logistic">快递公司</label>
                        <select id="logistic" v-model="model.logistic_id" class="col-4 form-control" :class="errors.logistic_id ? 'is-invalid' : ''">
                            <option v-for="logistic in logistics" :value="logistic.id">@{{ logistic.name }}</option>
                        </select>
                    </div>
                    <div class="row mt-2 ml-1">
                        <label class="col-2" for="warehouse"><b class="text-danger">*&nbsp;</b>仓库</label>
                        <select id="warehouse" v-model="model.warehouse_id" class="col-4 form-control" :class="errors.warehouse_id ? 'is-invalid' : ''">
                            <option v-for="warehouse in warehouses" :value="warehouse.id">@{{ warehouse.name }}</option>
                        </select>
                    </div>
                    <label class="row mt-0 mb-0 ml-1" v-if="errors.warehouse_id">
                        <label class="offset-2 text-danger font-weight-bold small">@{{ errors.warehouse_id[0] }}</label>
                    </label>
                    <div class="row mt-2 ml-1">
                        <label class="col-2" for="cubic_meter"><b class="text-danger">*&nbsp;</b>立方</label>
                        <input class="col-3 form-control" type="number" step="0.01" min="0" id="cubic_meter" v-model="model.cubic_meter" :class="errors.cubic_meter ? 'is-invalid' : ''">
                        <label class="col-1 offset-2" for="tonne"><b class="text-danger">*&nbsp;</b>吨</label>
                        <input class="col-3 form-control" type="number" step="0.01" min="0" id="tonne" v-model="model.tonne" :class="errors.tonne ? 'is-invalid' : ''">
                    </div>
                    <label class="row mt-0 mb-0 ml-1" v-if="errors.cubic_meter || errors.tonne">
                        <label class="offset-2 text-danger col-3 small"><b v-if="errors.cubic_meter">@{{ errors.cubic_meter[0] }}</b></label>
                        <label class="offset-3 text-danger font-weight-bold small" v-if="errors.tonne">@{{ errors.tonne[0] }}</label>
                    </label>
                    <div class="row mt-2 ml-1">
                        <label class="col-2" for="box_amount">箱数</label>
                        <input class="col-3 form-control" step="1" min="0" type="number" id="box_amount" v-model="model.box_amount" :class="errors.box_amount ? 'is-invalid' : ''">
                    </div>
                    <label class="row mt-0 mb-0 ml-1" v-if="errors.box_amount">
                        <label class="offset-2 text-danger font-weight-bold small">@{{ errors.box_amount[0] }}</label>
                    </label>
                    <div class="row mt-2 ml-1">
                        <label class="col-2" for="isUpload">是否上传明细单</label>
                        <input content="col-3" id="isUpload" type="checkbox" class="switch" v-model="model.is_upload">
                        <button id="openFile" type="button" class="col-2 offset-1 btn btn-info text-white"
                                title="表头必须包含：商品名称 数量 条码"
                                :data-toggle="errors.details ? 'popover' : 'tooltip'"
                                v-show="model.is_upload" @click="openFile()">
                            <span class="fa fa-cloud-upload"></span> 选择文件</button>
                        <span v-if="model.is_upload" class="text-secondary mt-1">&nbsp;@{{ fileName }}</span>
                        <label hidden><input type="file" id="file" accept=".csv, .xlsx, .xls" @change="selectedFile($event)"></label>
                    </div>
                    <div class="row mt-2 ml-1">
                        <label class="col-2" for="remark">预约备注</label>
                        <textarea class="col-6 form-control" v-model="model.remark" id="remark"></textarea>
                    </div>
                    <div class="row mt-4 ml-1">
                        <button type="button" class="btn btn-success col-8 offset-2" @click="submit()">提 交 预 约</button>
                    </div>
                </div>
                @include("store.deliveryAppointment._selectDate")
            </div>
        </div>
    </div>
@stop

@section("lastScript")
    <script>
        new Vue({
            el:"#container",
            data:{
                cars:[@foreach($cars as $car)@json($car),@endforeach],
                model:{
                    cars:[{license_plate_number:"",car_id:"",driver_name:"",driver_phone:""}],
                },
                owners:[@foreach($owners as $owner)@json($owner),@endforeach],
                warehouses:[@foreach($warehouses as $warehouse)@json($warehouse),@endforeach],
                logistics:[@foreach($logistics as $logistic)@json($logistic),@endforeach],
                fileName:"",
                details:[],
                errors : {
                    details:"",
                },
                haystack:[],
                capacities:[],
                selectDate:{},
                btnName:"确定预约",
            },
            mounted(){
                if (this.owners.length === 1)this.$set(this.model,"owner_id",this.owners[0].id);
                $('#openFile').tooltip();
            },
            methods:{
                searchInit(){
                    let stack = [];
                    this.cars.forEach(car=>{
                        stack.push(car);
                    });
                    this.haystack = stack;
                },
                selectCar(car,index){
                    this.model.cars[index].car_id = car.id;
                    this.model.cars[index].car_name = car.name;
                    this.haystack = [];
                },
                searchCar(name){
                    if (!name){
                        this.haystack = [];
                        return;
                    }
                    let stack = [];
                    this.cars.forEach(car=>{
                        if (car.name.indexOf(name)!==-1)stack.push(car);
                    });
                    this.haystack = stack;
                },
                seekOwner(e){
                    let val = e.target.value;
                    this.owners.some(owner=>{
                        if (owner.name.indexOf(val)!==-1){
                            this.$set(this.model,"owner_id",owner.id);
                            return true;
                        }
                    })
                },
                openFile(){
                    $('#file').click();
                },
                selectedFile(e){
                    window.tempTip.setDuration(3000);
                    let file=e.target.files[0];
                    if (!file)return;
                    this.fileName = file.name;
                    let formData = new FormData();
                    formData.append("file",file);
                    window.axios.post('{{url('store/deliveryAppointment/appointment/import')}}',formData,{
                        'Content-Type':'multipart/form-data'
                    }).then(res=>{
                        if (!res.data.success){
                            window.tempTip.setDuration(3000);
                            window.tempTip.show(res.data.data);
                        }else{
                            let arr = res.data.data;
                            let details = [];
                            for(let key  in arr.data){
                                let data=arr.data[key];
                                details.push({name:data["商品名称"],amount:data["数量"],bar_code:data["条码"]});
                            }
                            this.details = details;
                            if (Object.keys(arr.errors).length>0){
                                let err = "<span class='text-danger'>";
                                for(let key  in arr.errors){
                                    let errors=arr.errors[key];
                                    err += "<b class='text-dark'>第"+key+"行</b>"+"<br>";
                                    errors.forEach(error=>{
                                        err += "&nbsp;&nbsp;&nbsp;&nbsp;"+error+"<br>";
                                    });
                                }
                                err += "</span>";
                                this.errors.details = err;
                                $('#openFile').tooltip('dispose').attr("title","明细错误信息").popover({
                                    html: true,
                                    content: err,
                                    placement:'right',
                                    trigger:'focus'
                                }).popover('show');
                            }else $('#openFile').popover('dispose').tooltip('show');
                        }
                    }).catch(err=> {
                        window.tempTip.show("网络错误："+err);
                    })
                },
                addCar(){
                    this.model.cars.push({});
                },
                delCar(index){
                    this.$delete(this.model.cars,index);
                },
                submit(){
                    let errors = {};
                    if (!this.model.owner_id)errors.owner_id = ["不得为空"];
                    if (!this.model.warehouse_id)errors.warehouse_id = ["不得为空"];
                    if (!this.model.tonne && !this.model.cubic_meter){
                        errors.tonne = ["吨与立方值至少填写一个"];
                        errors.cubic_meter = ["立方值与吨至少填写一个"];
                    }
                    let change = [];
                    let insert = [];
                    this.model.cars.forEach((car,i)=>{
                        //if (!car.license_plate_number) errors["cars."+i+".license_plate_number"] = ["不得为空"];
                        if (!car.car_id && car.car_name){
                            if (this.cars.every(c=>{
                               if (c.name === car.car_name){
                                   car.car_id = c.id;
                                   return false;
                               }
                               return true;
                            })){
                                change.push({index:i,name:car.car_name});
                                if (insert.indexOf(car.car_name)===-1)insert.push(car.car_name);
                            }
                        }
                    });
                    if (JSON.stringify(errors) !== "{}"){
                        errors.details=this.errors.details;
                        this.errors = errors;
                        return
                    }
                    if (change.length>0)this._addCars(insert,change);
                    let param = {
                        model:this.model,
                        detail_amount:this.details.length,
                    };
                    window.tempTip.postBasicRequest("{{url('store/deliveryAppointment/getCapacity')}}",param,res=>{
                        if (res.errors) {
                            this.errors = res.errors;
                            return;
                        }
                        this.capacities = res;
                        $("#modal").modal("show");
                    });
                },
                _addCars(arr,change){
                    window.tempTip.postBasicRequest("{{url('maintenance/carType/batchInsert')}}",{arr:arr},res=>{
                        res.forEach(data=>{
                            change.forEach(car=>{
                                if (data.name === car.name)this.model.cars[car.index].car_id = data.id;
                            });
                        });
                    });
                },
                selectPeriod(date,time,isSelect){
                    if (isSelect) this.selectDate = {date:date,time:time};
                },
                submitAppointment(){
                    window.tempTip.setDuration(3000);
                    window.tempTip.setIndex(1099);
                    if (!this.selectDate.date){
                        window.tempTip.show("尚未选择预约时间");
                        return;
                    }
                    let url = "{{url('store/deliveryAppointment/submitAppointment')}}";
                    let param = {
                        model:this.model,
                        details:this.details,
                        date:this.selectDate,
                    };
                    window.tempTip.postBasicRequest(url,param,res=>{
                        if (res.errors){
                            this.errors = res.errors;
                            return;
                        }
                        if (res.isFail){
                            this.capacities.some(capacity=>{
                                if (capacity.date === this.selectDate.date){
                                    capacity.period.some(p=>{
                                        if (p.index === this.selectDate.time){
                                            p.isAvailable = false;
                                            return true;
                                        }
                                    });
                                    return true;
                                }
                            });
                            this.selectDate={};
                            window.tempTip.show("该预约时段已经被抢占了，请选择其他时段");
                            return;
                        }
                        window.location.href = "{{url('store/deliveryAppointment/showAppointmentInfo?k=')}}"+res.key;
                    },true);
                },
                verifyASN(){
                  if (!this.model.asn_number)return;
                  let url = "{{url('store/deliveryAppointment/verifyASN')}}";
                  window.tempTip.postBasicRequest(url,{asn:this.model.asn_number},res=>{
                      if (!res)return  "ASN单不存在明细项";
                      let details = [];
                      res.forEach(item=>{
                          details.push({name:"",amount:item.amount,bar_code:"",commodity_id:item.commodity_id});
                      });
                      this.details = details;
                      this.fileName = (details.length)+"条明细";
                      return "成功匹配ASN，"+(details.length)+"条明细";
                  })
                },
            },
        });
    </script>
@stop
