@extends('layouts.app')

@section('title','卸货任务')

@section('content')
    <div id="nav2">
        @component('personnel.menu')@endcomponent
        @component('personnel.discharge.menu')@endcomponent
        @component('personnel.discharge.task.menu')@endcomponent
    </div>
    <div id="list" class="d-none container-fluid">
        <div id="form_div"  style="min-width: 2250px"></div>

        <div class="form-inline mt-1" id="btn">
            <span class="dropdown">
                <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="dischargeTaskExport(false)" href="javascript:">导出勾选内容</a>
                    <a class="dropdown-item" @click="dischargeTaskExport(true)" href="javascript:">导出所有页</a>
                </div>
            </span>
            <span class="ml-1">
                @can('人事管理-卸货-创建')
                <button type="button" class="btn btn-outline-dark btn-sm form-control-sm tooltipTarget" @click="showCreateTaskModal(true)" style="background: #dad7e8;">创建任务</button>
                @endcan
            </span>
        </div>
        @include('personnel.discharge.task._table')
        @can('人事管理-卸货-创建')
        @include('personnel.discharge.task._createTask')
        @endcan
        @can('人事管理-卸货-编辑')
        @include('personnel.discharge.task._executeTask')
        @endcan
    </div>
@endsection

@section('lastScript')
    <script type="text/javascript" src="{{mix('js/queryForm/queryForm.js')}}"></script>
    <script type="text/javascript" src="{{mix('js/queryForm/export.js')}}"></script>
    <script>
        let dischargeTaskVue = new Vue({
            el: "#list",
            data: {
                dischargeTasks: {!! $dischargeTasks->toJson()!!}['data'],
                owners:{!! $owners !!},
                ownerFilter: [],
                facilitators:{!! $facilitators !!},
                warehouses:{!! $warehouses !!},
                facilitatorsFilter: [],
                addTask: {income_at:null},
                executingTack: {},
                taskError:{},
                taskTypes: [
                    {name: 0, value: "装车"},
                    {name: 1, value: "卸车"},
                    {name: 2, value: "翻托"},
                    {name: 3, value: "包膜"},
                ],
                units: [
                    {name: 0, value: 'm3'},
                    {name: 1, value: '吨'},
                    {name: 2, value: '件'},
                    {name: 3, value: '托'},
                ],
                status: [
                    {name: 0, value: '创建'},
                    {name: 1, value: '接单'},
                    // {name: 2, value: '作业中'},
                    {name: 3, value: '完成'},
                ],
                isUpdate: false,
                checkData: [],
                selectIndex: '',
                selectTr:0,
            },
            created() {
                this.owners.forEach(function (owner, index, array) {
                    array[index] = {
                        name: owner.id,
                        value: owner.name,
                    };
                });
                this.ownerFilter = JSON.parse(JSON.stringify(this.owners));
                this.facilitatorsFilter = JSON.parse(JSON.stringify(this.facilitators));
                this.dischargeTasks.forEach(function(task,index,self){
                    self[index]['btnText'] = '查';
                });
            },
            mounted() {
                $('#list').removeClass('d-none');
                $(".tooltipTarget").tooltip({'trigger': 'hover'});
                let _this = this;
                let data = [[
                    {
                        name: 'owner_id', type: 'select_multiple_select', tip: ['输入关键词快速定位下拉列表，回车确定', '选择要显示的客户'],
                        placeholder: ['货主', '定位或多选货主'],
                        data: _this.owners
                    },
                    {name: 'created_at_start', type: 'dateTime', tip: '创建开始日期'},
                    {name: 'created_at_end', type: 'dateTime', tip: '创建结束日期'},
                    {name: 'numbers', type: 'input', tip: '可支持多入库单号，模糊搜索可在两侧增加百分号(%)进行',placeholder:'入库单号'},
                    {name: 'status', type: 'select', tip: '状态' , data: _this.status,placeholder:'状态'},
                    {name: 'income_remark', type: 'input', tip: '备注' , data: _this.status,placeholder:'备注'}
                ]];
                this.form = new query({
                    el: '#form_div',
                    condition: data,
                    appendDom : "btn",
                    paginations:[ 50, 100, 200, 500,1000,20],
                })
                this.form.init();
                this.$forceUpdate();
            },
            watch: {
                checkData: {
                    handler() {
                        if (this.checkData.length === this.dischargeTasks.length) {
                            document.querySelector('#selectAll').checked = true;
                        } else {
                            document.querySelector('#selectAll').checked = false;
                        }
                    },
                    deep: true
                },
            },
            methods: {
                getUnit(type) {
                    let unit = ''
                    this.units.forEach(function (item) {
                        if (item.name === type) unit = item.value;
                    });
                    return unit;
                },
                getType(value) {
                    let type = ''
                    this.taskTypes.forEach(function (item) {
                        if (item.name === value) type = item.value;
                    });
                    return type;
                },
                getStatus(value) {
                    let status = '';
                    this.status.forEach(function (item) {
                        if (item.name === value) status = item.value;
                    })
                    return status;
                },
                checkAll(e) {
                    if (!e.target.checked) this.checkData = [];
                    else {
                        this.dischargeTasks.forEach((el, i) => {
                            if (this.checkData.indexOf(el['id']) === -1) this.checkData.push(el['id']);
                        });
                    }
                },
                // 创建任务 modals
                showCreateTaskModal(isDisplay) {
                    $('owner-name-filter').val('');
                    if (isDisplay){
                        if(!this.isUpdate)this.addTask.income_at =  moment().format('YYYY-MM-DDTHH:mm');
                        this.$forceUpdate();
                        $("#createdModal").modal('show');
                    } else {
                        this.isUpdate = false;
                        $("#createdModal").modal('hide');
                    }
                },
                // 执行任务 modal
                showExecutingTaskModal(index, isDisplay, task) {
                    $('owner-name-filter').val('');
                    this.executingTack = JSON.parse(JSON.stringify(task));
                    this.selectIndex = index;
                    if (isDisplay) {
                        this.executingTack.expenditure_at = moment().format('YYYY-MM-DDTHH:mm');
                        this.isUpdate = true;
                        this.$forceUpdate();
                        $("#executingTaskModal").modal('show');
                    } else {
                        this.isUpdate = false;
                        this.selectIndex = null;
                        $("#executingTaskModal").modal('hide');
                    }
                },
                // 编辑任务 modal
                showUpdateTaskModal(index, isDisplay, task) {
                    this.isUpdate = true;
                    this.selectIndex = Number(index);
                    this.addTask = JSON.parse(JSON.stringify(task));
                    this.showCreateTaskModal(isDisplay)
                },
                // 创建任务
                createTask(index) {
                    console.log(this.addTask);
                    if (this.isUpdate) {
                        this.updateCurrentTask(index);
                        return
                    }
                    this.addTask['income_total_cost'] = Number(this.addTask['income_unit_price']) * Number(this.addTask.income_amount);
                    this.addTask['status'] = 0;
                    let url = '{{url('apiLocal/personnel/discharge/task/store')}}';
                    tempTip.setDuration(2000);
                    tempTip.setIndex(999);
                    axios.post(url, this.addTask).then(res => {
                        if (res.data.success) {
                            tempTip.showSuccess("添加卸货任务成功")
                            this.dischargeTasks.unshift(res.data.data);
                            this.showCreateTaskModal(false);
                            this.addTask = {};
                            return ;
                        }
                        if(res.data.errors){
                            this.taskError = res.data.errors ;
                            return ;
                        }
                        tempTip.show(res.data.message ?? (res.data.data ?? '添加卸货任务失败'));
                    }).catch(err => {
                        tempTip.show(err);
                    });
                },
                // 执行任务
                executedTask(dischargeTask, index) {
                    let url = '{{url('apiLocal/personnel/discharge/task/updateFacilitator')}}';
                    tempTip.setDuration(2000);
                    tempTip.setIndex(9999);
                    dischargeTask['income_total_cost'] = Number(dischargeTask['income_unit_price']) * (dischargeTask['income_amount']);
                    dischargeTask['status'] = 1;
                    axios.put(url, dischargeTask).then(res => {
                        if (res.data.success) {
                            this.$set(this.dischargeTasks, index, res.data.data);
                            this.showExecutingTaskModal(null,false,null);
                            tempTip.showSuccess("任务操作成功");
                            this.selectIndex = null;
                            this.executingTack = {};
                            return;
                        }
                        if(res.data.errors){
                            this.taskError = res.data.errors;
                            return ;
                        }
                        tempTip.show(res.data.data);
                    }).catch(err => {
                        tempTip.show(err);
                    })
                },
                // 编辑当前任务
                updateCurrentTask(addTask,index) {
                    // 更新
                    let url = '{{url('apiLocal/personnel/discharge/task/update')}}';
                    tempTip.setDuration(2000);
                    tempTip.setIndex(2000);
                    axios.put(url, addTask).then(res => {
                        if (res.data.success) {
                            tempTip.showSuccess("修改成功")
                            this.showCreateTaskModal(false);
                            this.$set(this.dischargeTasks, index, res.data.data);
                            this.addTask = {};
                            this.selectIndex = null;
                            return;
                        }
                        res.data.message ? tempTip.show(res.data.message) : null;
                    }).catch(err => {
                        tempTip.show(err);
                    });
                    this.selectIndex = null;
                },
                updateCurrentTaskColumn(task,index,column,$e){
                    let url = '{{url('apiLocal/personnel/discharge/task/updateColumn')}}';
                    tempTip.setDuration(2000);
                    tempTip.setIndex(99);
                    let value = $($e.target).val();
                    let data = {id:task.id};
                    data[column] = value;
                    window.axios.put(url, data).then(res => {
                        if (res.data.success) {
                            if(res.data.data.status === 3)res.data.data.btnText = '查';
                            this.$set(this.dischargeTasks, index, res.data.data);
                            tempTip.showSuccess("修改成功")
                            this.addTask = {};
                            this.selectIndex = null;
                            return;
                        }else if(res.data.errors){
                            tempTip.show(res.data.errors);
                            return;
                        }
                        tempTip.show(res.data.data)
                        this.$set(this.dischargeTasks, index, task);
                    }).catch(err => {
                        tempTip.show(err);
                    });
                    this.selectIndex = null;
                },
                // 删除当前任务
                deleteTask(index, dischargeTask) {
                    if (!confirm("是否删除当前任务")) {
                        return
                    }
                    let url = '{{url('apiLocal/personnel/discharge/task/delete/?id=')}}'+dischargeTask['id'];
                    tempTip.setDuration(2000);
                    tempTip.setIndex(99);
                    axios.delete(url).then(res => {
                        if (res.data.success) {
                            this.$delete(this.dischargeTasks, index);
                            tempTip.showSuccess('删除成功')
                            return
                        }
                        tempTip.show('删除失败!' + res.data.data)
                    }).catch(err => {
                        tempTip.show(err);
                    });
                },
                // 下载
                dischargeTaskExport(isExportAll) {
                    let url = '{{url('personnel/discharge/task/export')}}';
                    let token = '{{ csrf_token() }}';
                    excelExport(isExportAll, this.checkData, url, this.sum, token);
                },
                // 筛选货主
                filterOwner(e) {
                    let value = $(e.target).val();
                    if (value === '') {
                        this.ownerFilter = JSON.parse(JSON.stringify(this.owners));
                        this.addTask.owner_id = null;
                    }
                    else {
                        this.ownerFilter = this.owners.filter(function (owner) {
                            return owner.value.indexOf(value) !== -1;
                        });
                        if(this.ownerFilter.length > 0)this.addTask.owner_id =this.ownerFilter[0]['name'];
                        else this.addTask.owner_id = null;

                    }
                },
                // 筛选装卸队
                filterProviders(e) {
                    let value = $(e.target).val();
                    if (value === '') this.facilitatorsFilter = JSON.parse(JSON.stringify(this.facilitators));
                    else {
                        let facilitators = JSON.parse(JSON.stringify(this.facilitators));
                        this.facilitatorsFilter = facilitators.filter(function (item) {
                            return item.name.indexOf(value) !== -1;
                        });
                        if(this.facilitatorsFilter.length > 0){
                            this.executingTack.facilitator_id =this.facilitatorsFilter[0]['id'];
                        }
                    }
                },
                getReceiptUrl(id){
                    return '{{url('personnel/discharge/task/receipt')}}'+'/?id='+id;
                },
                showReceipt(task){
                    window.open(this.getReceiptUrl(task.id));
                }


            }
        })
    </script>

@endsection
