@extends('layouts.app')
@section('title')录入-作业-计费模型@endsection

@section('content')
    <div id="nav2">
        @component('maintenance.menu')@endcomponent
        @component('maintenance.priceModel.operation.menu')
            @if(isset($model))
            <li class="nav-item">
                <a class="nav-link" href="{{URL::current()}}" :class="{active:isActive('edit',5)}">编辑</a>
            </li>
            @endif
        @endcomponent
    </div>
    <div class="container-fluid mt-2 card" id="container">
        @include("maintenance.priceModel.operation._addFeature")
        <form method="POST" action="{{url('maintenance/priceModel/operation')}}@if(isset($model))/{{$model->id}}/edit @endif" class="card-body offset-3">
            @csrf
            <div class="row">
                <label class="col-2" for="owner_id">项目</label>
                <select id="owner_id" class="selectpicker" multiple data-live-search="true" title="项目(多选)" :class="errors.owner_id ? 'is-invalid' : ''" v-model="model.owner_id">
                    <option v-for="owner in owners" :value="owner.id">@{{ owner.name }}</option>
                </select>
                <span class="invalid-feedback mt-0 offset-2" role="alert" v-if="errors.owner_id">
                    <strong>@{{ errors.owner_id[0] }}</strong>
                </span>
                <label hidden><input :value="model.owner_id" name="owner_id"></label>
            </div>
            <div class="row mt-3">
                <label for="operation_type" class="col-2">操作类型</label>
                <select id="operation_type" :disabled="model.id ? true : false" :class="errors.operation_type ? 'is-invalid' : ''" v-model="model.operation_type"  class="col-3 form-control" required>
                    <option value="入库">入库</option>
                    <option value="出库">出库</option>
                </select>
                <label hidden><input name="operation_type" :value="model.operation_type"></label>
                <span class="invalid-feedback mt-0 offset-2" role="alert" v-if="errors.operation_type">
                    <strong>@{{ errors.operation_type[0] }}</strong>
                </span>
            </div>
            <div class="row mt-3">
                <label for="strategy" class="col-2">计费策略</label>
                <select id="strategy"  :disabled="model.id ? true : false" :class="errors.strategy ? 'is-invalid' : ''" class="col-3 form-control" v-model="model.strategy" required>
                    <option value="默认">默认</option>
                    <option value="特征">特征</option>
                </select>
                <label hidden><input name="strategy" :value="model.strategy"></label>
                <span class="invalid-feedback mt-0 offset-2" role="alert" v-if="errors.strategy">
                    <strong>@{{ errors.strategy[0] }}</strong>
                </span>
            </div>
            <div class="row mt-3">
                <label for="name" class="col-2">名称</label>
                <input id="name" type="text" name="name" :class="errors.name ? 'is-invalid' : ''" class="col-6 form-control" v-model="model.name" required>
                <span class="invalid-feedback mt-0 offset-2" role="alert" v-if="errors.name">
                    <strong>@{{ errors.name[0] }}</strong>
                </span>
            </div>
            <div class="row mt-3" v-if="model.strategy == '特征'">
                <label class="col-2">特征：</label>
                <label v-if="model.feature">
                    @{{ model.feature }}
                    <input hidden name="feature" :value="model.feature" type="text">
                </label>
                <button type="button" class="btn btn-dark col-2 ml-2" @click="showAddFeatureModal(-1,model.feature)">调整特征</button>
            </div>
            <div class="row mt-3">
                <label for="priority" class="col-2">优先级</label>
                <input id="priority" type="number" min="0" name="priority" :class="errors.priority ? 'is-invalid' : ''" class="col-6 form-control" v-model="model.priority" required>
                <span class="invalid-feedback mt-0 offset-2" role="alert" v-if="errors.priority">
                    <strong>@{{ errors.priority[0] }}</strong>
                </span>
            </div>
            <div class="row mt-3" v-if="model.operation_type == '出库'">
                <label class="col-2" for="isDiscount">是否满减</label>
                <div class="col-2">
                    <input type="checkbox" id="isDiscount" class="rounded mt-1" v-model="model.isDiscount">
                </div>
                <div class="col-8 row" v-if="model.isDiscount">
                    <div class="col-1 cursor-pointer"><span class="fa fa-plus" @click="addDiscount(model.discount_count)"></span></div>
                    <label class="col-3" for="discount">满减阈值</label>
                    <input id="discount" v-model="model.discount_count[0]" name="discount_count[]" required
                           class="form-control form-control-sm col-6" :class="errors.discount_count ? 'is-invalid' : ''" step="1" type="number" min="0">
                </div>
            </div>
            <div class="row mt-1" v-for="(value,i) in model.discount_count" v-if="model.isDiscount && i!=0">
                <label class="col-2"></label><div class="col-2"></div>
                <div class="col-8 row">
                    <label class="offset-1 col-3">满减阈值@{{ i+1 }}</label>
                    <input v-model="model.discount_count[i]" :placeholder="Number(model.discount_count[i-1])+1" name="discount_count[]" required
                           class="form-control form-control-sm col-6" step="1" type="number" :min="Number(model.discount_count[i-1])+1">
                </div>
            </div>
            <div class="row mt-3">
                <label class="col-2" for="isSingle">按单计价</label>
                <div class="col-2">
                    <input type="checkbox" id="isSingle" class="pull-left rounded mt-1" v-model="model.isSingle">
                </div>
                <div class="col-8 row" v-if="model.isSingle">
                    <label class="col-3" for="total_price">普通价格</label>
                    <input id="total_price" name="total_price" v-model="model.total_price"
                           class="form-control form-control-sm col-6" :class="errors.total_price ? 'is-invalid' : ''" step="0.001" type="number" min="0">
                </div>
            </div>
            <div class="row mt-1" v-if="model.isSingle && model.isDiscount" v-for="(value,i) in model.total_discount_price">
                <label class="col-2"></label><div class="col-2"></div>
                <div class="col-8 row">
                    <label class="col-3" for="total_discount_price">满减价(@{{ model.discount_count[i] }}单)</label>
                    <input id="total_discount_price" name = "total_discount_price[]" v-model="model.total_discount_price[i]"
                           class="form-control form-control-sm col-6" step="0.001" type="number" min="0">
                </div>
            </div>
            <div class="row mt-3" v-if="!model.isSingle">
                <div v-for="(item,i) in model.items" class="card row text-white col-8" :class="i>0 ? 'bg-secondary mt-2' : 'bg-info'">
                    <div class="card-header">
                        <div class="pull-left" v-if="i==0"><span @click="addRule()" class="fa fa-plus-square-o" style="cursor: pointer"></span></div>
                        <div class="pull-right" v-if="model.items.length > 1"><span @click="delRule(i)" class="fa fa-window-close-o" style="cursor: pointer"></span></div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-4 form-inline">
                                <label for="amount"><span v-if="item.strategy=='起步'">起步数：</span><span v-else>计量：</span></label>
                                <input id="amount" type="number" :class="errors['items.'+i+'.amount'] ? 'is-invalid' : ''" v-model="item.amount" class="form-control" required>
                                <span class="invalid-feedback mt-0 offset-2" role="alert" v-if="errors['items.'+i+'.amount']">
                                    <strong>必须为整数</strong>
                                </span>
                            </div>

                            <div class="col-4 form-inline">
                                <label for="unit_id">单位：</label>
                                <select id="unit_id" v-model="item.unit_id" class="form-control" :class="errors['items.'+i+'.unit_id'] ? 'is-invalid' : ''" required>
                                    <option v-for="unit in units" :value="unit.id">@{{ unit.name }}</option>
                                </select>
                                <span class="invalid-feedback mt-0 offset-2" role="alert" v-if="errors['items.'+i+'.unit_id']">
                                    <strong>必选项</strong>
                                </span>
                            </div>
                            <div class="col-4 form-inline">
                                <label for="unit_price">单价：</label>
                                <input id="unit_price" type="number" min="0" step="0.001" class="form-control" v-model="item.unit_price"  required
                                       :class="errors['items.'+i+'.unit_price'] ? 'is-invalid' : ''">
                            </div>
                            <span class="invalid-feedback mt-0 offset-2" role="alert" v-if="errors['items.'+i+'.unit_price']">
                                <strong>必须为数字且不得为负</strong>
                            </span>
                        </div>
                        <div class="row mt-2">
                            <label for="out_priority" class="col-2">优先级：</label>
                            <input type="number" min="0" id="out_priority" v-model="item.priority" :class="errors['items.'+i+'.priority'] ? 'is-invalid' : ''" class="col-5 form-control">
                            <span class="invalid-feedback mt-0 offset-2" role="alert" v-if="errors['items.'+i+'.priority']">
                                <strong>必须为整数且数值区间为[0-100]</strong>
                            </span>
                        </div>
                        <div class="row mt-2">
                            <label for="out_storage_strategy" class="col-2">子策略：</label>
                            <select id="out_storage_strategy" v-model="item.strategy" class="col-5 form-control"
                                    @change="outRuleUnique(item.strategy)"
                                    :class="errors['items.'+i+'.strategy'] ? 'is-invalid' : ''">
                                <optgroup v-if="existStrategy.starting && item.strategy!='起步'" label="起步"></optgroup>
                                <option v-else>起步</option>
                                <optgroup v-if="existStrategy.default && item.strategy!='默认'" label="默认"></optgroup>
                                <option v-else>默认</option>
                                <option>特征</option>
                            </select>
                            <span class="invalid-feedback mt-0 offset-2" role="alert" v-if="errors['items.'+i+'.strategy']">
                                <strong>必选项</strong>
                            </span>
                        </div>
                        <div class="row mt-2" v-if="item.strategy == '特征'">
                            <label class="col-2">特征：</label>
                            <label v-if="item.feature">@{{ item.feature }}</label>
                            <button type="button" class="btn btn-dark col-2 ml-2" @click="showAddFeatureModal(i,item.feature)">调整特征</button>
                        </div>
                        <div class="row mt-2" v-if="model.isDiscount" v-for="(value,i) in item.discount_price">
                            <label class="col-2">满减价(@{{ model.discount_count[i] }}单)</label>
                            <input class="col-5 form-control form-control-sm" v-model="item.discount_price[i]" required
                                type="number" step="0.001" min="0">
                        </div>
                    </div>
                </div>
                <label hidden><input name="items" :value="JSON.stringify(model.items)"></label>
            </div>
            <div class="row mt-3">
                <label for="remark" class="col-2">备注</label>
                <textarea id="remark" name="remark" class="col-6 form-control" v-model="model.remark"></textarea>
            </div>

            <div class="row mt-3 offset-1">
                <button type="submit" class="btn btn-success col-7">提交</button>
            </div>
        </form>
    </div>
