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

@section('content')
    <div id="nav2">
        @component('maintenance.menu')@endcomponent
        @component('maintenance.priceModel.operation.menu')@endcomponent
    </div>
    <div class="container-fluid mt-2" id="container">
        @include("maintenance.priceModel.operation._addItemModal")
        @include("maintenance.priceModel.operation._addFeature")
        <div id="form_div"></div>
        @if(Session::has('successTip'))
            <div class="alert alert-success h1">{{Session::get('successTip')}}</div>
        @endif
        <table class="table table-hover table-striped text-nowrap">
            <tr>
                <th>序号</th>
                <th>操作</th>
                <th>名称</th>
                <th>类型</th>
                <th>策略</th>
                <th>项目</th>
                <th>优先级</th>
                <th>按单单价</th>
                <th>按单减免</th>
                <th>特征</th>
                <th>备注</th>
                <th>录入时间</th>
                <th>操作</th>
            </tr>
            <tr v-for="(model,i) in models" :id="'model-'+model.id"  @click="selectTr===i+1?selectTr=0:selectTr=i+1" :class="selectTr===i+1?'focusing' : ''">
                <td>@{{ i+1 }}</td>
                <td>
                    <button v-if="thisId != model.id" class="btn btn-sm btn-info text-white" @click="showDetail(model.id,model.operationType,i)">维护详情</button>
                    <button v-if="thisId == model.id" class="btn btn-sm btn-dark" @click="thisId = ''">关闭详情</button>
                </td>
                <td>@{{ model.name }}</td>
                <td>@{{ model.operationType }}</td>
                <td>@{{ model.strategy }}</td>
                <td><small v-for="owner in model.owners" class="m-0 font-weight-bold">@{{ owner.name }}<br></small></td>
                <td>@{{ model.priority }}</td>
                <td>@{{ model.totalPrice ? model.totalPrice : '/' }}</td>
                <td>
                    <span v-if="model.totalPrice"><small v-for="(price,i) in model.totalDiscountPrice">@{{ model.discountCount[i] }}单/@{{ price }}元<br></small></span>
                    <span v-else>/</span>
                </td>
                <td>@{{ model.feature }}</td>
                <td><div class="text-overflow-warp-200 warp-min-200">@{{ model.remark }}</div></td>
                <td>@{{ model.createdAt }}</td>
                <td>
                    @can("计费模型-作业-编辑")<button type="button" class="btn btn-sm btn-outline-info" @click="edit(model.id)">编辑</button>@endcan
                    @can("计费模型-作业-删除")<button type="button" class="btn btn-sm btn-outline-danger" @click="delModel(model.id,i)">删除</button>@endcan
                </td>
            </tr>
            <tr id="detail" v-show="thisId">
                <td></td>
                <td colspan="9">
                    <table class="table table-sm table-bordered">
                        <tr class="text-success">
                            <th>操作</th>
                            <th>计费策略</th>
                            <th>起步数</th>
                            <th>单位</th>
                            <th>单价</th>
                            <th>减免</th>
                            <th>优先级</th>
                            <th class="text-center">特征</th>
                            <th></th>
                        </tr>
                        <tr v-if="items[thisId] && items[thisId].length == 0">
                            <td colspan="8">
                                @can("计费模型-作业-编辑")<button class="btn btn-sm btn-outline-info" @click="showAddItemModal()">新增</button>@endcan
                            </td>
                        </tr>
                        <tr v-for="(item,i) in items[thisId]">
                            <td>
                                <span v-if="updateDetailId != item.id">
                                    @can("计费模型-作业-编辑")<button class="btn btn-sm btn-outline-info" @click="showAddItemModal()" v-if="i==0">新增</button>
                                    <button class="btn btn-sm btn-outline-info" @click="showUpdateDetail(item.id)">修改</button>@endcan
                                </span>
                                <span v-else>
                                    <button class="btn btn-sm btn-success" @click="submitUpdateDetail(item)">确定</button>
                                    <button class="btn btn-sm btn-danger" @click="updateDetailId = ''">取消</button>
                                </span>
                            </td>
                            <td>@{{ item.strategy }}</td>
                            <td>
                                <label v-if="updateDetailId == item.id">
                                    <input type="number" min="0" id="detailAmount"  class="form-control form-control-sm"
                                           :value="item.amount">
                                </label>
                                <label v-else>@{{ item.amount }}</label>
                            </td>
                            <td>
                                <label v-if="updateDetailId == item.id">
                                    <select class="form-control form-control-sm" id="detailUnit">
                                        <option v-for="unit in units" :value="unit.id" v-if="unit.id==item.unit_id" selected>@{{ unit.name }}</option>
                                        <option v-for="unit in units" :value="unit.id" v-if="unit.id!=item.unit_id">@{{ unit.name }}</option>
                                    </select>
                                </label>
                                <label v-else>@{{ item.unit ? item.unit.name : '' }}</label>
                            </td>
                            <td>
                                <label v-if="updateDetailId == item.id">
                                    <input type="number" min="0" step="0.001" id="detailUnitPrice" class="form-control form-control-sm"
                                           :value="item.unit_price">
                                </label>
                                <label v-else>@{{ item.unit_price }}</label>
                            </td>
                            <td>
                                <span v-if="item.discount_price.length>0"><small v-for="(price,i) in item.discount_price">@{{ models[thisIndex].discountCount[i] }}单/@{{ price }}元<br></small></span>
                                <span v-else>/</span>
                            </td>
                            <td>
                                <label v-if="updateDetailId == item.id">
                                    <input type="number" min="0" id="detailPriority" class="form-control form-control-sm"
                                           :value="item.priority">
                                </label>
                                <label v-else>@{{ item.priority }}</label>
                            </td>
                            <td>@{{ item.featureFormat }}</td>
                            <td>
                                @can("计费模型-作业-编辑")<button class="btn btn-sm btn-success" v-if="item.strategy == '特征'" @click="showAddFeatureModal(i,item.feature)">维护特征</button>@endcan
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </div>
@stop

