@extends('layouts.app')
@section('title')采购管理-采购-查询@endsection

@section("content")
    @component('procurement.procurement.menu')@endcomponent
    <div class="container-fluid" id="list">
        <div class="card container-fluid">
            @if(Session::has('successTip'))
                <div class="alert alert-success h1">{{Session::get('successTip')}}</div>
            @endif
            <div class="row">
                <div class="col-4">
                    <div class="row pt-2">
                        <span class="fa fa-shopping-cart fa-4x offset-md-3" style="color: #4c2584;opacity: 0.3"></span>
                        <span class="ml-4 mt-2">
                                <h5 class="font-weight-bold">@{{ countReceive }}</h5>
                                <p class="text-muted">今日收货次数</p>
                            </span>
                    </div>
                </div>
                <div class="col-4">
                    <div class="row pt-2">
                        <span class="fa fa-file-o fa-4x offset-md-3" style="color: #9fcdff;opacity: 0.3"></span>
                        <span class="ml-4 mt-2">
                                <h5 class="font-weight-bold">@{{ countProcurement }}</h5>
                                <p class="text-muted">今日发起采购次数</p>
                            </span>
                    </div>
                </div>
                <div class="col-4">
                    <div class="row pt-2">
                        <span class="fa fa-calendar-o fa-4x offset-md-3" style="color: #2ca02c;opacity: 0.3"></span>
                        <span class="ml-4 mt-2">
                        <h5 class="font-weight-bold">0</h5>
                        <p class="text-muted">今日对账金额</p>
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <div id="form_div" class="mt-1"></div>
        <div class="row mt-2">
        <span class="dropdown ml-3">
        <button class="btn btn-outline-dark btn-sm form-control-sm dropdown-toggle tooltipTarget"
                data-toggle="dropdown" title="导出所有页将会以搜索条件得到的筛选结果，将其全部记录（每一页）导出">
            导出Excel
        </button>
        <div class="dropdown-menu">
            <a class="dropdown-item" @click="procurementExport(false)" href="javascript:">导出勾选内容</a>
            <a class="dropdown-item" @click="procurementExport(true)" href="javascript:">导出所有页</a>
        </div>
        </span>
            <span class="btn btn-sm btn-outline-info ml-2" @click="addProcurement">新增采购</span>
            <span class="btn btn-sm btn-outline-success ml-2" @click="addEnquiry">新增询价</span>
            <span class="btn btn-sm btn-outline-danger ml-2" @click="addProof">新增打样</span>
            @can('采购管理-采购-新建')
                @include('procurement.procurement._addProcurement')
            @endcan
            @can('采购管理-采购-编辑')
                @include('procurement.procurement._addQuantity')
            @endcan
            <span class="btn btn-sm btn-outline-primary ml-2" @click="createAnew()">重新发起</span>
        </div>
        <table class="table table-sm table-striped table-bordered table-hover text-nowrap card-body mt-2 td-min-width-80" id="table">
            <tr v-for="(procurement,i) in procurements"  @click="selectTr===i+1?selectTr=0:selectTr=i+1" :class="selectTr===i+1?'focusing' : ''">
                <td>
                    <input class="checkItem" type="checkbox" :value="procurement.id">
                </td>
                <td><span class="text-center">@{{ procurement.code }}</span></td>
                <td>
                    <span v-if="procurement_status[procurement.status]!='订单取消'">
                        <span class="btn btn-sm btn-outline-secondary" v-if="procurement.status<3"
                              @click="cancel(procurement.id,procurement.type,procurement.code)">取消</span>
                         @can('采购管理-采购-提前确定')
                        <span class="btn btn-sm btn-outline-success" v-if="procurement_type[procurement.type]=='询价单' && procurement.status==1"
                              @click="initiateProcurement(procurement)">发起采购</span>
                        <span class="btn btn-sm btn-outline-info" v-if="procurement_type[procurement.type]=='采购单' && procurement.status==1"
                              @click="initiateProcurement(procurement)">提前确定</span>
                        @else
                            <span class="btn btn-sm btn-outline-success" v-if="procurement_type[procurement.type]=='询价单' && procurement.isFinishEnquiry"
                                  @click="initiateProcurement(procurement)">发起采购</span>
{{--                            <span class="btn btn-sm btn-outline-info" v-if="procurement_type[procurement.type]=='采购单' && procurement.status==1"--}}
{{--                                  @click="initiateProcurement(procurement)">提前确定</span>--}}
                        @endcan
                    </span>
                </td>
                <td class="text-center">
                    <span :class="[procurement.type==1?'text-info font-weight-bold':procurement.type==2?'text-success font-weight-bold':'']">@{{ procurement_type[procurement.type] }}</span>
                </td>
                <td class="text-center">
                    <span :class="[procurement.status==10?'text-danger font-weight-bold':procurement.status==9?'text-success font-weight-bold':'']"  >@{{ procurement_status[procurement.status] }}</span>
                </td>

                <td class="text-center text-muted"><span v-if="procurement.owner_material.owner">@{{ procurement.owner_material.owner.name }}</span></td>
{{--                <td><span v-if="procurement.owner_material.owner">@{{ procurement.owner_material.owner.customer? procurement.owner_material.owner.customer.company_name:'' }}</span></td>--}}
                <td class="tooltipTarget text-center" style="max-width: 200px;overflow:hidden"><span v-if="procurement.owner_material">@{{ procurement.owner_material.material_code }}</span></td>
                <td class="text-center text-muted"><span v-if="procurement.owner_material.material">@{{ procurement.owner_material.material.name }}</span></td>
                <td class="text-center"><span v-if="procurement.owner_material">@{{ procurement.owner_material.size }}</span></td>
                <td class="text-center text-muted"><span v-if="procurement.owner_material">@{{ procurement.owner_material.special }}</span></td>
                <td class="text-center"><span v-if="procurement.owner_material">@{{ procurement.owner_material.specification }}</span></td>
                <td class="text-center">
                    <div class="align-center text-center" >
                            <span v-if="procurement.owner_material.file">
                        <a target='_blank' :href="getDownFileUrl(procurement.owner_material)" class="text-primary text-decoration is-hover"  style="cursor: default" >
                            <i class="fa fa-download"></i>&nbsp;@{{ procurement.owner_material.file.file_name }}
                        </a>
                    </span>
                            <span v-else>-</span>
                    </div>
                </td>
{{--                <td>--}}
{{--                    <span v-if="procurement_type[procurement.type]=='询价单' && procurement.supplier" >@{{ procurement.supplier.name ??  '' }}</span>--}}
{{--                    <span  v-if="procurement.supplier">@{{ procurement.supplier.name ??  '' }}</span>--}}
{{--                </td>--}}
                <td class="text-center" style="min-width: 80px">
                    <div :class="procurement.procurement_quotations&&procurement.procurement_quotations.length==1 ? '' : 'up'" :id="'procurement_quotation-'+i">
                        <div v-for="procurement_quotation in procurement.procurement_quotations" class="row">
                            <div class="col-6  border border-1"><span v-if="procurement_quotation.supplier">@{{ procurement_quotation.supplier.name }}</span></div>
                            <div class="col-6 border border-1">@{{ procurement_quotation.offer }}</div>
                        </div>
                    </div>
                    <div class="row text-center cursor-pointer" v-if="procurement.procurement_quotations&&procurement.procurement_quotations.length>1">
                        <b @click="unfold(i)" class="col-12 cursor-pointer" v-if="!upList[i]">共有 @{{ procurement.procurement_quotations.length }} 家报价，<template v-for="(item,i) in procurement.procurement_quotations">价格@{{ i+1 }}:@{{ item.offer }}&nbsp</template>点击展开</b>
                        <b class="col-12" @click="unfold(i)" v-else>点击收起明细</b>
                    </div>
                </td>
                <td class="text-center">@{{ procurement.quantity }}</td>
{{--                <td>--}}
{{--                    <span v-if="procurement_type[procurement.type]=='询价单'">@{{ procurement.cost_price }}</span>--}}
{{--                    <span >@{{ procurement.cost_price }}</span>--}}
{{--                </td>--}}
                <td class="text-center"><span>@{{ procurement.unit_price }}</span></td>
                <td class="text-center"><span v-if="procurement.deliver_amount">@{{ procurement.deliver_amount }}</span></td>
                <td class="text-center"><span>@{{ procurement.quantity*procurement.unit_price }}</span></td>
                <td class="text-muted"><span v-if="procurement.owner_material.owner">@{{ procurement.owner_material.owner.customer? procurement.owner_material.owner.customer.phone:'' }}</span></td>
            </tr>
        </table>
        <div class="text-info h5 btn btn">{{$procurements->count()}}/@{{ sum }}</div>
        <div>{{$procurements->appends($paginateParams)->links()}}</div>
    </div>
