@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 d-none" id="container">
        <div id="form"></div>
        <div class="mt-1">
            <button type="button" class="btn btn-outline-dark btn-sm form-control-sm dropdown-toggle tooltipTarget" :class="[checkData.length>0?'btn-dark text-light':'']"
                    data-toggle="dropdown" title="导出所有页将会以搜索条件得到的筛选结果，将其全部记录（每一页）导出">
                导出Excel
            </button>
            <div class="dropdown-menu">
                <a class="dropdown-item" @click="executeExport(false)" href="javascript:">导出勾选内容</a>
                <a class="dropdown-item" @click="executeExport(true)" href="javascript:">导出所有页</a>
            </div>
            @can("入库管理-入库预约-质检")<button type="button" class="btn btn-outline-primary" @click="qualityInspectionMark()">质检</button>@endcan
        </div>
        <table class="table table-striped table-hover text-nowrap td-min-width-80" id="table">
            <tr class="text-center">
                <th>
                    <label for="all" id="cloneCheckAll">
                        <input id="all" type="checkbox" @click="checkAll($event)">全选
                    </label>
                </th>
                <th>序号</th>
                <th>操作</th>
                <th>状态</th>
                <th>货主</th>
                <th>预约时间</th>
                <th>仓库</th>
                <th>
                    <div class="row" style="min-width: 800px">
                        <div class="col-12">车辆信息</div>
                    </div>
                    <div class="row">
                        <div class="col-2">预约号</div>
                        <div class="col-2">车牌号</div>
                        <div class="col-2">车型</div>
                        <div class="col-1">司机姓名</div>
                        <div class="col-2">司机电话</div>
                        <div class="col-3">操作/送达时间</div>
                    </div>
                </th>
                <th>吨</th>
                <th>立方</th>
                <th>箱数</th>
                <th>快递公司</th>
                <th>快递单号</th>
                <th>采购单号</th>
                <th>ASN单号</th>
                <th>
                    <div class="row">
                        <div class="col-12 text-center">明细单</div>
                    </div>
                    <div class="row" style="min-width: 500px">
                        <div class="col-5 text-center">商品名称</div>
                        <div class="col-4 text-center">条码</div>
                        <div class="col-2 text-center">数量</div>
                    </div>
                </th>
                <th>预约备注</th>
                <th>创建时间</th>
            </tr>
            <tr v-for="(info,i) in list">
                <td>
                    <label>
                        <input class="checkItem" type="checkbox" :value="info.id" v-model="checkData">
                    </label>
                </td>
                <td>@{{ i+1 }}</td>
                <td>
                    <span v-if="info.status==0">
                        <button type="button" @click="cancel(info.id,i)" class="btn btn-sm btn-outline-danger">取消预约</button><br>
                        <button type="button" @click="updateDeliveryDate(info,i)" class="btn btn-sm btn-outline-primary">修改预约</button>
                    </span>
                    <span v-if="info.status==2">
                        <button type="button" @click="printReceipt(info)" class="btn btn-sm btn-outline-success"><i class="fa fa-print"></i>&nbsp;打印</button>
                    </span>
                </td>
                <td>
                    <span v-if="info.status==0 && info.cars.length>0 && info.cars[0].status==1">
                        <span class="fa fa-circle text-primary">作业中</span>
                    </span>
                    <span v-else>
                        <label v-if="!poolMapping.status">
                            <span class="fa fa-circle text-secondary">未知</span>
                        </label>
                        <label v-else>
                            <small><span class="fa fa-circle" :class="info.status==0 ? 'text-info' : (info.status==2 ? 'text-success' : 'text-danger')"></span></small>
                            @{{ poolMapping.status[info.status] }}
                            <span v-if="info.type_mark==0" class="badge badge-primary">质检单</span>
                        </label>
                    </span>

                </td>
                <td>
                    <label v-if="!poolMapping.owners"></label>
                    <label v-else>@{{ poolMapping.owners[info.owner_id] }}</label>
                </td>
                <td class="text-primary">@{{ info.appointment_date }}&nbsp;&nbsp;@{{ info.period }}</td>
                <td>
                    <label v-if="!poolMapping.warehouses"></label>
                    <label v-else>@{{ poolMapping.warehouses[info.warehouse_id] }}</label>
                </td>
                <td>
                    <div v-if="info.cars.length>0" class="text-center">
                        <div class="row">
                            <div class="col-2 font-weight-bold">@{{ info.cars[0].appointment_number }}</div>
                            <div class="col-2 text-secondary">@{{ info.cars[0].license_plate_number }}</div>
                            <div class="col-2 text-secondary">@{{ info.cars[0].car ? info.cars[0].car.name : '' }}</div>
                            <div class="col-1 text-secondary">@{{ info.cars[0].driver_name }}</div>
                            <div class="col-2 text-secondary">@{{ info.cars[0].driver_phone }}</div>
                            <div class="col-3">
                                @can("入库管理-入库预约-预约管理-卸货完成")<button class="btn btn-sm btn-outline-success" @click="unloading(i,0)" v-if="info.cars[0].status==1">卸货完成</button>@endcan
                                <div v-if="info.cars[0].status==2">@{{ info.cars[0].delivery_time }}</div>
                            </div>
                        </div>
                        <div class="up" :id="'item-'+info.id" v-show="info.cars.length>1">
                            <div class="row" v-for="(car,j) in info.cars" v-if="j!==0">
                                <div class="col-2 font-weight-bold">@{{ car.appointment_number }}</div>
                                <div class="col-2 text-secondary">@{{ car.license_plate_number }}</div>
                                <div class="col-2 text-secondary">@{{ car.car ? car.car.name : '' }}</div>
                                <div class="col-1 text-secondary">@{{ car.driver_name }}</div>
                                <div class="col-2 text-secondary">@{{ car.driver_phone }}</div>
                                <div class="col-3">
                                    @can("入库管理-入库预约-预约管理-卸货完成")<button class="btn btn-sm btn-outline-success" @click="unloading(i,j)" v-if="car.status==1">卸货完成</button>@endcan
                                    <div v-if="car.status==2">@{{ car.delivery_time }}</div>
                                </div>
                            </div>
                        </div>
                        <div class="text-center m-auto small cursor-pointer" v-if="info.cars.length>1" @click="upAll(info.id)">
                            <span class="fa" :class="upList[info.id] ? 'fa-angle-double-down' : 'fa-angle-double-right'" style="margin-top: 2px;"></span>&nbsp;
                            <span v-if="upList[info.id]">收起其余@{{ info.cars.length-1 }}条</span>
                            <span v-else>展开其余@{{ info.cars.length-1 }}条</span>
                        </div>
                    </div>
                </td>
                <td>@{{ info.tonne>0 ? info.tonne : '-' }}</td>
                <td>@{{ info.cubic_meter>0 ? info.cubic_meter : '-' }}</td>
                <td>@{{ info.box_amount>0 ? info.box_amount : '-' }}</td>
                <td>@{{ info.logistic ? info.logistic.name : '' }}</td>
                <td>@{{ info.logistic_number }}</td>
                <td><span v-html="warpText(info.procurement_number)"></span></td>
                <td><span v-html="warpText(info.asn_number)"></span></td>
                <td>
                    <div v-if="info.details.length>0">
                        <div class="row">
                            <div class="col-5 font-weight-bold text-overflow-warp">@{{ info.details[0].commodity_id ? (info.details[0].commodity ? info.details[0].commodity.name : '') : info.details[0].name }}</div>
                            <div class="col-4 text-secondary text-overflow-warp">@{{ info.details[0] | getCommodity }}</div>
                            <div class="col-2 text-secondary">@{{ info.details[0].amount }}</div>
                        </div>
                        <div class="up" :id="'detail-'+info.id" v-show="info.details.length>1">
                            <div class="row" v-for="(detail,i) in info.details" v-if="i!==0">
                                <div class="col-5 font-weight-bold text-overflow-warp">@{{ detail.commodity_id ? (detail.commodity ? detail.commodity.name : '') : detail.name }}</div>
                                <div class="col-4 text-secondary text-overflow-warp">@{{ detail | getCommodity }}</div>
                                <div class="col-2 text-secondary">@{{ detail.amount }}</div>
                            </div>
                        </div>
                        <div class="text-center m-auto small cursor-pointer" v-if="info.details.length>1" @click="upAllDetail(info.id)">
                            <span class="fa" :class="upListDetail[info.id] ? 'fa-angle-double-down' : 'fa-angle-double-right'" style="margin-top: 2px;"></span>&nbsp;
                            <span v-if="upListDetail[info.id]">收起其余@{{ info.details.length-1 }}条</span>
                            <span v-else>展开其余@{{ info.details.length-1 }}条</span>
                        </div>
                    </div>
                </td>
                <td>@{{ info.remark }}</td>
                <td>@{{ info.created_at }}</td>
            </tr>
        </table>
        @include("store.deliveryAppointment._selectDate")
        @include("store.deliveryAppointment._printBody")
        @include("store.deliveryAppointment._printInfo")
    </div>
