@extends('layouts.app')
@section('title')客户@endsection

@section('content')
    <div id="nav2">
        @component('customer.menu')@endcomponent
        @component('customer.customer.menu')@endcomponent
    </div>
    <div class="d-none container-fluid card" id="container">
        <div class="card-body mt-2">
            <div id="form_div" class="mb-2"></div>
            @if(Session::has('successTip'))
                <div class="alert alert-success h1">{{Session::get('successTip')}}</div>
            @endif
            @include("customer.customer._customerLog")
            @include("customer.customer._addContract")
            @include("customer.customer._relatedOwner")
            <table class="table table-striped table-hover 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="(customer,i) in customers" :id="'model-'+customer.id">
                    <td>@{{ i+1 }}</td>
                    <td>@{{ customer.code }}</td>
                    <td>@{{ customer.name }}</td>
                    <td>@{{ customer.company_name }}</td>
                    <td>@{{ customer.invoice_address }}</td>
                    <td>@{{ customer.contact_man }}</td>
                    <td>@{{ customer.phone }}</td>
                    <td>@{{ customer.remark }}</td>
                    <td><span class="cursor-pointer" @click="showCustomerLog(customer.id,i)">查看</span></td>
                    <td v-if="customer.contractQuantity>0" class="cursor-pointer" @click="showContract(customer.id)"><span class="fa" :class="contractIds['_'+customer.id] === true ? 'fa-angle-double-down' : 'fa-angle-double-right'"></span>@{{ customer.contractQuantity }}份合同</td>
                    <td v-else>#</td>
                    <td>@{{ customer.created_at }}</td>
                    <td>
                        <div v-show="tagIndexes[i]">
                            <select :id="'sel-'+i" class="selectpicker" multiple data-live-search="true" title="标签(多选)">
                                <option v-for="tag in tags" :value="tag.name">@{{ tag.value }}</option>
                            </select><br>
                            <button class="btn btn-sm btn-success" @click="addTag(i)">确定</button>
                            <button class="btn btn-sm btn-danger" @click="cancelTag(i)">取消</button>
                        </div>
                        <div v-if="!tagIndexes[i]">
                            <span v-for="(tag,i) in customer.tags">
                                <span class="badge badge-primary m-1" >@{{ tag.name }}</span><br v-if="(i+1)%2 === 0">
                            </span>
                        </div>
                    </td>
                    <td>
                        @can("客户-编辑")
                            <button class="btn btn-sm btn-outline-success" @click="addContract(i)">新建合同</button>
                            <button v-if="!tagIndexes[i]" class="btn btn-sm btn-info text-white" @click="setTag(i)">设定标签</button>
                            <button class="btn btn-sm btn-outline-primary" @click="relatedOwner(i)">关联项目</button>
                            <a :href="'{{url('customer/customer')}}/'+customer.id+'/edit'"><button class="btn btn-sm btn-outline-info">改</button></a>
                        @endcan
                        @can("客户-删除")<button class="btn btn-sm btn-outline-danger" @click="destroy(customer.id,i,customer.name)">删</button>@endcan
                    </td>
                </tr>
            </table>
        </div>
    </div>
@stop

