var permDelete = $("#perm-delete").val();//删除权限
var permEdit = $("#perm-edit").val();//编辑权限

/**
 * 用户信息
 */
$(function () {
  var service = $("#contextPath").val();
  var param = {
    mobile: '',
    carNumber: '',
    custName: '',
    beginTime: '',
    endTime: '',
    status: '',
    source: '',
  };
  var detailList = {
    userName: '',
    orderNo: '',
    mobile: '',
    carNumber: '',
    orderContent: '',
    createTime: '',
    handleMen: '',
    amount: '',
    status: '',
    evaluate: ''
  };
  var checkedList = [];
  var price = 0;
  var custId = '';
  var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
  var table_data = new Array();
  var ids = '';
  var str = '';
  var workId = '';
  var orderId = '';
  // 数据获取
  var api = {
    set_detail_list: function (detailList, list) { //详情页面步骤
      let htmlDetail = "";
      $(".alert3 .order_name").text(detailList.userName);
      $(".alert3 .order_number").text(detailList.orderNo);
      $(".alert3 .order_mobile").text(detailList.mobile);
      $(".alert3 .order_car_number").text(detailList.carNumber);
      $(".alert3 .order_content").text(detailList.orderContent);
      $(".alert3 .order_createTime").text(detailList.createTime);
      $(".alert3 .order_washer").text(detailList.handleMen);
      $(".alert3 .order_amount").text(detailList.amount);
      $(".alert3 .order_status").text(detailList.status);
      $(".alert3 .order_evaluate").text(detailList.evaluate);
      $(".right .detail").removeClass('check');
      let statusTxt = "";
      for (let i = 0; i < list.length; i++) {
        statusTxt = api.getStatusDetail(list[i].operationType);
        htmlDetail +=
          "<li class='layui-timeline-item check detail'><i class='layui-icon layui-timeline-axis'></i><div class='layui-timeline-content layui-text' style='width:227px;'><h3 class='layui-timeline-title'>" +
          statusTxt + "</h3><p><span class='detail_time'>" +
          list[i].createTime +
          "</span><br><span class='detail_content'>" + list[i].represent + "</span></p></div></li>"
      }
      $(".right .layui-timeline").html(htmlDetail);
      // $(".right .detail").each(function (index, value) {
      //   if (index < list.length) {
      //     $(value).addClass('check');
      //     $(value).find('.detail_time').text(list[index].createTime);
      //     $(value).find('.detail_content').text(list[index].represent);
      //   }
      // })
    },
    get_order_status: function (status, isEvaluate, comment) { //详情页面状态和评价判断
      if (status != '') {
        if (status == 1) {
          return "等待接单"
        } else if (status == 2) {
          return "待洗车"
        } else if (status == 3) {
          return "洗车中"
        } else if (status == 4) {
          return "已完成"
        } else if (status == 5) {
          return "已转单"
        } else if (status == 6) {
          return "已取消"
        }
      }
      if (isEvaluate == 1) {
        $(".alert3 .order_evaluate").text('待评价');
      } else if (isEvaluate == 2) {
        $(".alert3 .order_evaluate").text(comment);
      }
    },
    get_order_detail: function (id) { //详情数据获取
      $.ajax({
        type: "post",
        url: service + "/admin/washcar/getWashOrderInfo",
        data: {
          id: id
        },
        success: function (data) {
          console.log(data, 333333);
          if (data.code == '200') {
            let detail = data.data;
            detailList = {
              userName: detail.userName,
              orderNo: detail.orderNo,
              mobile: detail.mobile,
              carNumber: detail.carNumber,
              orderContent: detail.orderContent,
              createTime: detail.createTime,
              handleMen: detail.handleMen,
              amount: detail.amount,
              status: api.get_order_status(detail.status),
              evaluate: api.get_order_status('', detail.isEvaluate, detail.comment)
            };
            api.set_detail_list(detailList, detail.list);
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    get_order_search: function (searchStr) { //搜索下单
      var orgIds = $(".alert2 #orgIds").attr('org__id');
      if(!orgIds){
        orgIds = $("#orgId").attr('org__id');
      }
      $.ajax({
        type: "post",
        url: service + "/admin/washcar/getCustmoerList",
        data: {
          searchStr: searchStr,
          page: 1,
          limit: 1,
          orgId: orgIds
        },
        success: function (data) {
          console.log(data, 9999);
          if (data.code == '200') {
            $("#username").val(data.data[0].userName);
            $("#mobile").val(data.data[0].mobile);
            $("#carNumber").val(data.data[0].carNumber);
            $("#parkSpace").val(data.data[0].parkSpace),
              custId = data.data[0].id;
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    get_order_current: function (params) { //下单
      let stringParam = {
        userId: params.userId,
        userName: params.userName,
        mobile: params.mobile,
        carNumber: params.carNumber,
        parkSpace: params.parkSpace,
        keySpace: params.keySpace,
        list: JSON.stringify(params.list),
        orgId: params.orgId
      };
      console.log(stringParam);
      $.ajax({
        type: "post",
        url: service + "/admin/washcar/saveWashOrder",
        data: stringParam,
        success: function (data) {
          let dataJ = data;
          console.log(dataJ);
          if (dataJ.code == '200') {
            layer.msg(dataJ.msg)
            $('.alert').css('display', 'block');
            api.set_initial_status();
            $("#orderIn").html('')
            $("#price").text(price.toFixed(2));
            api.get_user_order_list(param);

          } else {
            layer.msg(dataJ.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    get_order_project: function () { //获取下单项目
      var orderIn = "";
      $("#orderIn").html('');
      $(".has_no").css("display", "none");
      $("#orderIn").css("display", "none");
      var orgid = $(".alert2 #orgIds").attr('org__id');
      if(!orgid){
        orgid =  $("#orgId").attr('org__id');
      }
      $.ajax({
        type: "post",
        url: service + "/admin/washcar/getOrderIn",
        data: {
          projectId: orgid
        },
        success: function (data) {
          if (data.code == '200') {

            let list = data.data;
            // console.log(list,'6666666666');
            $("#orderIn").css("display", "block");
            $.each(list, function (index, value) {
              var trs = "";
              trs += "<input type='checkbox' name='like1[" + index + "]' lay-skin='primary' title='" + value.serviceName + ' ' + value.amount + " 元' value='" + value.id + "'  lay-filter='check" + value.id + "'>";
              orderIn += trs;
            })
            $("#orderIn").append(orderIn);
            checkedList = [];
            price = 0
            layui.use('form', function () {
              var form = layui.form;
              form.render('checkbox');
              for (let i = 0; i < list.length; i++) {
                form.on("checkbox(check" + list[i].id + ")", function (data) {
                  if (data.elem.checked) {
                    console.log(data, 111);
                    let json = data.elem.title.split(' ');
                    let select = {
                      id: data.value,
                      // serviceName: json[0],
                      // amount: json[1]
                    };
                    checkedList.push(select);
                    price += parseFloat(json[1]);
                    // console.log(checkedList,'aaa')
                    $("#price").text(price.toFixed(2));
                  } else {
                    let unJson = data.elem.title.split(' ');
                    price -= parseFloat(unJson[1]);
                    $("#price").text(price.toFixed(2));
                  }
                });
              };
              form.render('checkbox');
            });
          } else {
            $(".has_no").css("display", "block");
          }
        },
        error: function (error) {
          layer.msg('error');
        }
      });
    },
    get_paidan_step: function (id, washSerId) { //派单
      $.ajax({
        type: "post",
        url: service + "/admin/washcar/dispatch",
        data: {
          id: id,
          washSerId: washSerId
        },
        success: function (data) {
          console.log(data, 222222222);
          if (data.code == '200') {
            $('.layui-form-checkbox').removeClass('layui-form-checked');
            layer.msg(data.msg)
            str = '';
            $("#patchList").html('');
            $('.alert').css('display', 'none');
            api.get_user_order_list(param);
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    get_worker_list: function (id) { //获取洗车工人
      let worker = '';
      $.ajax({
        type: "post",
        url: service + "/admin/washcar/getWashCarService",
        data: {
          id: id
        },
        success: function (data) {
          console.log(data, 222222222);
          if (data.code == '200') {
            // api.get_patch_alert(data.data);
            let patchList = data.data;
            $.each(patchList, function (index, value) {
              worker += "<li class=''><input type='radio' id='" +
                value.id + "'  name='radio' class='index1'/><div class='layui-unselect layui-form-checkbox' lay-skin='primary'><i class='layui-icon'></i></div><div class='layui-table-cell laytable-cell-2-name patch1'><div class='operate'><span>" +
                value.name + "</span><span>(工号：" +
                value.workNo + ")</span></div></div><div class='layui-table-cell laytable-cell-2-workingCount patch1'><div class='operate'>进行中：" +
                value.workingCount + "单</div></div><div class='layui-table-cell laytable-cell-2-isOnline patch1'>状态：<span class='txt_blue status'>" + value.isOnline + "</span></div></li>";
            })
            worker += "<div class='clear'></div>"
            str = worker;
            $("#patchList").append(str);
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    get_worker_del: function (id) { //删除订单列表
      $.ajax({
        type: "post",
        url: service + "/admin/washcar/deleteOrder",
        data: {
          id: id
        },
        success: function (data) {
          console.log(data, 222222222);
          if (data.code == '200') {
            layer.msg(data.msg)
            api.get_user_order_list(param);
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    get_user_order_list: function (params) { //初次加载页面
      layui.use(['table', 'laydate', 'form'], function () {
        var table = layui.table;
        var form = layui.form,
          layer = layui.layer,
          laydate = layui.laydate;
        //日期
        laydate.render({
          elem: '#date1'
        });
        laydate.render({
          elem: '#date2'
        });
        table.render({
          elem: '#table_user_info',
          url: service + '/admin/washcar/getOrderList',
          method: 'post',
          where: {
            mobile: params.mobile,
            carNumber: params.carNumber,
            custName: params.custName,
            beginTime: params.beginTime,
            endTime: params.endTime,
            status: params.status,
            source: params.source,
            orgId: params.orgId
          },
          skin: 'nob', //行边框风格
          even: true, //开启隔行背景
          size: 'lg', //小尺寸的表格
          limit: 5,
          cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
          cols: [
            [{
                field: 'paixu',
                width: 96,
                title: '序号',
                templet: '#paixu',
              }, {
                field: 'status',
                width: 164,
                title: '状态',
                templet: function (data) {
                  if (data.status == 1) {
                    return "<span class='txt_blue'>等待接单</span>"
                  } else if (data.status == 2) {
                    return '待洗车'
                  } else if (data.status == 3) {
                    return '洗车中'
                  } else if (data.status == 4) {
                    return '已完成'
                  } else if (data.status == 5) {
                    return '已转单'
                  } else if (data.status == 6) {
                    return '已取消'
                  }
                }
              }, {
                field: 'orderNo',
                width: 174,
                title: '订单号',
              }, {
                field: 'userName',
                width: 174,
                title: '用户信息',
                templet: function (data) {
                  return "<div class='operate'><span class='tl'>姓名：" + data.userName + "</span><span class='tl'>电话：" + data.mobile + "</span><span class='tl'>车牌：" + data.carNumber + "</span></div>"
                }
              }, {
                field: 'orderContent',
                title: '订单内容',
                width: 174,
                minWidth: 100
              } //minWidth：局部定义当前单元格的最小宽度，layui 2.2.1 新增
              , {
                field: 'createTime',
                title: '创建时间',                                          
                width: 174
              }, {
                field: 'fullName',
                title: '处理人',
                width: 174
              }, {
                field: 'amount',
                width: 174,
                title: '费用'
              }, {                                         
                field: 'manage',
                width: 181,                                    
                title: '操作',
                    
                templet: function (data) {
                  var str = "<div class='operate'>";
                  if (data.status == 1 && permEdit == 1) {
                    str += "<span class='op_patch_btn' lay-event='patch' style='display: inline-block;float: left;line-height: 60px;margin-top: 32px;'><i class='patch'></i><i class='op_hover'>派单</i></span>"
                  }
                  if (data.status == 6 && permDelete == 1) {
                    str += "<span class='op_del_btn' lay-event='del' style='display: inline-block;float: left;line-height: 60px;margin-top: 32px;margin-left: 8px;'><i class='delete'></i><i class='op_hover'>删除</i></span>"
                  }

                  str += "<span class='op_detail_btn' lay-event='detail' style='display: inline-block;float: left;line-height: 60px;margin-top: 32px;margin-left: 8px;'><i class='detail'></i><i class='op_hover'>详情</i></span>"

                  str += "</div>";
                  return str;
                }
              }
            ]
          ],
          id: '',
          page: true,
          response: {
            statusName: 'code', //数据状态的字段名称，默认：code             
            statusCode: 200, //成功的状 态码，默认：0        
            countName: "count", //数据总数的字段名称，默认：count            
            dataName: "data" //数据列表的字段名称，默认：data
          },
          done: function (res, curr, count) {
            $(".patch,.delete,.detail").mouseover(function () {
              $(this).next().show();
            })
            $(".patch,.delete,.detail").mouseout(function () {
              $(this).next().hide();
            })
          }
        });
        table.on('tool(order)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
          console.log(obj.event); //点击事件
          console.log(obj.data, 'ddd');
          if (obj.event === 'patch') {
            $('.alert1').css('display', 'block');
            $('.alert1 .alert_con>h2').text('派单');
            orderId = obj.data.id;
            api.get_worker_list(orderId);
          } else if (obj.event === 'detail') {
            api.get_order_detail(obj.data.id);
            $('.alert3').css('display', 'block');
          } else if (obj.event === 'del') {
            layer.confirm('真的删除行么', function (index) {
              obj.del();
              layer.close(index);
              api.get_worker_del(obj.data.id);
            });
          }
          //所在行的所有相关数据  
        });
      });
    },
    get_form_summit_val: function (params) { //清空数据
      $("#username").val(params.userName);
      $("#mobile").val(params.mobile);
      $("#carNumber").val(params.carNumber);
      $("#dept").val(params.dept);
      $("#position").val(params.position);
      $("#carType").val(params.carType);
      $("#parkSpace").val(params.parkSpace);
    },
    get_patch_alert: function (data) { //洗车工人页面渲染
      layui.use('table', function () {
        var table = layui.table;
        table.render({
          elem: '#patch',
          cols: [
            [{
                type: 'checkbox',
                checkbox: true
              },
              {
                field: 'name',
                width: 145,
                templet: function (data) {
                  return "<div class='operate'><span>" + data.name + "</span><span>(工号：" + data.workNo + ")</span></div>"
                }
              }, {
                field: 'workingCount',
                width: 95,
                templet: function (data) {
                  return "<div class='operate'>进行中：" + data.workingCount + "单</div>"
                }
              }, {
                field: 'isOnline',
                width: 100,
                templet: function (data) {
                  if (data.isOnline == 1) {
                    return "状态：<span class=''>下班</span>"
                  } else if (data.isOnline == 2) {
                    return "状态：<span class='txt_blue'>上班</span>"
                  }
                }
              }
            ]
          ],
          data: data,
          done: function (res, curr, count) {
            table_data = res.data;
            for (var i = 0; i < res.data.length; i++) {
              //数据id和要勾选的id相同时checkbox选中
              if (res.data[i].id == ids) {
                //这里才是真正的有效勾选
                res.data[i]["LAY_CHECKED"] = 'true';
                //找到对应数据改变勾选样式，呈现出选中效果
                var index = res.data[i]['LAY_TABLE_INDEX'];
                $('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                $('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
              }

            }
          }
        });
        //监听工具条
        table.on('checkbox(paidan)', function (obj) {
          console.log(obj);
          // var data = obj.data;
          if (obj.checked) {
            ids = obj.data.id;
            // alert(obj.data.id); //洗车工id
          }
        });
      });
    },
    toJson: function (str) { //转化为Json格式
      if (JSON && JSON.parse) {
        return JSON.parse(str);
      } else {
        return eval('(' + str + ')');
      }
    },
    set_initial_status: function () { //初始化数据
      checkedList = [];
      price = 0;
      $("#orderIn").html('')
      $("#price").text(price);
      $("#search").val('');
      $("#username").val('');
      $("#mobile").val('');
      $("#carNumber").val('');
      $("#parkSpace").val('');
      str = '';
      $("#patchList").html('');
      $("#orderIn").html('');
      $(".has_no").css("display", "none");
      $("#orderIn").css("display", "none");
      $('#orgIds').get(0).selectedIndex = 0;
      layui.form.render('select');
    },
    getStatusDetail: function (status) {
      console.log(111111111111);
      switch (status) {
        case 10:
          return "创建"
          break;
        case 11:
          return "派单"
          break;
        case 16:
          return "取消订单"
          break;
        case 13:
          return "洗车中"
          break;
        case 14:
          return "已完成"
          break;
        case 15:
          return "转单"
          break;
      }
    },
    search_fuzzy: function(){
      $('body').on("input",'#orgId',function(event){
        var _this = $(this)
        cjqt.search_fuzzy.event_input(_this,'org__id','org__span',service,'/admin/templ/getOrgListByName')
      });
      $('body').on("focus",'#orgId',function(event){
        var _this = $(this)
        cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',service,'/admin/templ/getOrgListByName')
      });
      $('body').on('blur','#orgId',function(event) {
        var _this = $(this)
        cjqt.search_fuzzy.event_blur(_this,'org__id')
      });
      $('body').on('click','#orgId~.select_wrap>.org__span', function(event) {
        event.preventDefault();
        event.stopPropagation();
        /* Act on the event */
        var _this = $(this)
        cjqt.search_fuzzy.event_click(_this,'org__id','#orgId')
      });

      $('body').on("input",'#orgIds',function(event){
        var _this = $(this)
        cjqt.search_fuzzy.event_input(_this,'org__id','org__span',service,'/admin/templ/getOrgListByName')
      });
      $('body').on("focus",'#orgIds',function(event){
        var _this = $(this)
        cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',service,'/admin/templ/getOrgListByName')
      });
      $('body').on('blur','#orgIds',function(event) {
        var _this = $(this)
        cjqt.search_fuzzy.event_blur(_this,'org__id')
      });
      $('body').on('click','#orgIds~.select_wrap>.org__span', function(event) {
        event.preventDefault();
        event.stopPropagation();
        /* Act on the event */
        var _this = $(this)
        cjqt.search_fuzzy.event_click(_this,'org__id','#orgIds')
      });
    },
  };
  // 模糊搜索
  api.search_fuzzy()
  api.get_user_order_list(param);

  // 下单项目选择
  $("#orgIds").change(function () {
    setTimeout(function(){
      api.get_order_project();
    },200)
  })
  // 事件处理
  $('.btn1').click(function () {
    $('.alert2').css('display', 'block');
    $('.alert2 .alert_con>h2').text('下单');
    api.get_order_project();
  })
  // 下单
  $('.saveBtn2').click(function () {
    var data = {
      userId: custId,
      userName: $("#username").val(),
      mobile: $("#mobile").val(),
      carNumber: $("#carNumber").val(),
      parkSpace: $("#parkSpace").val(),
      keySpace: $("#keySpace").val(),
      list: checkedList,
      orgId: $("#orgId").attr('org__id')
    };
    console.log(data)
    if (data.userId != '') {
      api.get_order_current(data);
    }
  })
  // 派单
  $('.saveBtn1').click(function () {
    api.get_paidan_step(orderId, workId);
    // $('.alert').css('display', 'none');
  })
  // 关闭弹框按钮
  $('.cancelBtn').click(function () {
    $('.alert').css('display', 'none');
    api.set_initial_status();
    detailList = {
      userName: '',
      orderNo: '',
      mobile: '',
      carNumber: '',
      orderContent: '',
      createTime: '',
      handleMen: '',
      amount: '',
      status: '',
      evaluate: ''
    };
    api.set_detail_list(detailList);
  })
  // 查询
  $('#searchUser').click(function () {
    let data = {
      mobile: $('input[name="phone"]').val(),
      carNumber: $('input[name="number"]').val(),
      custName: $('input[name="custName"]').val(),
      beginTime: $('input[name="date1"]').val(),
      endTime: $('input[name="date2"]').val(),
      status: $('#status').val(),
      source: $('#root').val(),
      orgId: $('#orgId').attr('org__id')
    };
    console.log(data);
    api.get_user_order_list(data);
  })
  // 重置
  $('#resetSearch').click(function () {
    $('input[name="phone"]').val('');
    $('input[name="number"]').val('');
    $('input[name="custName"]').val('');
    $('input[name="date1"]').val('');
    $('input[name="date2"]').val('');
    $('#status').get(0).selectedIndex = 0;
    $('#root').get(0).selectedIndex = 0;
    $('#orgId').get(0).selectedIndex = 0;
    layui.form.render('select');
  })
  // 搜索下单
  $('.search_icon').click(function () {
    let pros = $("#search").val();
    console.log(pros);
    api.get_order_search(pros);
  })
  $("#patchList").on('click', '.index1', function () {
    // console.log(this);
    workId = this.id;
    $('.layui-form-checkbox').removeClass('layui-form-checked');
    $("#" + workId + "").next().addClass('layui-form-checked');
  })
})