@section("lastScript")
    <script type="text/javascript" src="{{mix('js/queryForm/queryForm.js')}}"></script>
    <script>
        new Vue({
            el:"#container",
            data:{
                models : [
                    @foreach($models as $model)
                    {
                        id : "{{$model->id}}",
                        operationType : "{{$model->operation_type}}",
                        name : "{{$model->name}}",
                        strategy : "{{$model->strategy}}",
                        feature : "{{$model->featureFormat}}",
                        remark : "{{$model->remark}}",
                        priority : "{{$model->priority}}",
                        discountCount : "{{$model->discount_count}}" ? "{{$model->discount_count}}".split(",") : ["/"],
                        totalPrice : "{{$model->total_price}}",
                        totalDiscountPrice : "{{$model->total_discount_price}}" ? "{{$model->total_discount_price}}".split(",") : ["/"],
                        createdAt : "{{$model->created_at}}",
                        owners : {!! $model->owners !!},
                    },
                    @endforeach
                ],
                owners : [
                    @foreach($owners as $owner)
                    {name:"{{$owner->id}}",value:"{{$owner->name}}"},
                    @endforeach
                ],
                thisId : "",
                thisIndex : "",
                items : [],
                updateDetailId : '',
                units : null,
                type : {!! json_encode(\App\Feature::type,JSON_UNESCAPED_UNICODE) !!},
                logic : ['包含','不包含','等于'],
                item : {
                    "strategy" : '特征',
                    "amount" : "",
                    "unit_id" : "",
                    "unit_price" : "",
                    "priority" : 0,
                },
                features : [],
                existStrategy:{default:false,starting:false},
                selectTr:''
            },
            mounted(){
                let data=[
                    [
                        {name:'owner_id',type:'select_multiple_select',tip:['输入关键词快速定位下拉列表，回车确定','选择要显示的项目'],
                            placeholder:['项目','定位或多选项目'],data:this.owners},
                        {name: 'name', type: 'input', tip: '价格名称：可在左侧增加百分号(%)进行模糊搜索', placeholder: '价格名称'},
                    ]
                ];
                this.form = new query({
                    el:"#form_div",
                    condition:data,
                });
                this.form.init();
            },
            methods:{
                showDetail(id,type,index){
                    if (this.items[id]){
                        this.thisId = id;
                        $("#model-"+id).after($("#detail"));
                        return;
                    }
                    window.axios.post("{{url('maintenance/priceModel/operation/getItems')}}",{id:id,type:type})
                        .then(res=>{
                            if (res.data.success){
                                res.data.data.forEach((item,i)=>{
                                    res.data.data[i].discount_price = item.discount_price ? item.discount_price.split(",") : [];
                                });
                                this.items[id] = res.data.data;
                                this.thisId = id;
                                this.thisIndex = index;
                                $("#model-"+id).after($("#detail"));
                                return;
                            }
                            window.tempTip.setDuration(3000);
                            window.tempTip.show(res.data.data);
                        }).catch(err=>{
                        window.tempTip.setDuration(3000);
                        window.tempTip.show("网络错误："+err);
                    });
                },
                showUpdateDetail(id){
                    if (!this.units)this._getUnits();
                    this.updateDetailId = id;
                },
                _getUnits(){
                    window.axios.post("{{url('maintenance/unit/getUnits')}}")
                        .then(res=>{
                            if (res.data.success){
                                this.units = res.data.data;
                                return;
                            }
                            window.tempTip.setDuration(3000);
                            window.tempTip.show(res.data.data);
                        }).catch(err=>{
                        window.tempTip.setDuration(3000);
                        window.tempTip.show("网络错误："+err);
                    });
                },
                submitUpdateDetail(item){
                    let amount = $("#detailAmount").val();
                    let unit_id = $("#detailUnit").val();
                    let unit_price = $("#detailUnitPrice").val();
                    let priority = $("#detailPriority").val();
                    window.axios.post("{{url('maintenance/priceModel/operation/updateItem')}}",
                        {id:item.id,amount:amount,unit_id:unit_id,unit_price:unit_price,priority:priority})
                        .then(res=>{
                            if (res.data.success){
                                item.amount = amount;
                                if (item.unit_id != unit_id){
                                    this.units.some((unit)=>{
                                        if (unit_id == unit.id){
                                            item.unit = unit;
                                            return true;
                                        }
                                    });
                                    item.unit_id = unit_id;
                                }
                                item.unit_price = unit_price;
                                item.priority = priority;
                                this.updateDetailId = '';
                                window.tempTip.setDuration(2000);
                                window.tempTip.showSuccess("修改成功");
                                return;
                            }
                            window.tempTip.setDuration(3000);
                            window.tempTip.show(res.data.data);
                        }).catch(err=>{
                        window.tempTip.setDuration(3000);
                        window.tempTip.show("网络错误："+err);
                    });
                },
                showAddItemModal(){
                    if (!this.units)this._getUnits();
                    let startingSign = true;
                    let defaultSign = true;
                    this.items[this.thisId].forEach(item=>{
                        if (item.strategy === '默认')defaultSign = false;
                        if (item.strategy === '起步')startingSign = false;
                    });
                    if (!startingSign)this.existStrategy.starting = true;
                    if (!defaultSign)this.existStrategy.default = true;
                    $("#addItem").modal("show");
                },
                submitItem(){
                    if (!this.thisId || !this.item.strategy || !this.item.unit_id || !this.item.unit_price){
                        window.tempTip.setDuration(3000);
                        window.tempTip.show("计费策略,单位,单价为必填项");
                        return;
                    }
                    window.axios.post("{{url('maintenance/priceModel/operation/createItem')}}",
                        {owner_price_operation_id:this.thisId,strategy:this.item.strategy,amount:this.item.amount,unit_id:this.item.unit_id,unit_price:this.item.unit_price,priority:Number(this.item.priority)})
                        .then(res=>{
                            if (res.data.success){
                                this.items[this.thisId].unshift(res.data.data);
                                this.$forceUpdate();
                                window.tempTip.setDuration(2000);
                                window.tempTip.setIndex(1099);
                                window.tempTip.showSuccess("新增出库策略成功");
                                $("#addItem").modal("hide");
                                return;
                            }
                            window.tempTip.setDuration(3000);
                            window.tempTip.setIndex(1099);
                            window.tempTip.show(res.data.data);
                        }).catch(err=>{
                        window.tempTip.setDuration(3000);
                        window.tempTip.show("网络错误："+err);
                    });
                },
                showAddFeatureModal(index,feature){
                    window.axios.post("{{url('maintenance/priceModel/operation/getFeatures')}}", {feature:feature})
                        .then(res=>{
                            if (res.data.success){
                                this.features = res.data.data;
                                if (this.features.length === 0)this.addFeature();
                                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/addFeature')}}",
                        {id:this.items[this.thisId][this.thisIndex].id,features:this.features})
                        .then(res=>{
                            if (res.data.success){
                                this.items[this.thisId][this.thisIndex].featureFormat = res.data.data.featureFormat;
                                this.items[this.thisId][this.thisIndex].feature = res.data.data.feature;
                                this.$forceUpdate();
                                $("#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);
                    });
                },
                delModel(id,index){
                    window.tempTip.confirm("确定要删除该作业计费吗？",()=>{
                        window.axios.delete("{{url('maintenance/priceModel/operation')}}/"+id)
                            .then(res=>{
                                if (res.data.success){
                                    this.$delete(this.models,index);
                                    window.tempTip.setDuration(2000);
                                    window.tempTip.showSuccess("已成功删除该条作业计费");
                                    return;
                                }
                                window.tempTip.setDuration(3000);
                                window.tempTip.show(res.data.data);
                            }).catch(err=>{
                            window.tempTip.setDuration(3000);
                            window.tempTip.show("网络错误："+err);
                        });
                    });
                },
                edit(id){
                    window.location.href = "{{url('maintenance/priceModel/operation')}}/"+id+"/edit";
                }
            },
        });
    </script>
@stop