@section('lastScript')
    <script type="text/javascript" src="{{mix('js/queryForm/queryForm.js')}}"></script>
    <script>
        new Vue({
            el:"#container",
            data:{
                customers :  {!!  $customers->toJson() !!}['data'],
                customerLogs : [],
                index:'',
                currentLogIndex:"",
                logStatuses:[],
                contractIds:[],
                customerOwners:[],
                files:[],
                owners:[
                  @foreach($owners as $owner)
                    {id:"{{$owner->id}}",name:"{{$owner->name}}",customer_id:"{{$owner->customer_id}}"},
                  @endforeach
                ],
                ownerIds:[],
                ownerNames:[],
                tagIndexes : [],
                tags:[
                    @foreach($tags as $tag)
                    {name:"{{$tag->id}}",value:"{{$tag->name}}"},
                    @endforeach
                ],
            },
            mounted(){
                this._formatOwner();
                $('#container').removeClass('d-none');
                this.rendering();
                let data=[
                    [
                        {name:'company_name',type:'input',tip:'可在检索值前加百分号(%)进行模糊搜索',placeholder:'公司名称'},
                        {name:'contact_man',type:'input',tip:'可在检索值前加百分号(%)进行模糊搜索',placeholder:'联系人'},
                        {name:'phone',type:'input',tip:'可在检索值前加百分号(%)进行模糊搜索',placeholder:'联系电话'},
                        {name:'tags',type:'select_multiple_select',tip:['输入关键词快速定位下拉列表，回车确定','选择要显示的客户'],
                            placeholder:['标签','定位或多选标签'],data:this.tags},
                    ]
                ];
                new query({
                    el:"#form_div",
                    condition:data,
                }).init();
            },
            methods:{
                addTag(index){
                    let val = $("#sel-"+index).selectpicker('val');
                    let url = "{{url('customer/customer/addTag')}}";
                    let params = {id:this.customers[index]['id'],tags:val};
                    window.tempTip.postBasicRequest(url,params,(res)=>{
                        this.customers[index].tags = res;
                        this.tagIndexes[index] = false;
                        this.$forceUpdate();
                        return "设定标签成功";
                    });
                },
                cancelTag(index){
                    this.tagIndexes[index] = false;
                    this.$forceUpdate();
                },
                setTag(index) {
                    this.tagIndexes[index] = true;
                    let defaults = [];
                    if (this.customers[index].tags){
                        this.customers[index].tags.forEach(tag=>{
                            defaults.push(tag.id);
                        });
                    }
                    this.$forceUpdate();
                    /*if (this.tags.length<1){
                        window.tempTip.postBasicRequest("{{--{{url('customer/customer/customerTag/get')}}--}}",{},(res)=>{
                            this.tags = res;
                        });
                    }*/
                    //setTimeout(()=>{
                        $(".selectpicker").selectpicker('refresh').selectpicker('val',defaults);
                    //},500);
                },
                _formatOwner(){
                    let ownerIds=[];
                    let ownerNames=[];
                    this.owners.forEach(owner=>{
                        if (owner.customer_id){
                            if (ownerIds[owner.customer_id]){
                                ownerIds[owner.customer_id].push(owner.id);
                                ownerNames[owner.customer_id].push(owner.name);
                            }else{
                                ownerIds[owner.customer_id] = [owner.id];
                                ownerNames[owner.customer_id] = [owner.name];
                            }
                        }
                    });
                    this.ownerIds = ownerIds;
                    this.ownerNames = ownerNames;
                },
                relatedOwner(index){
                    this.index = index;
                    this.$forceUpdate();
                    let val = this.ownerIds[this.customers[index]['id']];
                    $("#ownerSelectpicker").selectpicker('val',val ? val : []);
                    $("#relatedOwner").modal('show');
                },
                selectFile(){
                    $("#files").click();
                },
                uploadFiles(event){
                    let files = event.target.files;
                    for(let i=0;i<files.length;i++){
                        this.files.push(files[i]);
                    }
                },
                deleteFile(index){
                    this.$delete(this.files,index);
                },
                rendering() {
                    this.customers.forEach((customer,i)=> {
                        let contracts = [];
                        if (customer.owners)
                        customer.owners.forEach(owner=> {
                            if (owner.contracts)
                            owner.contracts.forEach(contract=>{
                                contracts.push({
                                    number:contract.contract_number,
                                    salesman:contract.salesman,
                                    remark:contract.remark,
                                    ownerName:owner.name,
                                    files:contract.files ? contract.files : []});
                            });
                        });
                        customer["contractQuantity"] = contracts.length;
                        this._renderingHtml(customer.id,contracts);
                    });
                    this.$forceUpdate();
                },
                destroy(id,index,name){
                    window.tempTip.confirm("确定要删除客户“"+name+"”吗？",()=>{
                        window.axios.delete("{{url('customer/customer')}}/"+id)
                            .then(res=>{
                                if (res.data.success){
                                    this.$delete(this.customers,index);
                                    window.tempTip.setDuration(2000);
                                    window.tempTip.showSuccess("删除"+name+"成功");
                                    return;
                                }
                                window.tempTip.setDuration(3000);
                                window.tempTip.show(res.data.data);
                            }).catch(err=>{
                            window.tempTip.setDuration(3000);
                            window.tempTip.show("网络错误："+err);
                        })
                    })
                },
                showCustomerLog(id,index){
                    this.index = index;
                    if (this.customerLogs[id]){
                        $("#modal").modal('show');
                        return;
                    }
                    let url="{{url('customer/customer/getLog')}}";
                    let params = {customer_id:id};
                    window.tempTip.postBasicRequest(url,params,(res)=> {
                        this.customerLogs[id] = res;
                        this.$forceUpdate();
                        $("#modal").modal('show');
                    });
                },
                textClass(event,isOver){
                    event = event.target.children[0];
                    if (isOver){event.classList.remove("text-overflow-replace");}
                    else {event.classList.add("text-overflow-replace");}
                },
                edit(index,user){
                    let id = "{{\Illuminate\Support\Facades\Auth::id()}}";
                    if (id != user.id) return;
                    if (index === 0)this.currentLogIndex=index;
                    else this.currentLogIndex='';
                },
                closeEditLog(){
                    this.currentLogIndex = '';
                    if (this.customerLogs[this.customers[this.index]['id']][0].id === ''){
                        this.$delete(this.customerLogs[this.customers[this.index]['id']],0);
                    }
                },
                editLog(){
                    let log = this.customerLogs[this.customers[this.index]['id']][this.currentLogIndex];
                    if (log.id === ''){
                        let description = $("#description-"+log.id)[0].value;
                        let logStatus = $("#logStatus-"+log.id)[0].value;
                        let url="{{url('customer/customer/storeLog')}}";
                        let params = {customer_id:this.customers[this.index]['id'],description:description,customer_log_status_id:logStatus};
                        window.tempTip.postBasicRequest(url,params,(res)=>{
                            this.customerLogs[this.customers[this.index]['id']][0] = res;
                            this.currentLogIndex = '';
                            this.$forceUpdate();
                            return "成功创建客户日志";
                        },true);
                        return;
                    }
                    let url="{{url('customer/customer/editLog')}}";
                    let description = $("#description-"+log.id)[0].value;
                    let params = {id:log.id,description:description};
                    window.tempTip.postBasicRequest(url,params,(res)=> {
                        this.customerLogs[this.customers[this.index]['id']][this.currentLogIndex].description = description;
                        this.currentLogIndex = '';
                        this.$forceUpdate();
                        return "修改说明成功！";
                    },true);
                },
                addLog(){
                    if (this.logStatuses.length < 1)window.tempTip.postBasicRequest("{{url('customer/customer/getLogStatus')}}",{},(res)=>{
                        this.logStatuses = res;
                    },true);
                    let logs = this.customerLogs[this.customers[this.index]['id']];
                    if (logs.length > 0 && logs[0].id === "")return;
                    logs.unshift({
                        id:"",
                        status:{name:""},
                        user:{name:"{{\Illuminate\Support\Facades\Auth::user()->name}}"},
                        description:"",
                        created_at:"",
                    });
                    this.currentLogIndex = 0;
                    this.$forceUpdate();
                },
                showContract(id){
                    if (this.contractIds['_'+id] &&  this.contractIds['_'+id]===true){
                        this.contractIds['_'+id] = false;
                        $("#customer-"+id).slideUp(undefined,function () {
                            $("#customer-tr-"+id).addClass("d-none");
                        });
                    }else {
                        $("#customer-tr-"+id).removeClass("d-none");
                        this.contractIds['_'+id] = true;
                        $("#customer-"+id).slideDown();
                    }
                    this.$forceUpdate();
                },
                _renderingHtml(id,contracts){
                    let domId   = "customer-"+id;
                    let trDomId = "customer-tr-"+id;
                    let html = "<tr class='d-none' id='"+trDomId+"'><td colspan='12'>"+
                        "<div id='"+domId+"'><table class='table table-sm'>"+
                        "<tr id='contract-tr-"+id+"'><th>合同号</th><th>销售姓名</th><th>所属项目</th><th>备注</th><th>附件</th></tr>";
                    contracts.forEach(contract=> {
                        html = this._createContractList(html,contract.number,contract.salesman,contract.ownerName,contract.remark,contract.files);
                    });
                    html += "</table></div></td></tr>";
                    $("#model-"+id).after(html);
                    $("#"+domId).slideUp();
                },
                _createContractList(html,number,salesman,ownerName,remark,files){
                    html += "<tr><td>"+number+"</td><td>"+salesman+"</td><td>"+ownerName+"</td><td><div style='white-space: normal;max-width: 200px' '>"+remark+"</div</td><td class='p-0'>";
                    if (files) files.forEach(function (file) {
                        let name = file.file_name;
                        let url = '{{url('customer/ownerContract/down?file=')}}'+file.url+"&name="+name;
                        if (file.type === 'jpg' || file.type === 'png'){
                            html += "<a target='_blank' href='"+url+"' class='small'><span class='fa fa-file-image-o'></span>"+name+"</a><br>";
                        }else html += "<a target='_blank' href='"+url+"' class='small'><span class='fa fa-link'></span>"+name+"</a><br>";
                    });
                    html += "</td></tr>";
                    return html;
                },
                addContract(index){
                    this.index = index;
                    let id = this.customers[index].id;
                    if (!this.customerOwners[id]){
                        let url = "{{url("maintenance/owner/get")}}";
                        let params = {customer_id:id};
                        window.tempTip.postBasicRequest(url,params,(res)=> {
                            this.customerOwners[id] = res;
                            this.$forceUpdate();
                        });
                    }
                    $("#addContract").modal("show");
                },
                submitContract(){
                    window.tempTip.setIndex(1099);
                    let owner = document.getElementById("owner").value;
                    let number = document.getElementById("contract_number").value;
                    let remark = document.getElementById("remark").value;
                    if (!owner || !number){
                        window.tempTip.show("项目与合同号为必输项");
                        return;
                    }
                    let formData = new FormData();
                    this.files.forEach(file=>{
                        formData.append("files[]",file);
                    });
                    formData.append("owner_id",owner);
                    formData.append("contract_number",number);
                    formData.append("remark",remark);
                    window.tempTip.setDuration(9999);
                    window.tempTip.waitingTip("新建中,请耐心等候......");
                    window.axios.post('{{url('customer/ownerContract/store')}}',formData,{
                        'Content-Type':'multipart/form-data'
                    }).then(res=>{
                        if (res.data.success){
                            this.files = [];
                            let id = this.customers[this.index].id;
                            let html = this._createContractList('',
                                res.data.data.contract_number,
                                res.data.data.salesman,
                                res.data.data.owner ? res.data.data.owner.name : '',
                                res.data.data.remark,
                                res.data.data.files);
                            this.customers[this.index].contractQuantity += 1;
                            $("#contract-tr-"+id).after(html);
                            window.tempTip.cancelWaitingTip();
                            window.tempTip.setDuration(2000);
                            window.tempTip.showSuccess("新建合同“"+number+"”成功");
                            $("#addContract").modal("hide");
                            return;
                        }
                        window.tempTip.cancelWaitingTip();
                        window.tempTip.setDuration(3000);
                        window.tempTip.show(res.data.data);
                    }).catch(err=>{
                        window.tempTip.cancelWaitingTip();
                        window.tempTip.setDuration(3000);
                        window.tempTip.show('网络错误：'+err);
                    });
                },
                submitRelatedOwner(){
                    let val = $("#ownerSelectpicker").selectpicker('val');
                    let id = this.customers[this.index]['id'];
                    if (val.length>0){
                        let error = "";
                        let storage = [];
                        this.owners.forEach(owner=>{

                            if (owner.customer_id){
                                val.forEach((v,i)=>{
                                    if (v===owner.id&&(owner.customer_id!=id)){
                                        error += owner.name+",";
                                        storage.push(i);
                                    }
                                });
                            }
                        });
                        if (error){
                            window.tempTip.setIndex(1099);
                            window.tempTip.confirm(error+"已绑定其他客户,是否取消选中",()=>{
                                storage.forEach(s=>{
                                    val.splice(s,1);
                                });
                                $("#ownerSelectpicker").selectpicker('val',val);
                            });
                            return;
                        }
                    }
                    let url = "{{url('customer/customer/relatedOwner')}}";
                    let params = {ids:val,customer_id:id};
                    window.tempTip.postBasicRequest(url,params,(res)=>{
                        let names = [];
                        this.owners.forEach(owner=>{
                            if (val.indexOf(owner.id) !== -1)names.push(owner.name);
                        });
                        this.ownerNames[id] = names;
                        this.$forceUpdate();
                        return "关联成功";
                    },true);
                }
            },
            filters:{
                size:function (val) {
                    if (!val)return '';
                    val = Number(parseInt(val/1024));
                    if (val >= 1024){
                        return  parseInt(val/1024)+"MB";
                    }
                    return val+"KB";
                }
            },
        });
    </script>
@stop
