<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta name="decorator" content="base"/>
    <link rel="stylesheet" href="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/style/admin.css" media="all">
    <link rel="stylesheet" href="${ctxPlugin}/static/css/reset.css" media="all">
</head>
<body>

<div class="layui-fluid">
    <div class="layui-card layui-form">
        <div class="layui-tab layui-tab-brief">
            <ul class="layui-tab-title">
                <sfTags:pagePermission authFlag="FWSGL_FWSGL_FWSGL_T" html='<li class="layui-this"><a href="${ctx}/siteInformation/siteDataList">服务商管理</a></li>'/>
                <sfTags:pagePermission authFlag="FWSGL_FWSGL_GCSGL_T" html='<li class=""><a href="${ctx}/employeInformation/employeList">工程师管理</a></li>'/>
                <button class="layui-btn f-r mt-10 mr-15 pl-10 pr-10 " id="searchBtn" data-type="reload">
                    <i class="layui-icon fs-12">&#xe615;</i>查询
                </button>
            </ul>
        </div>

        <div class="layui-card-body layuiadmin-card-header-auto" >
            <form class="layui-form layui-card" action="" id="searchForm">
                <div class="layui-form-item">
                    <div class="layui-col-md2 layui-col-sm3">
                        <label class="layui-form-label">服务商名称：</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" class="layui-input" id="name" >
                        </div>
                    </div>
                    <div class="layui-col-md2 layui-col-sm3">
                        <label class="layui-form-label">服务商地址：</label>
                        <div class="layui-input-block">
                            <input type="text" name="province" class="layui-input" id="province" >
                        </div>
                    </div>
                    <div class="layui-col-md2 layui-col-sm3">
                        <label class="layui-form-label">联系电话：</label>
                        <div class="layui-input-block">
                            <input type="text" name="telephone" class="layui-input" id="telephone" >
                        </div>
                    </div>
                    <%--<div class="layui-col-md2 layui-col-sm3" style="margin-left:20px">
                        <label class="layui-form-label">绑定crm客户：</label>
                        <div class="layui-input-block">
                            <select  id="customerId" name="customerId"  lay-search>
                                <option value="">请选择</option>
                                 <option value="1">未绑定</option>
                                 <option value="2">已绑定</option>
                            </select>
                        </div>
                    </div>--%>
                </div>
            </form>
        </div>

        <div class="layui-card-body">
            <table class="layui-hide " id="test" lay-filter="test"></table>
        </div>

    </div>
</div>
<div id="toolbarDemo" class="layui-form-item layui-hide">
    <sfTags:pagePermission authFlag="FWSGL_FWSGL_FWSGL_ADD" html='<button class="layui-btn layui-btn-sm" id="addBtn" lay-event="addSite"><i class="layui-icon layui-icon-add-1"></i>添加 </button>'/>
    <sfTags:pagePermission authFlag="FWSGL_FWSGL_FWSGL_DEL" html='<button class="layui-btn layui-btn-sm" id="deleteBtn" lay-event="delete"><i class="layui-icon layui-icon-delete"></i>删除 </button>'/>

   <%-- <sfTags:pagePermission authFlag="FWSGL_FWSGL_FWSGL_BINDING" html='<button class="layui-btn layui-btn-sm" id="bindingBtn" lay-event="binding"><i class="layui-icon layui-icon-ok-circle"></i>绑定CRM客户</button>'/>
    <sfTags:pagePermission authFlag="FWSGL_FWSGL_FWSGL_UNBUND" html='<button class="layui-btn layui-btn-sm" id="UnbundlingBtn" lay-event="Unbundling"><i class="layui-icon layui-icon-close-fill"></i>解除CRM客户</button>'/>
    --%>

    <sfTags:pagePermission authFlag="FWSGL_FWSGL_FWSGL_DC" html='<button class="layui-btn layui-btn-sm" id="exportBtn" lay-event="exports"><i class="layui-icon layui-icon-export"></i>导出 </button>'/>
</div>
</div>

