@extends('layouts.app')

@section('title','需求')

@section('content')
    <nav id="nav2">
        @component('demand.menu')@endcomponent
        @component('demand.search.menu')@endcomponent
    </nav>

    <div class="container-fluid d-none" id="list">
        <div id="form_div"></div>

        @include('demand.search._table')
        @include('demand.search._uploadFile')

    </div>
@endsection

@section('lastScript')
    <script src="{{mix('js/queryForm/queryForm.js')}}"></script>

    <script>
        let demand_vue = new Vue({
            el: '#list',
            data: {
                demands: {!! $demands->toJson() !!}['data'],
                status: [
                    {name: 0, value: '未处理'}, {name: 1, value: '处理中'}, {name: 2, value: '已处理'},
                ],
                types: [
                    {name: 0, value: '需求'}, {name: 1, value: '问题'}
                ],
                selectTr: null,
                uploadError: [],
                selectDemand: null,
                selectIndex: null,
                imgs: [],

            },
            created() {
                let that = this;
                this.demands.forEach(function (item, index, self) {
                    that.initDemand(self[index]);
                });
            },
            mounted() {
                this.imgs = Array.from(document.getElementById('list').querySelectorAll('img'));
                this.lazy();
                if (this.imgs && this.imgs.length > 0) {
                    window.addEventListener('scroll', this.lazy)
                }
                $('#list').removeClass('d-none');
                let data = [
                    [
                        {name: 'created_at_start', type: 'time', tip: '创建开始时间'},
                        {name: 'created_at_end', type: 'time', tip: '创建结束时间'},
                        {name: 'type', type: 'select', data: this.types, placeholder: '类型'},
                    ]
                ];
                let form = new query({
                    el: "#form_div",
                    condition: data,
                });
                form.init();
            },
            methods: {
                initDemand(demand) {
                    demand['status'] = this.status[demand['status']]['value'] ?? '';
                    demand['type'] = this.types[demand['type']]['value'] ?? '';
                    demand['showAddDiv']= false;
                    demand['showAddBtn']= false;
                    if (demand['upload_file']) this.setImgUrl(demand['upload_file']);
                    if (demand['processes']){
                        demand['processes'].forEach(function(item,index,self){
                            self[index]['status'] = false;
                        });
                    }
                },
                setImgUrl(uploadFile) {
                    let url = '{{url('/storage/')}}';
                    let urlPath = uploadFile['url'];
                    let type = uploadFile.type;
                    uploadFile['url'] = url + urlPath + '-thumbnail.' + type;
                    uploadFile['bulkyUrl'] = url + urlPath + '-bulky.' + type;
                    uploadFile['commonUrl'] = url + urlPath + '-common.' + type;
                },
                /** 完结需求 */
                finishDemand(demand,index) {
                    let url = '{{url('apiLocal/demand/finish')}}';
                    window.tempTip.setDuration(3000);
                    window.axios.post(url, {id: demand['id']}).then(res => {
                        if (res.data.success) {
                            window.tempTip.showSuccess('需求完结成功');
                            demand.status = '已处理'
                            return;
                        }
                        window.tempTip.show('需求完结失败' + res.data.data);
                    }).catch(err => {
                        window.tempTip.show('需求完结异常' + err);
                    });
                },
                /** 删除 */
                destroyDemand(demand, index) {
                    if (!confirm('确定要删除当前需求吗？')) {
                        return;
                    }
                    let url = '{{url('apiLocal/demand/destroy?id=')}}' + demand['id'];

                    window.axios.delete(url).then(res => {
                        if (res.data.success) {
                            window.tempTip.showSuccess('删除成功!');
                            this.$delete(this.demands,index);
                            this.imgs = Array.from(document.getElementById('list').querySelectorAll('img'));
                            this.lazy();
                            this.$forceUpdate();
                            return;
                        }
                        window.tempTip.show(res.data.data);
                    }).catch(err => {
                        window.tempTip.show('删除出现异常' + err);
                    });
                },
                /** 添加处理过程 */
                addProcess(demand) {
                    window.tempTip.setDuration(3000);
                    let url = '{{url('apiLocal/demand/process/store')}}';
                    let process = $('#addProcess'+demand['id']).val();
                    let data = {'demand_id': demand['id'], 'explain': process};
                    if(process === null || process.length === 0){
                        window.tempTip.show('输入内容');
                        $('#addProcess'+demand['id']).focus();
                        return;
                    }
                    window.axios.post(url, data).then(res => {
                        if (res.data.success) {
                            if(!demand['processes'])demand['processes']= [res.data.data];
                            else demand['processes'].unshift(res.data.data);
                            this.$forceUpdate();
                            window.tempTip.showSuccess('添加处理过程成功');
                            $('#addProcess'+demand['id']).val();
                            this.toggleAddDiv(demand,demand['id']);
                            return;
                        }
                        $('#addProcess'+demand['id']).focus();
                        window.tempTip.show('添加处理过程失败')
                    }).catch(err => {
                        $('#addProcess'+demand['id']).focus();
                        window.tempTip.show('添加处理过程异常:' + err);
                    });

                },
                /** 文件上传 */
                uploadFile() {
                    let fileInput = document.querySelector('#upLoadFile-input');
                    let url = '{{url('apiLocal/demand/uploadFile')}}';

                    let formData = new FormData();
                    formData.append('id', this.selectDemand);
                    let file = fileInput.files[0];
                    formData.append('file', file);
                    tempTip.setDuration(9999)
                    tempTip.setIndex(1051)
                    tempTip.waitingTip('上传中......');

                    if(fileInput.files.length === 0){
                        tempTip.cancelWaitingTip();
                        this.uploadError = ['请选择上传文件'];
                        return;
                    }
                    let that = this;
                    window.axios.post(url, formData, {
                        'Content-Type': 'multipart/form-data'
                    }).then(res => {
                        tempTip.cancelWaitingTip()
                        tempTip.setDuration(2000)
                        if (res.data.success) {
                            this.initDemand(res.data.data);
                            this.$set(this.demands, this.selectIndex, res.data.data);
                            $('#uploadFile').modal('hide');
                            setTimeout(function(){
                                that.imgs.push(document.getElementById('img_'+res.data.data['id']));
                                that.lazy();
                            },1);
                            window.tempTip.showSuccess('文件上传成功');
                            this.$forceUpdate();
                            return;
                        }
                        if(res.data.errors)this.uploadError = res.data.errors;
                        window.tempTip.show('文件上传失败');
                    }).catch(err => {
                        tempTip.cancelWaitingTip()
                        window.tempTip.show('文件上传异常：' + err);
                    });
                },
                /** 修改需求描述 */
                updateDemand(demand, column, $e) {
                    let url = '{{url('apiLocal/demand/update')}}';
                    let data = {'id': demand['id']};
                    let value = $($e.target).val();
                    data[column] = value;

                    window.tempTip.setDuration(3000);
                    window.axios.post(url, data).then(res => {
                        if (res.data.success) {
                            demand[column] = value;
                            this.$forceUpdate();
                            window.tempTip.showSuccess('修改需求成功');
                            return;
                        }
                        window.tempTip.show(res.data.data);
                    }).catch(err => {
                        window.tempTip.show('修改需求描述异常:' + err);
                    });
                },
                /** 问题认领 */
                claimDemand(demand, index) {
                    let url = '{{url('apiLocal/demand/claim')}}';
                    window.tempTip.setDuration(3000);
                    window.axios.post(url, {id: demand['id']}).then(res => {
                        if (res.data.success) {
                            this.initDemand(res.data.data);
                            this.$set(this.demands, index, res.data.data);
                            window.tempTip.showSuccess('认领成功!');
                            return;
                        }
                        if (res.data.errors) window.tempTip.show(res.data.errors);
                        else window.tempTip.show(res.data.data);
                    }).catch(err => {
                        window.tempTip.show('认领出现异常' + err);
                    });
                },
                showUploadDiv(demand, index) {
                    this.selectDemand = demand['id'];
                    this.selectIndex = index;
                    this.uploadError = [];
                    $('#uploadFile').modal('show');
                },
                lazy() {
                    //可视区域高度
                    let height = window.innerHeight;
                    //滚动区域高度
                    let scrollHeight = document.documentElement.scrollTop || document.body.scrollTop;
                    let _this = this;
                    this.imgs.forEach(function (img, i) {
                        if ((height + scrollHeight) > $('#' + img.getAttribute('id')).offset().top && img.getAttribute('data-src')) {
                            let temp = new Image();
                            temp.src = img.getAttribute('data-src');
                            temp.onload = function () {
                                img.src = img.getAttribute('data-src');
                                _this.$delete(_this.imgs, i);
                            }
                        }
                    });
                },
                removeCommonImg(id) {
                    $('#' + id).remove();
                },
                commonImg(id, demand,index) {
                    if (!demand['upload_file']) return;
                    let bulkyUrl = demand['upload_file']['bulkyUrl'];
                    let commonUrl = demand['upload_file']['commonUrl'];
                    $('#' + id).after(
                        "<div id=\"imgBulky_" + demand['id'] + "\" style='position: absolute;padding-top: 2px;z-index: 99'>" +
                        "<div style='position:absolute'>" +
                            "<div >" +
                            "<a target='_blank' href='" + bulkyUrl + "'>" +
                                "<img src='" + commonUrl + "'" + "style='position: relative;left:-50px;' >" +
                            "</a>" +
                            "</div>" +
                                "<button type='button' class='btn btn-sm btn-danger' onclick='demand_vue.btnDeleteImg(this,"+index+")' value='" + id + "' style='position: relative;float: right;margin-right: 51px;margin-top: -30px;' >删除</button>" +
                        "</div>" +
                        "</div>");
                },
                btnDeleteImg(e,index) {
                    let idStr = $(e).val()
                    let id = idStr.substr(idStr.indexOf('_') + 1)
                    if (!confirm('确定要删除所选图片吗？')) return;
                    this.destroyImg(id,index);
                },
                destroyImg(id,index) {
                    let url = '{{url('apiLocal/demand/destroyFile/?id=')}}'+id;
                    window.tempTip.setDuration(3000);
                    window.axios.delete(url).then(res=>{
                        if(res.data.success){
                            window.tempTip.showSuccess('附件删除成功！');
                            this.$delete(this.demands[index],['upload_file']);
                            this.$forceUpdate();
                            return ;
                        }
                        window.tempTip.show('附件删除异常:'+res.data.data);
                    }).catch(err=>{
                        window.tempTip.show(err);
                    });
                },
                toggleAddDiv(demand,id){
                    let div = $('#addDiv_'+id);
                    if(demand['showAddDiv']){
                        div.addClass('d-none');
                    }else{
                        div.removeClass('d-none');
                    }
                    demand['showAddDiv'] = !demand['showAddDiv'];
                },
                toggleDelBtn(demandId,process){
                    let btn = $('#demand-'+demandId+'process-'+process['id']);
                    if(process['status']){
                        btn.addClass('d-none');
                    }else{
                        btn.removeClass('d-none');
                    }
                    process['status'] = !process['status'];
                },
                showAddBtn(demand){
                    if(demand['showAddBtn']){
                        $("#addBtn_"+demand.id).addClass('d-none');
                    }else{
                        $("#addBtn_"+demand.id).removeClass('d-none');
                    }
                    demand['showAddBtn'] = !demand['showAddBtn'];
                },
                deleteProcess(demand,process,process_i,index){
                    if (!confirm('确定要删除当前描述吗？')) {
                        return;
                    }

                    let url = '{{url('apiLocal/demand/process/destroy/?id=')}}'+ process['id'];
                    window.tempTip.setDuration(3000);
                    window.axios.delete(url).then(res=>{
                        if(res.data.success){
                            this.$delete(this.demands[index]['processes'],process_i);
                            demand.processes.slice(process_i,0);
                            window.tempTip.showSuccess('描述删除成功！');
                            this.$forceUpdate();
                            return;
                        }
                        window.tempTip.show('描述删除失败！'+res.data.data ? res.data.data : '' );
                    }).catch(err=>{
                        window.tempTip.show(err);
                    });
                }
            }
        });
    </script>
@endsection
