//config的设置是全局的
layui.config({
    base: '/static/js/extend/' //假设这是你存放拓展模块的根目录
}).extend({ //设定模块别名
    common: 'common' //如果 mymod.js 是在根目录，也可以不用设定别名
});


layui.use(['form','table','common'], function() {
    var form = layui.form;
    var common = layui.common;
    var table = layui.table;
    var tableInfo=table.render({
            elem: '#business'
            ,url:'/business/getList'
            ,id: 'id'
            ,where:{
                 queryUserPhone:$("input[name='queryUserPhone']").val(),
                 queryMaintenanceState:$("#queryMaintenanceState").val()
            }
            ,method:"post"
            ,contentType:"application/json;charset=UTF-8"
            ,loading:true
            ,cols: [[
                {field:'id', title: 'ID', sort: true,checkbox:true ,fixed: 'left'}
                ,{field:'businessNo', title: '服务编号'}
                ,{field:'userName', title: '用户名称'}
                ,{field:'userCellphone', title: '用户手机号', sort: true}
                ,{field:'address', title: '维修地址',templet:function (d) {
                    return common.ajaxGetRequest("/lbs/getLbsMapById",{id:d.provinceId}).name+"" +common.ajaxGetRequest("/lbs/getLbsMapById",{id:d.city}).name+" "+common.ajaxGetRequest("/lbs/getLbsMapById",{id:d.regionId}).name+" "+d.address
                }}
                ,{field:'remarks', title: '备注'}
                ,{field:'maintainType', title: '服务类型',templet:function (d) {
                    return d.maintainType==1?"维修":"安装"
                }}
                ,{field:'businessType', title: '分配类型',templet:function (d) {
                    return d.businessType==1?"系统分配":"抢单"
                }}
                ,{field:'payType', title: '支付方式',templet:function (d) {
                    if (d.payType==null){
                       return "暂无支付记录"
                    }else if (d.payType==1){
                        return "微信"
                    }else if (d.payType==2){
                        return "支付宝"
                    }
                }}
                ,{field:'installType', title: '维修类型',templet:function (d){
                    if (d.installType=="installationPrice"){
                      return "门锁安装（不修不改）";
                    }else if (d.installType=="modifyPrice"){
                      return "门锁安装（含修孔）";
                    }else if (d.installType=="openingPrice"){
                      return "门锁安装（含开孔）";
                    }else if (d.installType=="newOpeningPrice"){
                      return "门锁安装（全新开孔）";
                    }else{
                        return "/";
                    }
                }}
                ,{field:'repairPrice', title: '维修价格'}
                ,{field:'repairPrice', title: '零售价',templet:function (d) {
                    return d.repairPrice+"￥";
                }}
                ,{field:'maintenanceState', title: '接单状态',templet:function (d) {
                        return getMaintenanceState(d.maintenanceState);
                }}
                ,{field:'marketPrice', title: '分配订单',toolbar: '#openRepair'}
            ]]
            ,page: true
    });

//监听行工具事件
    var parentData=undefined;
    table.on('tool(business)', function(obj){
        if (obj.event=='open'){
            layer.open({
                type: 1,
                skin: 'layui-layer-rim', //加上边框
                area: ['70%', '80%'], //宽高
                content: $("#openRepairDiv")
            });
            table.render({
                elem: '#openRepairTable'
                , url: '/user/getList'
                , id: 'openRepairTable'
                , where: {
                    master:1,
                    regionId:obj.data.regionId
                }
                ,method:"post"
                ,defaultToolbar: ['filter', 'print', 'exports']
                ,contentType:"application/json;charset=UTF-8"
                , loading: true
                , cols: [[
                    {field: 'id', title: 'ID', sort: true, checkbox: true, fixed: 'left'}
                    , {field: 'userNo', title: '维修师傅编号'}
                    , {field: 'name', title: '师傅名称'}
                    , {field: 'userCellphone', title: '手机号'}
                    , {field: 'provinceId', title: '省份'}
                    , {field: 'cityId', title: '市'}
                    , {field: 'areaId', title: '区'}
                    , {field: 'servicesAreaId', title: '维修区域'}
                    , {field: 'team', title: '是否团队',templet:function (d) {
                        return d.team=1?"是":"否";
                    }}
                    , {field: 'teamNumber', title: '团队人数'}
                    , {field: 'createTime', title: '创建时间'}
                    , {fixed: 'right', title: '操作', width: 100,templet:function (d) {
                            if(obj.data.repairId!=d.id){
                                return '<a class="layui-btn layui-btn-xs" lay-event="selectRepair">分配</a>'
                            }else{
                                return '正在维修';
                            }

                        }}
                ]]
                , page: true
            });
            parentData=obj.data;
        }
    });

    table.on('tool(openRepairTable)', function(obj){
        if (obj.event=='selectRepair'){
            layer.confirm('您是否要将本次维修派送给'+obj.data.name+"师傅？", {
                btn: ['配送','取消'] //按钮
            }, function(){
                var result= common.ajaxPostRequest("/business/pushTask",{userNo:obj.data.userNo,businessNo:parentData.businessNo},"openRepairTable");
                if (result==undefined){
                    parentData.repairId=obj.data.id;
                    layer.alert("分配成功！", {
                        icon: 1,
                        skin: 'layer-ext-moon'
                    });
                }
            });

        }
    });
    //处理级联查询
    form.on('select(selectRegion)', function(data){
        if (data.elem.id!='regionId'){
            var targetId=data.elem.id=='province'?"city":"regionId";
            common.ajaxRegionRequest(targetId,data.value);
            if (data.elem.id=='province'){
                $("#area").find("option").remove();
                $("#area").append('<option value="">请选择</option>');
            }
            form.render();
        }
    });

    //处理级联查询
    form.on('select(selectParent)', function(data){
        if (data.elem.id!='repairNode'){
            common.ajaxNodeRequest(data.elem.name,data.value,"/businessCategory/getByParentId");
            form.render();
        }
        if (data.elem.name=='categoryId'){
            var businessCategory= common.ajaxGetRequest("/businessCategory/getById",{id:data.value,state:1});
            form.val('initData', {
                 "openHolePriceHide": businessCategory.openHole
                ,"simpleMaintenanceHide": businessCategory.simpleMaintenance
                ,"mediumMaintenanceHide": businessCategory.mediumMaintenance
                ,"severeMaintenanceHide": businessCategory.severeMaintenance
                ,"retailPrice": businessCategory.retailPrice
                ,"marketPrice": businessCategory.marketPrice
            });
        }
    });

    //处理级联查询
    form.on('select(selectParentNode)', function(data){
        $("#marketPrice").val($('#repairNode option:selected').attr("marketprice"));
    });

    //处理级联查询
    form.on('radio(selectOpenHole)', function(data){
        if (data.value==1){
            $("#maintenanceDiv").show();
        }else{
            $("#maintenanceDiv").hide();
        }
    });

    //监听提交
    form.on('submit(formDemo)', function(data){
        if (data.field.id==null){
            data.field.address=$('#province option:selected').text()+" "+$('#city option:selected').text()+" "+$('#area option:selected').text()+" "+data.field.address;
        }
        data.field.provinceId=$('#province option:selected').val();
        data.field.city=$('#city option:selected').val();
        data.field.openHolePrice=$("#openHolePriceHide").val();
        if(data.field.openHoleType==1){
            if (data.field.maintenanceType==3){
                data.field.maintenancePrice= $("#severeMaintenanceHide").val();
            } else if(data.field.maintenanceType==2){
                data.field.maintenancePrice=$("#mediumMaintenanceHide").val();
            }else if(data.field.maintenanceType==1){
                data.field.maintenancePrice=$("#simpleMaintenanceHide").val();
            }
        }
        common.ajaxPostRequest("/business/saveOrUpdate",data.field);
    });

    //重置按钮
    $(document).on('click', '#resetButton', function() {
        $("#add-main select").find("option").removeAttr("selected");
        $("#add-main select").find("option").eq(0).attr("selected","selected");
        $("#marketPrice").val(null);
        form.render('select'); //刷新select选择框渲染
        $('#input[name="maintenanceType"]').removeAttr("checked");
        $('#input[name="openHoleType"]').removeAttr("checked");
        $('input[name="maintenanceType"][value="1"]').attr("checked");
        $('input[name="openHoleType"][value="0"]').attr("checked");
        $("#maintenanceDiv").hide();

    });

    //删除按钮
    $(document).on('click', '#deleteBusinessByIds', function() {
        var checketData= table.checkStatus('id');
        if (checketData.data.length==0){
            layer.alert("请选择一条数据", {
                icon: 2,
                skin: 'layer-ext-moon'
            })
            return false;
        }
        layer.confirm('确定要删除？', {
            btn: ['确认','取消'] //按钮
        }, function(){
            var ids="";
            for (var i=0;i<checketData.data.length;i++){
                ids+=checketData.data[i].id+","
            }
            common.ajaxGetRequest("/business/deleteBusinessById",{ids:ids.substring(0,ids.length-1)},"id");
            layer.close(layer.index);
        });
    });

    //修改
    $(document).on('click', '#getBusinessById', function() {
        var checketData= table.checkStatus('id');
        if (checketData.data.length==0){
            layer.alert("请选择一条数据", {
                icon: 2,
                skin: 'layer-ext-moon'
            })
            return false;
        }else if (checketData.data.length>1) {
            layer.alert("只能选择一条数据", {
                icon: 2,
                skin: 'layer-ext-moon'
            })
            return false;
        }
        var data={id:checketData.data[0].id};
        var result= common.ajaxGetRequest("/business/getBusinessById",data);
        openSaveOrUpdate()

        //区域
        common.ajaxRegionRequest("regionId",result.city);
        //市区
        common.ajaxRegionRequest("city",result.provinceId);
        //查看类目信息
        var repair= common.ajaxGetRequest("/businessCategory/getById",{id:result.categoryId,state:1});
        //加载类目信息
        common.ajaxNodeRequest("repairNode",repair.parentId)
        common.ajaxNodeRequest("repairParent",0)
        console.log(repair)
        form.val('initData', {
            "userCellphone": result.userCellphone
            ,"retailPrice": result.retailPrice
            ,"address": result.address
            ,"remarks": result.remarks
            ,"id": result.id
            ,"marketPrice": result.marketPrice
            ,"userName": result.userName
            ,"regionId": result.regionId
            ,"city": result.city
            ,"province": result.provinceId
            ,"categoryId":repair.id
            ,"repairNode": repair.parentId
            ,"otherPrice": result.otherPrice
            ,"markupPrice": result.markupPrice
            ,"emptyPrice": result.emptyPrice
        });
        console.log(repair.emptyPrice);
        console.log(repair.markupPrice);
        console.log(repair.otherPrice);

        if (result.openHoleType=1){
            $('input[name="openHoleType"][value="1"]').attr("checked","checked");
            $("#maintenanceDiv").show();
            $('input[name="maintenanceType"][value="'+result.maintenanceType+'"]').attr("checked","checked");
        }else{
            $('input[name="openHoleType"][value="0"]').attr("checked","checked");
        }
        form.render()
    });

    //打开新增or 修改窗口
    $(document).on('click', '#openSaveOrUpdate', function() {
        openSaveOrUpdate();
    });

    function openSaveOrUpdate() {
        common.layuiOpen("add-main","60%","60%")
        $("#resetButton").trigger('click');
        common.ajaxRegionRequest("province",1)
        common.ajaxNodeRequest("repairParent",0)
    }

    $(document).on('click', '#queryForm', function() {
        table.reload("id",{
           where:{
                 queryUserPhone:$("input[name='queryUserPhone']").val(),
                 queryMaintenanceState:$("#queryMaintenanceState").val()
          }
        })
    });

});


function getMaintenanceState(state) {
      if (state==0){
        return "待接待";
      }else if(state==1){
        return "待预约";
      }else if(state==2){
        return "预约失败";
      }else if(state==3){
        return "待上门";
      }else if(state==4){
        return "已出发";
      }else if(state==5){
        return "已返工";
      }else if(state==6){
        return "维修确认";
      }else if(state==7){
        return "待回访";
      }else if(state==8){
        return "已入账";
      }else if(state==9){
        return "评价打分";
      }else if(state==9){
        return "申请售后";
      }
}