<script src="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/layui/layui.js"></script>
<script src="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/layui/data.js"></script>
<script type="text/javascript">
    var saveMark = false;
    //初始数据
    var $form;
    var form;
    var upload;
    var $;
    var table;
    layui.config({
        base: '${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'tableExt', 'jquery', 'layer','laypage','laydate','form','excel'], function(){
        $ = layui.$
            ,form = layui.form
            ,tableExt = layui.tableExt;
        table = layui.table;
        var excel = layui.excel;
        //服务商信息列表
        var addDiZhi='${fns:checkPagePermission(request, "FWSGL_FWSGL_FWSGL_TJDZ_B")}';
        var updateDiZhi='${fns:checkPagePermission(request, "FWSGL_FWSGL_FWSGL_XGDZ_B")}';
        var detail='${fns:checkPagePermission(request, "FWSGL_FWSGL_FWSGL_FWSXQ_B")}';
        tableExt.render({
            elem: '#test'
            , height: 'full-130'
            , id: 'test'
            , defaultToolbar: false
            , url: '${ctx}/siteInformation/site'
            , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
            , page: true
            , toolbar:"#toolbarDemo"
            , method:"post"
            , limits: [20, 50, 100]
            , limit: 20
            , cols: [[
                {field: 'number', width: 50, title: '序号', align: 'center', type: 'numbers',rowspan:'2', fixed: 'left'}
                ,{field : 'id', width : '4%',checkbox : true,align : 'center',rowspan:'2' , fixed: 'left'}
                ,{field : 'customer_id', width : '4%',rowspan:'2' , fixed: 'left',hide:true}
                , {field: 'mobile', title: '操作', width: 150, align: 'center',rowspan:'2', fixed: 'left',
                    templet: function (d) {
                        var add;
                        if (isBlank(d.provincet)) {
                            if(addDiZhi=='0'){
                                add = '<a class="layui-table-opt-link" lay-event="add"><i class="layui-icon fs-16">&#xe654;</i>添加地址</a>';
                            }else{
                                add='--';
                            }
                        }else{
                            if(updateDiZhi=='0'){
                                add = '<a class="layui-table-opt-link" lay-event="edit"><i class="layui-icon fs-16">&#xe642;</i>编辑地址</a>'
                            }else{
                                add='--';
                            }
                        }
                        return add;
                    },
                }
                , {field: 'name', title: '服务商名称', width: 150, align: 'center',exportable:true ,rowspan:'2', fixed: 'left',templet:function(d){
                            var html = "";
                            if(detail=='0'){
                                html += "<a href=\"#\" class=\"layui-table-link\" onclick=\"siteDetail('"+d.id+"')\">"+d.name+"</a>";
                            }else{
                                html=d.name;
                            }
                            return html;
                        }}
                , {field: 'login_name', title: '登录账号', width: 200, align: 'center',exportable:true ,rowspan:'2'}
                , {field: 'contacts', width: 150, title: '联系人', align: 'center',exportable:true ,rowspan:'2'}
                , {field: 'telephone', width: 180, title: '联系电话', align: 'center',exportable:true ,rowspan:'2'}
                , {field: 'provincet', title: '计算里程默认地址', width: 400, align: 'center',exportable:true ,rowspan:'2',
                    templet: function (d) {
                        if (!isBlank(d.provincet) && !isBlank(d.cityt) && !isBlank(d.areat) && !isBlank(d.addresst)) {
                            return d.provincet+d.cityt+d.areat+d.addresst;
                        }else{
                            return "";
                        }
                    },
                    expFormat:function (d) {
                        if (!isBlank(d.provincet) && !isBlank(d.cityt) && !isBlank(d.areat) && !isBlank(d.addresst)) {
                            return d.provincet+d.cityt+d.areat+d.addresst;
                        }else{
                            return "";
                        }
                    }
                }
                , {field: 'available_amount', title: '备件额度', width: 100, align: 'center',exportable:true ,rowspan:'2'}
                , {field: 'customer_name', title: 'CRM客户名称', width: 400, align: 'center',exportable:true ,rowspan:'2',
                    templet: function (d) {
                      if(d.is_crm_customer =='2'){
                          return d.customer_name;
                      }
                      return "";
                    },
                    expFormat:function (d) {
                        if(d.is_crm_customer =='2'){
                            return d.customer_name;
                        }
                        return "";
                    }
                }
                , {field: 'province', title: '服务商地址', width: 400, align: 'center',exportable:true ,rowspan:'2',
                    templet: function (d) {
                        if (!isBlank(d.province) && !isBlank(d.city) && !isBlank(d.area) && !isBlank(d.address)) {
                            return d.province+d.city+d.area+d.address;
                        }else{
                            return "";
                        }
                    },
                    expFormat:function (d) {
                        if (!isBlank(d.province) && !isBlank(d.city) && !isBlank(d.area) && !isBlank(d.address)) {
                            return d.province+d.city+d.area+d.address;
                        }else{
                            return "";
                        }
                    }
                }
                , {field: 'amount', title: '工程师数量', width: 100, align: 'center',exportable:true ,rowspan:'2',templet:function(d){
                            var html = "";
                            return html + "<a href=\"#\" class=\"layui-table-link\" onclick=\"employeList('"+d.id+"')\">"+d.amount+"</a>";
                        }
                }
                , {field: 'refusal_count', title: '拒接工单次数', width: 140, align: 'center',exportable:true ,rowspan:'2'}
                , {field: 'create_time', title: '创建时间', width: 200, align: 'center',exportable:true ,rowspan:'2'}
            ],
            ]
            ,exportOpt:{                           //导出选项配置
                ele:'#exportBtn',                   //导出的Dom元素
                headerTitle: '服务商信息',             //excel表格的标题
                pageData:false,                     //true:导出的数据为页面数据，false:最大导出maxAmount条数据
                maxAmount: 1000,                    //当pageData为false生效
                fileName: '服务商信息',
                where: function (){
                    console.log(_serializeJson($("#searchForm")));//当pageData为false时生效，过滤的条件
                    return _serializeJson($("#searchForm"));
                }
            }
        });

        table.on('toolbar(test)',function(obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            if (obj.event === 'addSite') {
                layer.open({
                    type: 2,
                    title: '添加服务商',
                    content: '${ctx}/siteInformation/addSite',
                    area: ['80%', '80%']
                });
            } else if (obj.event === 'delete') {
                var data = checkStatus.data;
                if (data.length < 1) {
                    layer.msg("请先选择数据", {icon: 5, anim: 6});
                    return;
                }
                var ids = "";
                for (var i = 0; i < data.length; i++) {
                    ids += data[i].id + ",";
                }
                var indexla = layer.confirm('您确定要删除服务商吗？', {
                    icon: 3,
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    $.ajax({
                        type: "POST",
                        url: "${ctx}/siteInformation/deleteSite",
                        data: {
                            ids: ids
                        },
                        success: function (result) {
                            if(result.code=='200'){
                                layer.msg('删除成功！', {icon: 1, time: 1000}, function () {
                                    window.location.reload();
                                });
                            }else if(result.code=='501'){
                                layer.msg('该服务商有未完成工单，无法删除！', {icon: 2});
                            }else if(result.code=='502'){
                                layer.msg('该服务商有库存备件，无法删除!', {icon: 2});
                            }else if(result.code=='503'){
                                layer.msg('该服务商有未结算工单，无法删除!', {icon: 2});
                            }else {
                                layer.msg('删除失败!', {icon: 2});
                            }
                        },
                        error:{
                        }
                    })
                }, function () {
                    layer.close(indexla);
                });
            }else if(obj.event === 'Unbundling'){
                var data = checkStatus.data;
                if (data.length != 1) {
                    layer.msg("请先选择一个服务商数据",{icon:5,anim:6});
                    return;
                }
                var ids=data[0].id;
                var customerId = data[0].customer_id;
                if(isBlank(customerId)){
                    layer.msg('该服务商没有绑定CRM客户!', {icon: 2});
                    return ;
                }

                var indexla = layer.confirm('您确定要给服务商解除绑定客户吗？', {
                    icon: 3,
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    $.ajax({
                        type: "POST",
                        url: "${ctx}/siteInformation/Unbundling",
                        data: {
                            siteId: ids
                        },
                        success: function (result) {
                            layer.close(indexla);
                            if(result.code=='200'){
                                layer.msg('解绑成功！', {icon: 1, time: 1000}, function () {
                                    window.location.reload();
                                });
                            }else {
                                layer.msg('解绑失败!', {icon: 2});
                            }
                        },
                        error:{
                        }
                    })
                }, function () {
                    layer.close(indexla);
                });
            }else if(obj.event === 'binding'){
                var data = checkStatus.data;
                if (data.length != 1) {
                    layer.msg("请先选择一个服务商数据",{icon:5,anim:6});
                    return;
                }
                var ids=data[0].id;

                var customerId = data[0].customer_id;
                if(!isBlank(customerId)){
                    layer.msg('该服务商已经绑定CRM客户，不可重复绑定!', {icon: 2});
                    return ;
                }


                var indexla = layer.confirm('您确定要给服务商绑定客户吗？', {
                    icon: 3,
                    btn: ['确定', '取消'] //按钮
                }, function () {

                    layer.open({
                        type: 2,
                        title: '绑定CRM客户',
                        content: '${ctx}/siteInformation/bindingCustomer?id='+ids,
                        area: ['700px', '400px']
                    });
                    layer.close(indexla);
                }, function () {
                    layer.close(indexla);
                });
            }
        });

        //监听事件
        table.on('tool(test)', function (obj) {
            var data = obj.data;
            if (obj.event === 'add') {//添加地址
                var editId = data.id;
                layer.open({type: 2,
                    title: '添加地址',
                    content: '${ctx}/siteInformation/addRess?id=' + editId,
                    area: ['70%', '40%'],
                    btn: ['保存', '取消'],
                    yes: function (index, layero) {
                        var iframeWindow = window['layui-layer-iframe' + index]
                            , submitID = 'LAY-user-front-addRess'
                            , submit = layero.find('iframe').contents().find('#' + submitID);

                        //监听提交
                        iframeWindow.layui.form.on('submit(' + submitID + ')', function (data) {
                            var field = data.field; //获取提交的字段
                            addMark(field, index, editId);
                        });
                        submit.trigger('click');
                    },
                    success : function(layero) {
                        layero.find('.layui-layer-btn').css('text-align', 'center');
                        layero.find('.layui-layer-btn').find(".layui-layer-btn0").css("background-color","#009688");
                    }
                });
            }else if (obj.event === 'edit') {//编辑地址
                var editId = data.id;
                layer.open({
                    type: 2,
                    title: '编辑地址',
                    content: '${ctx}/siteInformation/editAddRess?id=' + editId,
                    area: ['70%', '40%'],
                    btn: ['保存', '取消'],
                    yes: function (index, layero) {
                        var iframeWindow = window['layui-layer-iframe' + index]
                            , submitID = 'LAY-user-front-addRess'
                            , submit = layero.find('iframe').contents().find('#' + submitID);

                        //监听提交
                        iframeWindow.layui.form.on('submit(' + submitID + ')', function (data) {
                            var field = data.field; //获取提交的字段
                            editAddressMark(field, index, editId);
                        });
                        submit.trigger('click');
                    },
                    success : function(layero) {
                        layero.find('.layui-layer-btn').css('text-align', 'center');
                        layero.find('.layui-layer-btn').find(".layui-layer-btn0").css("background-color","#009688");
                    }
                });
            }
        });

        $('input').on('keydown', function(event){
            if(event.keyCode == 13){
                //执行相关操作
                $("#searchBtn").click();
            }
        });

        //编辑地址
        var noRepeatAdd = false;
        function editAddressMark(data, index,id) {
            if (noRepeatAdd) {
                return;
            }
            noRepeatAdd = true;
            $.ajax({
                url: '${ctx}/siteInformation/editorAddressSave',
                type: 'post',
                data: {
                    id:id,
                    province: data.province,
                    city: data.city,
                    area: data.area,
                    address: data.address
                },
                success: function (data) {
                    if (data.code == "200") {
                        layer.msg("添加成功！", {icon: 1});
                        table.reload('test'); //数据刷新
                        layer.close(index); //关闭弹层
                    } else if (data.code == "205") {
                        layer.msg("添加失败！", {icon: 2});
                        table.reload('test'); //数据刷新
                    }
                },
                complete: function () {
                    noRepeatAdd = false;
                }
            });
        }


        //新增地址
        var noRepeatAdd = false;
        function addMark(data, index,id) {
            if (noRepeatAdd) {
                return;
            }
            noRepeatAdd = true;
            $.ajax({
                url: '${ctx}/siteInformation/addRessSave',
                type: 'post',
                data: {
                    id:id,
                    province: data.province,
                    city: data.city,
                    area: data.area,
                    address: data.address
                },
                success: function (data) {
                    if (data.code == "200") {
                        layer.msg("添加成功！", {icon: 1});
                        table.reload('test'); //数据刷新
                        layer.close(index); //关闭弹层
                    } else if (data.code == "205") {
                        layer.msg("添加失败！", {icon: 2});
                        table.reload('test'); //数据刷新
                    }
                },
                complete: function () {
                    noRepeatAdd = false;
                }
            });
        }

        function isBlank(val) {
            if (val == null || val == '' || val == undefined) {
                return true;
            }
            return false;
        }

        $('#searchBtn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        var active = {
            reload: function () {
                table.reload('test', {
                    where: {
                        name: $('#name').val(),
                        province: $("#province").val(),
                        telephone: $("#telephone").val(),
                        customerId: $("#customerId").val()
                    }
                });
            }
        };
    });


    function denglsj(id, userId) {
        console.log("siteInfo" + id + " userId : " + userId)
        parent.denglusdj(id, userId);
    }

    /*服务商详情*/
    function siteDetail(id) {
        layer.open({
            type: 2,
            title: " 服务商信息",
            area: ['80%', '80%'],
            resize: false,
            content: '${ctx}/siteInformation/addSite?id='+id
        });
    }

    /*服务商详情*/
    function employeList(id) {
        window.location.href = '${ctx}/employeInformation/employeList?id='+id;
    }


</script>
</body>
</html>