@stop

@section("lastScript")
    <script>
        new Vue({
            el:"#container",
            data:{
                model:{
                    id: "{{isset($model) ? $model->id : ''}}",
                    owner_id:{!! old('owner_id') ? json_encode(old('owner_id')) : (isset($model) ? json_encode(array_column($model->owners->toArray(),"id")) : '[]') !!},
                    operation_type:"{{old('operation_type') ?? (isset($model) ? $model->operation_type : '')}}",
                    strategy:"{{old('strategy') ?? (isset($model) ? $model->strategy : '')}}",
                    name:"{{old('name') ?? (isset($model) ? $model->name : '')}}",
                    priority:"{{old('priority') ?? (isset($model) ? $model->priority : 0)}}",
                    feature:"{{old('feature') ?? (isset($model) ? $model->feature : '')}}",
                    discount_count:"{{old('discount_count') ?? (isset($model) ? $model->discount_count : '')}}",
                    total_price:"{{old('total_price') ?? (isset($model) ? $model->total_price : '')}}",
                    total_discount_price:"{{old('total_discount_price') ?? (isset($model) ? $model->total_discount_price : '')}}",
                    remark:"{{old('remark') ?? (isset($model) ? $model->remark : '')}}",
                    items:{!! old('items') ? json_encode(old('items')) : (isset($model)&&$model->items ? $model->items : "[{strategy:'',amount:'',unit_id:'',unit_price:'',feature:'',priority:''}]")!!},
                },
                owners : [
                    @foreach($owners as $owner)
                    {id:"{{$owner->id}}",name:"{{$owner->name}}"},
                    @endforeach
                ],
                units : [
                    @foreach($units as $unit)
                    {id:"{{$unit->id}}",name:"{{$unit->name}}"},
                    @endforeach
                ],
                type : {!! json_encode(\App\Feature::type,JSON_UNESCAPED_UNICODE) !!},
                logic : ['包含','不包含','等于'],
                features : [],
                thisIndex : "",
                errors:{!! $errors !!},
                existStrategy:{default:false,starting:false},
                oldFeature : '',
            },
            mounted(){
                this.$set(this.model,"isSingle",!!this.model.total_price);
                this.$set(this.model,"isDiscount",!!this.model.discount_count);
                this.$set(this.model,"discount_count",this.model.discount_count ? this.model.discount_count.split(",") : [""]);
                this.$set(this.model,"total_discount_price",this.model.total_discount_price ? this.model.total_discount_price.split(",") : [""]);
                this.model.items.forEach((item,i)=>{
                    item.discount_price = item.discount_price ? item.discount_price.split(",") : [""];
                    this.$set(this.model.items,i,item);
                });
            },
            methods:{
                outRuleUnique(strategy){
                    if (strategy==='起步') this.existStrategy.starting = true;
                    if (strategy==='默认') this.existStrategy.default = true;
                    let startingSign = true;
                    let defaultSign = true;
                    this.model.items.forEach(item=>{
                        if (item.strategy === '默认')defaultSign = false;
                        if (item.strategy === '起步')startingSign = false;
                    });
                    if (startingSign)this.existStrategy.starting = false;
                    if (defaultSign)this.existStrategy.default = false;
                },
                addRule(){
                    this.model.items.push({
                        "strategy" : "",
                        "amount" : "",
                        "unit_id" : "",
                        "unit_price" : "",
                        "feature" : "",
                        "priority" : "",
                        "discount_price":new Array(this.model.discount_count.length).fill(""),
                    });
                },
                delRule(index){
                    this.$delete(this.model.items,index);
                },
                showAddFeatureModal(index,feature){
                    if (!feature){
                        this.features = [{
                            "strategyGroupStartSign": false,
                            "calculation" : "",
                            "type" : "",
                            "id" : "",  //特征ID
                            "logic" : "",  //特征逻辑
                            "describe" : "",  //特征信息
                            "strategyGroupEndSign" : false,
                        }];
                        this.thisIndex = index;
                        $("#addFeatureModal").modal("show");
                        return;
                    }
                    if (this.oldFeature === feature) {
                        this.thisIndex = index;
                        $("#addFeatureModal").modal("show");
                        return;
                    }
                    window.axios.post("{{url('maintenance/priceModel/operation/getFeatures')}}", {feature:feature})
                        .then(res=>{
                            if (res.data.success){
                                this.features = res.data.data;
                                this.oldFeature = feature;
                                if (!this.features || this.features.length === 0){
                                    this.features = [{
                                        "strategyGroupStartSign": false,
                                        "calculation" : "",
                                        "type" : "",
                                        "id" : "",  //特征ID
                                        "logic" : "",  //特征逻辑
                                        "describe" : "",  //特征信息
                                        "strategyGroupEndSign" : false,
                                    }];
                                }
                                this.thisIndex = index;
                                $("#addFeatureModal").modal("show");
                                return;
                            }
                            window.tempTip.setDuration(3000);
                            window.tempTip.show(res.data.data);
                        }).catch(err=>{
                        window.tempTip.setDuration(3000);
                        window.tempTip.show("网络错误："+err);
                    });
                },
                addFeature(){
                    this.features.push({
                        "strategyGroupStartSign": false,
                        "calculation" : "",
                        "type" : "",
                        "id" : "",  //特征ID
                        "logic" : "",  //特征逻辑
                        "describe" : "",  //特征信息
                        "strategyGroupEndSign" : false,
                    });
                },
                delFeature(index) {
                    this.$delete(this.features,index);
                },
                submitFeature(){
                    window.axios.post("{{url('maintenance/priceModel/operation/getFeature')}}",
                        {features:this.features})
                        .then(res=>{
                            if (res.data.success){
                                if (this.thisIndex == '-1') this.model.feature = res.data.data;
                                else this.model.items[this.thisIndex].feature = res.data.data;
                                $("#addFeatureModal").modal("hide");
                                window.tempTip.setDuration(2000);
                                window.tempTip.setIndex(1099);
                                window.tempTip.showSuccess("已更新特征");
                                return;
                            }
                            window.tempTip.setDuration(3000);
                            window.tempTip.setIndex(1099);
                            window.tempTip.show(res.data.data);
                        }).catch(err=>{
                        window.tempTip.setDuration(3000);
                        window.tempTip.setIndex(1099);
                        window.tempTip.show("网络错误："+err);
                    });
                },
                addDiscount(arr){
                    this.model.items.forEach(item=>{
                        item.discount_price.push('');
                    });
                    this.model.total_discount_price.push("");
                    arr.push('');
                },
            },
        });
    </script>
@stop