@stop

@section("lastScript")
    <script type="text/javascript" src="{{mix('js/queryForm/export.js')}}"></script>
    <script type="text/javascript" src="{{mix('js/queryForm/queryForm.js')}}"></script>
    <script>
        new Vue({
            el:"#container",
            data:{
                list:[@foreach($list as $data)@json($data),@endforeach],
                status:[],
                warehouses:[],
                owners:[@foreach($owners as $owner){name:"{{$owner->id}}",value:"{{$owner->name}}"},@endforeach],
                checkData:[],
                poolMapping:{},
                upList:{},
                upListDetail:{},
                sum:Number("{{$list->total()}}"),
                capacities:[],
                btnName:"确定修改预约",
                index:"",
                selectDate:{},
                periods:@json(\App\DeliveryAppointment::PERIOD),
                printInfo:{},
                infoShow:false,
            },
            mounted(){
                let status = [];
                let statusMap = {};
                let warehouses = [];
                let warehouseMap = {};
                let owners = [];
                let ownerMap = [];

                @foreach(\App\DeliveryAppointment::STATUS as $index=>$status)
                status.push({name:"{{$index}}",value:"{{$status}}"});
                statusMap["{{$index}}"] = "{{$status}}";
                @endforeach
                this.status = status;
                this.$set(this.poolMapping,"status",statusMap);

                @foreach($warehouses as $warehouse)
                warehouses.push({name:"{{$warehouse->id}}",value:"{{$warehouse->name}}"});
                warehouseMap["{{$warehouse->id}}"] = "{{$warehouse->name}}";
                @endforeach
                this.warehouses = warehouses;
                this.poolMapping.warehouses = warehouseMap;

                @foreach($owners as $owner)
                owners.push({name:"{{$owner->id}}",value:"{{$owner->name}}"});
                ownerMap["{{$owner->id}}"] = "{{$owner->name}}";
                @endforeach
                this.owners = owners;
                this.poolMapping.owners = ownerMap;

                $(".up").slideUp();
                $("#container").removeClass("d-none");
                this._renderingForm();
            },
            watch:{
                checkData:{
                    handler(){
                        document.querySelector('#all').checked = this.checkData.length === this.list.length;
                    },
                    deep:true
                },
            },
            methods: {
                exePrint(){
                    this.infoShow = true;
                    if (!this.printInfo.signer){
                        window.tempTip.setIndex(1099);
                        window.tempTip.show("请填写签收人");
                        return;
                    }
                    $("#printModal").modal('hide');
                    let iframe=document.getElementById("print-iframe");
                    if(!iframe){
                        let el = document.getElementById("printContent");
                        iframe = document.createElement('IFRAME');
                        iframe.setAttribute("id", "print-iframe");
                        iframe.setAttribute('style', 'position:absolute;width:0;height:0;left:-500px;top:-500px;');
                        document.body.appendChild(iframe);
                        let doc = iframe.contentWindow.document;
                        doc.write('<LINK rel="stylesheet" type="text/css" href="{{ asset(mix("css/app.css")) }}">');
                        doc.write('<div>' + el.innerHTML + '</div>');
                        doc.close();
                        iframe.contentWindow.focus();
                    }
                    this.infoShow = false;
                    setTimeout(function () {
                        iframe.contentWindow.print();
                        if (navigator.userAgent.indexOf("MSIE") > 0){
                            document.body.removeChild(iframe);
                        }
                    },200);
                },
                _renderingForm(){
                    let data=[
                        [
                            {name:'created_at_start',type:'dateTime',tip:"选择显示创建日期的结束时间"},
                            {name:'appointment_date_start',type:'dateTime',tip:"选择显示预约日期的结束时间"},
                            {name:'owner_id',type:'select_multiple_select',tip:['输入关键词快速定位下拉列表，回车确定','选择要显示的客户'],
                                placeholder:['货主','定位或多选货主'],data:this.owners},
                            {name:'status',type:'select',placeholder: '状态',data:this.status},
                        ],
                        [
                            {name:'created_at_end',type:'dateTime',tip:"选择显示创建日期的结束时间"},
                            {name:'appointment_date_end',type:'dateTime',tip:"选择显示预约日期的结束时间"},
                            {name:'warehouse_id',type:'select',placeholder: '仓库',data:this.warehouses},
                        ],
                    ];
                    let form = new query({
                        el:"#form",
                        condition:data,
                    });
                    form.init();
                },
                upAll(id){
                    let dom = "#item-"+id;
                    if (this.upList[id]) $(dom).slideUp();
                    else $(dom).slideDown();
                    this.$set(this.upList,id,!this.upList[id]);
                },
                upAllDetail(id){
                    let dom = "#detail-"+id;
                    if (this.upListDetail[id]) $(dom).slideUp();
                    else $(dom).slideDown();
                    this.$set(this.upListDetail,id,!this.upListDetail[id]);
                },
                unloading(i,j){
                    window.tempTip.confirm("确定已经完成卸货？",()=>{
                        window.tempTip.postBasicRequest("{{url('store/deliveryAppointment/unloading')}}",{id:this.list[i].cars[j].id},res=>{
                            this.list[i].cars[j].status = 2;
                            if (this.list[i].cars.every(car=>{
                                if (car.status!=2)return false;
                                return true
                            }))this.list[i].status = 2;
                            return "成功确认";
                        })
                    })
                },
                cancel(id,index){
                    window.tempTip.confirm("确定要取消该次预约吗？此操作不可逆，请谨慎选择",()=>{
                        window.tempTip.postBasicRequest("{{url('store/deliveryAppointment/cancel')}}",{id:id},res=>{
                            this.$set(this.list[index],"status",res);
                            return "成功取消该单预约";
                        })
                    })
                },
                checkAll(e){
                    if (e.target.checked){
                        this.checkData = [];
                        this.list.forEach((el)=>{
                            this.checkData.push(el.id);
                        });
                    }else this.checkData = [];
                },
                executeExport(isAll){
                    let url = '{{url('store/deliveryAppointment/export')}}';
                    let token='{{ csrf_token() }}';
                    excelExport(isAll,this.checkData,url,this.sum,token);
                },
                updateDeliveryDate(info,index){
                    for (let i=0;i<info.cars.length;i++){
                        if (info.cars[i].status!=0){
                            window.tempTip.setDuration("3000");
                            window.tempTip.show("车辆已达，无法修改预约");
                            return;
                        }
                        this.index = index;
                        let param = {
                            model:info,
                            detail_amount:info.details.length,
                        };
                        window.tempTip.postBasicRequest("{{url('store/deliveryAppointment/getCapacity')}}",param,res=>{
                            this.capacities = res;
                            $("#modal").modal("show");
                        });
                    }
                },
                submitAppointment(){
                    window.tempTip.setDuration(3000);
                    window.tempTip.setIndex(1099);
                    if (!this.selectDate.date){
                        window.tempTip.show("尚未选择预约时间");
                        return;
                    }
                    let url = "{{url('store/deliveryAppointment/updateAppointment')}}";
                    let param = {
                        id:this.list[this.index].id,
                        date:this.selectDate,
                    };
                    window.tempTip.postBasicRequest(url,param,res=>{
                        if (res && 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;
                        }
                        this.list[this.index].appointment_date = this.selectDate.date;
                        this.list[this.index].date_period = this.selectDate.time;
                        this.list[this.index].period = this.periods[this.selectDate.time];
                        $("#modal").modal("hide");
                        return "修改预约时间成功";
                    },true);
                },
                selectPeriod(date,time,isSelect){
                    if (isSelect) this.selectDate = {date:date,time:time};
                },
                qualityInspectionMark(){
                    if (this.checkData.length<1){
                        window.tempTip.setDuration("3000");
                        window.tempTip.show("未勾选记录");
                        return;
                    }
                    let url = "{{url('store/deliveryAppointment/qualityInspectionMark')}}";
                    window.tempTip.postBasicRequest(url,{ids:this.checkData},()=>{
                        this.list.forEach(data=>{
                            if (this.checkData.indexOf(data.id)!==-1){
                                data.type_mark = 0;
                            }
                        });
                        return "标记质检成功";
                    });
                },
                printReceipt(info){
                    let d = new Date();
                    let str = '';
                    str += d.getFullYear() + '年';
                    str += d.getMonth() + 1 + '月';
                    str += d.getDate() + '日';
                    str += d.getHours() + '时';
                    str += d.getMinutes() + '分';
                    str += d.getSeconds() + '秒';

                    this.printInfo = info;
                    this.printInfo.print_date = str;
                    $("#printModal").modal("show");
                },
                warpText(code){
                    if (!code)return code;
                    code = code.split(/[,， ]+/is);
                    let str = "";
                    for (let i=0;i<code.length;i++){
                        str += code[i]+"<br>";
                    }
                    return str;
                }
            },
            filters:{
                getCommodity(detail){
                    if (!detail.commodity_id)return detail.name;
                    if (detail.commodity && detail.commodity.barcodes.length>0)return detail.commodity.barcodes[0].code;
                    return "";
                },
            },
        });
    </script>
@stop