@endsection
@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 type="text/javascript" src="{{mix('js/queryForm/header.js')}}"></script>{{--新版2--}}
    <script>
        let vue = new Vue({
            el: '#list',
            data: {
                countReceive:{!! $countReceive !!},
                countProcurement:{!! $countProcurement !!},
                procurements: {!! $procurements->toJson() !!}['data'],
                owners: [
                        @foreach($owners as $owner)
                    {
                        name: '{{$owner->id}}', value: '{{$owner->name}}',
                        ownerMaterials: [
                                @foreach($owner->ownerMaterials ? $owner->ownerMaterials :[] as $ownerMaterial)
                            {
                                id: '{{$ownerMaterial->id}}',
                                material_code: '{{$ownerMaterial->material_code ?? ''}}',
                                material_name: '{{$ownerMaterial->material->name ?? ''}}',
                                size: '{{$ownerMaterial->size ?? ''}}',
                                special: '{{$ownerMaterial->special ?? ''}}',
                                specification: '{{$ownerMaterial->specification ?? ''}}',
                            },
                            @endforeach
                        ],
                        @if($owner->customer)customer_name: '{{$owner->customer->name ?? ''}}',@endif
                    },
                    @endforeach
                ],
                materials: [
                        @foreach($materials as $material)
                    {
                        name: '{{$material->id}}', value: '{{$material->name}}'
                    },
                    @endforeach
                ],
                is_procurement:'',
                procurement_type:{!! json_encode(\App\Procurement::type,JSON_UNESCAPED_UNICODE) !!},
                procurement_status:{!! json_encode(\App\Procurement::status,JSON_UNESCAPED_UNICODE) !!},
                sum:{!! $procurements->total() !!},
                owner_id:'{{old('owner_id')}}',
                owner_material_id: '{{old('owner_material_id')}}',
                material_name: '{{old('material_name')}}',
                customer_name: '{{old('customer_name')}}',
                size: '{{old('size')}}',
                special: '{{old('special')}}',
                specification: '{{old('specification')}}',
                quantity: '{{old('quantity')}}',
                amount: '{{old('amount')}}',
                unit_price: '{{old('unit_price')}}',
                total_price: '{{old('total_price')}}',
                procurement_id:'',supplier:'',offer:'',supplier_id:'',
                ownerMaterials: [],
                errors: {},
                selectTr:'',
                createdProcurement:{},
                upList:{},
            },
            mounted: function () {
                $(".up").slideUp();
                $(".tooltipTarget").tooltip({'trigger': 'hover'});
                $('#list').removeClass('d-none');
                let data = [
                    [
                        {name: 'created_at_start', type: 'dateTime', tip: '选择显示指定日期的起始时间'},
                        {name: 'created_at_end', type: 'dateTime', tip: '选择显示指定日期的结束时间'},
                        {
                            name: 'owner_id', type: 'select_multiple_select', tip: ['输入关键词快速定位下拉列表,回车确定', '选择要显示的项目'],
                            placeholder: ['项目', '定位或多选项目'], data: this.owners
                        },
                        {
                            name: 'material_id',
                            type: 'select_multiple_select',
                            tip: ['输入关键词快速定位下拉列表,回车确定', '选择要显示的耗材'],
                            placeholder: ['耗材', '定位或多选耗材'],
                            data: this.materials
                        },
                        // {name: 'company_name', type: 'input', tip: '采购公司:可在两侧增加百分号(%)进行模糊搜索', placeholder: '采购公司'},
                    ],
                ];
                this.form = new query({
                    el: "#form_div",
                    condition: data,
                });
                this.form.init();
                let column = [
                    {name: 'code', value: '采购编号', neglect: true,class: 'text-center'},
                    {name: '操作', value: '操作', neglect: true,class: 'text-center'},
                    {name: 'type', value: '单据类型', class: 'text-center'},
                    {name: '采购单状态', value: '采购单状态', neglect: true,class: 'text-center'},
                    {name: 'owner_id', value: '项目', class: 'text-center'},
                    // {name: 'company_name', value: '采购公司', class: 'text-center'},
                    {name: 'material_code', value: '耗材编号', class: 'text-center'},
                    {name: 'material_name', value: '耗材'},
                    {name: 'size', value: '尺寸大小', class: 'text-center'},
                    {name: 'special', value: '特殊要求', class: 'text-center'},
                    {name: 'specification', value: '材质规格', class: 'text-center'},
                    {name: '附件', value: '附件', class: 'text-center'},
                    // {name: 'supplier', value: '供应商', class: 'text-center'},
                    {name:"price",type:"multi",title:"报价信息",rows:[
                            {value:"供应商",col:"6"},
                            {value:"采购单价(元)",col:"6"},
                        ]},
                    {name: 'quantity', value: '采购数量', neglect: true,class: 'text-center'},
                    // {name: 'offer', value: '采购单价(元)', neglect: true,class: 'text-center'},
                    {name: 'unit_price', value: '销售单价(元)', neglect: true,class: 'text-center'},
                    {name: '送货数量', value: '送货数量', neglect: true,class: 'text-center'},
                    {name: '销售总价', value: '销售总价(元)', neglect: true,class: 'text-center'},
                    {name: '联系方式', value: '联系方式', neglect: true,class: 'text-center'},
                ];

                new Header({
                    el: "table",
                    name: "procurement",
                    column: column,
                    data: this.procurements,
                    fixedTop: ($('#form_div').height()) + 2,
                }).init();
            },
            methods: {
                addProcurement() {
                    this.errors = {};
                    this.is_procurement='procurement';
                    $('#add-procurement').modal('show');
                    $('#owner_name').val('');
                },
                addEnquiry() {
                    this.errors = {};
                    this.is_procurement='enquiry';
                    $('#add-procurement').modal('show');
                    $('#owner_name').val('');
                },
                addProof() {
                    this.errors = {};
                    this.is_procurement='proof';
                    $('#add-procurement').modal('show');
                    $('#owner_name').val('');
                },
                initiateProcurement(procurement) {
                    let _this=this;
                    this.procurement_id=procurement.id;
                    let url="{{url('procurement/procurement/initiateProcurement')}}";
                    let params={id:procurement.id};
                    window.axios.post(url,params).then(res => {
                            if (res.data.success) {
                              _this.supplier=res.data.data.supplier.name;
                              _this.supplier_id=res.data.data.supplier_id;
                              _this.offer=res.data.data.offer;
                              if(res.data.data.procurement.quantity)_this.quantity=res.data.data.procurement.quantity;else _this.quantity='';
                              if(res.data.data.procurement.amount)_this.amount=res.data.data.procurement.amount; else _this.amount='';
                              $('#add-quantity').modal('show');
                            } else {
                                tempTip.setDuration(3000);
                                tempTip.show(res.data.message);
                            }
                        }).catch(err => {
                        window.tempTip.setDuration(3000);
                        window.tempTip.show("网络错误：" + err);
                    });
                },
                unfold(index){
                    this.$set(this.upList,index,this.upList[index] ? !this.upList[index] : true);
                    $("#procurement_quotation-"+index).slideToggle();
                },
                show(id,$e){
                    $("#"+id).slideToggle();
                    let value= $($e.target).html();
                    if(value=== '点击展开'){
                        value = '点击收起';
                    }else if(value === '点击收起'){
                        value ='点击展开'
                    }
                    $($e.target).html(value);
                },
                owner_seek: function (e) {
                    let _this = this;
                    let $val = e.target.value;
                    if ($val === '') {
                        _this.owner_id = '';
                    } else {
                        _this.owners.forEach(function (owner) {
                            if (owner.value.includes($val)) {
                                _this.owner_id = owner.name;
                                _this.ownerMaterials = owner.ownerMaterials;
                                _this.customer_name = owner.customer_name;
                            }
                        });
                    }
                },
                ownerMaterial: function () {
                    let _this = this;
                    _this.ownerMaterials.forEach(function (ownerMaterial) {
                        if (_this.owner_material_id === ownerMaterial.id) {
                            _this.material_name = ownerMaterial.material_name;
                            _this.size = ownerMaterial.size;
                            _this.special = ownerMaterial.special;
                            _this.specification = ownerMaterial.specification;
                        }
                    })
                },
                selectOwner: function () {
                    let _this = this;
                    _this.owners.forEach(function (owner) {
                        if (_this.owner_id === owner.name) {
                            _this.ownerMaterials = owner.ownerMaterials;
                            _this.customer_name = owner.customer_name;
                        }
                    })
                },
                countTotalPrice: function () {
                    let _this = this;
                    if (_this.unit_price === '' || _this.amount === '') _this.total_price = null;
                    _this.total_price = _this.unit_price * _this.amount;
                },
                createProcurement() {
                    let _this = this;
                    let url = '{{url('procurement/procurement/createProcurement')}}';
                    let params = {
                        owner_id: _this.owner_id,
                        owner_material_id: _this.owner_material_id,
                        quantity: _this.quantity,
                        amount: _this.amount,
                        unit_price: _this.unit_price
                    };
                    window.axios.post(url, params).then(function (res) {
                        if (!res.data.success) {
                            _this.errors = res.data.errors
                        } else {
                            _this.procurements.push(res.data.data);
                            $("#add-procurement").modal('hide');
                            _this.clearData();
                            tempTip.setDuration(3000);
                            tempTip.showSuccess('新增采购单成功！');
                        }
                    }).catch(function (err) {
                        tempTip.setDuration(3000);
                        tempTip.show('新增采购单失败！网络错误：' + err);
                    });
                },
                createEnquiry() {
                    let _this = this;
                    let url = '{{url('procurement/procurement/createEnquiry')}}';
                    let params = {owner_id: _this.owner_id, owner_material_id: _this.owner_material_id};
                    window.axios.post(url, params).then(function (res) {
                        if (!res.data.success) {
                            _this.errors = res.data.errors;
                        } else {
                            _this.procurements.push(res.data.data);
                            $("#add-procurement").modal('hide');
                            _this.clearData();
                            tempTip.setDuration(3000);
                            tempTip.showSuccess('新增询价单成功！');

                        }
                    }).catch(function (err) {
                        tempTip.setDuration(3000);
                        tempTip.show('新增询价单失败！网络错误：' + err);
                    });
                },
                createProof() {
                    let _this = this;
                    let url = '{{url('procurement/procurement/createProof')}}';
                    let params = {owner_id: _this.owner_id, owner_material_id: _this.owner_material_id};
                    window.axios.post(url, params).then(function (res) {
                        if (!res.data.success) {
                            _this.errors = res.data.errors;
                        } else {
                            _this.procurements.push(res.data.data);
                            $("#add-procurement").modal('hide');
                            _this.clearData();
                            tempTip.setDuration(3000);
                            tempTip.showSuccess('新增打样单成功！');

                        }
                    }).catch(function (err) {
                        tempTip.setDuration(3000);
                        tempTip.show('新增打样单失败！网络错误：' + err);
                    });
                },
                clearData() {
                    this.owner_id = '';this.owner_material_id = '';
                    this.material_name = '';this.customer_name = '';
                    this.size = '';this.special = '';
                    this.specification = '';this.quantity = '';
                    this.amount = '';this.unit_price = '';
                    this.total_price = '';this.procurement_id='';
                    this.supplier_id='';this.offer='';
                },
                procurementExport(selectAll) {
                    let url = '{{url('procurement/procurement/procurementExport')}}';
                    let token = '{{ csrf_token() }}';
                    excelExport(selectAll, checkData, url, this.sum, token);
                },
                cancel(id, type, code) {
                    window.tempTip.confirm('确定取消' + this.procurement_type[type] + ' ' + code, () => {
                        window.axios.get("{{url('procurement/procurement/cancel')}}/" + id)
                            .then(res => {
                                if (res.data.success) {
                                    this.procurements.forEach(function (procurement) {
                                        if (procurement.id === res.data.data.id) {
                                            procurement.status = res.data.data.status;
                                            window.tempTip.setDuration(2000);
                                            window.tempTip.showSuccess("已成功取消该条采购申请");
                                        }
                                    })
                                } else {
                                    tempTip.setDuration(3000);
                                    tempTip.show(res.data.message);
                                }
                            }).catch(err => {
                            window.tempTip.setDuration(3000);
                            window.tempTip.show("网络错误：" + err);
                        });
                    });
                },
                submitProcurement() {
                    let _this=this;
                    let id=this.procurement_id;
                    if (!id)return;
                    let url="{{url('procurement/procurement/submitProcurement')}}";
                    let params={id:id,quantity:this.quantity,amount:this.amount,unit_price:this.unit_price,offer:this.offer,supplier_id:this.supplier_id};
                    window.axios.post(url,params).then(res => {
                            if (!res.data.success) {
                                _this.errors = res.data.errors;
                            } else {
                                this.procurements.forEach(function (procurement) {
                                    if (procurement.id === res.data.data.id) {
                                        procurement.status = res.data.data.status;
                                        procurement.amount = res.data.data.amount;
                                        procurement.type = res.data.data.type;
                                        procurement.quantity = res.data.data.quantity;
                                        procurement.unit_price = res.data.data.unit_price;
                                        $("#add-quantity").modal('hide');
                                        _this.clearData();
                                        window.tempTip.setDuration(2000);
                                        window.tempTip.showSuccess("已成功发起采购申请");
                                    }
                                })
                            }
                        }).catch(err => {
                        window.tempTip.setDuration(3000);
                        window.tempTip.show("网络错误：" + err);
                    });
                },
                //从新创建procurement
                createAnew(){
                    let _this=this;
                    let url="{{url('procurement/procurement/createAnew')}}";
                    let params={checkData:checkData};
                    window.axios.post(url,params).then(res => {
                        if (!res.data.success) {
                            window.tempTip.setDuration(3000);
                            window.tempTip.show(res.data.message);
                        } else {
                           res.data.data.forEach(function (procurement) {
                               _this.procurements.push(procurement);
                            });
                            checkData=[];
                            window.tempTip.setDuration(2000);
                            window.tempTip.showSuccess("重新发起成功");
                        }
                    }).catch(err => {
                        window.tempTip.setDuration(3000);
                        window.tempTip.show("网络错误：" + err);
                    });
                },
                getDownFileUrl(ownerMaterial){
                    return '{{ url("maintenance/ownerMaterial/downFile?file=")}}'+ownerMaterial.file.url+'&name='+ownerMaterial.file.file_name;
                },
            }
        });
    </script>
@endsection
