layui.use('laydate', function () {
  var laydate = layui.laydate;
  //日期时间范围
  laydate.render({
    elem: '#test10'
    , range: true
  });
});

layui.use(['table', 'jquery'], function () {
  var table = layui.table;
  var form = layui.form,
    layer = parent.layer === undefined ? layui.layer : parent.layer,
    $ = layui.jquery;
  //监听表格复选框选择
  table.on('checkbox(demo)', function (obj) {
    console.log(obj)
  });
  //监听工具条
  table.on('tool(demo)', function (obj) {
    var data = obj.data;
    if (obj.event === 'edit') {
      helper.cookies.set('F_WORKORDERID', data.F_WORKORDERID);
      //置忙

      var dataJson = {
        workid: data.F_WORKORDERID
      }

      $.ajax({
        url: "/Order/canDZ",
        type: "post",
        async: false,//同步请求
        contentType: "application/json",
        dataType: "text",
        cache: false,
        data: JSON.stringify(dataJson),
        success: function (thisResult) {
          if (thisResult) {
            if ($("#SeatFlag").val() == 1) {
              top.AgentBusy();
            }
            layer.open({
              type: 2,
              anim: 4,
              scrollbar: false,
              content: '/Order/EditMyOrder/?dtype=' + $("#dtype").val() + '&orderKeyId=' + data.F_WORKORDERID,
              area: ['90%', '90%'],
              id: 'CallWorkFolw',
              title: '服务监督热线系统业务工单',
              end: function () {

                //置闲
                if ($("#SeatFlag").val() == 1) {
                  top.AgentFree();
                }
                //执行重载
                table.reload('recordtable', {
                  page: {
                    curr: 1 //重新从第 1 页开始 
                  }
                  , where: {
                    types: 0,
                    dateParty: $("#test10").val()
                    , NowDateTime: new Date()
                    , workorderNum: $("#workorderNum").val()
                    , cusName: $("#cusName").val()
                    , userInfo: $("#userInfo").val()
                    , bussType: $("#bussType").val()
                    , detailType: $("#bussDetail").val()
                    , Content: $("#Content").val()
                    , F_RETURNVISITRESULT: $("#FromType").val()
                  }
                });
              }

            });
          } else {
            layer.msg('该工单在编辑');

          }

        },
        error: function (error) {
          return false;
        }
      });

    }
    else if (obj.event === 'view') {
      layer.open({
        type: 2,
        anim: 4,
        scrollbar: false,
        content: '/Order/ViewMyOrder/?orderKeyId=' + data.F_WORKORDERID,
        area: ['90%', '90%'],
        id: 'ViewMyOrder',
        title: '服务监督热线系统业务工单'

      });
    } else if (obj.event === 'overrule') {
      layer.open({
        type: 1,
        title: '确认驳回么？',
        skin: 'layui-layer-molv',
        closeBtn: 0,
        shadeClose: true,
        shade: false,
        area: ['300px', '200px'],
        content: '<div id="mydiv" style="margin-left:10px;margin-top:10px;">' +
          '<textarea placeholder="请输入驳回内容" id="txtReason" style="width:280px;height:70px;resize:none;border-radius:6px;border-color:#ccc;" >' +
          '</textarea></div>',
        btn: ['确定', '取消']
        , yes: function (index, layero) {
          var txtReason = $.trim(top.$('#txtReason').val());
          if (!txtReason) {
            layer.msg('请输入驳回意见！');
            return
          }
          layer.close(index)
          $.ajax({
            url: "/WorkOrder/OverruleDHFWorkOrder",
            type: "get",
            async: false,//同步请求
            contentType: "application/json",
            dataType: "text",
            cache: false,
            data: {
              workOrderId: data.F_WORKORDERID,
              opinion: txtReason
            },
            success: function (thisResult, result) {

              if (thisResult == "True") {
                layer.open({
                  content: '驳回成功'
                  , icon: 1
                  , btn: ['确定']
                  , yes: function (index, layero) {
                    //执行重载
                    table.reload('recordtable', {
                      page: {
                        curr: 1 //重新从第 1 页开始
                      }
                      , where: {
                        types: 0,
                        dateParty: $("#test10").val()
                        , NowDateTime: new Date()
                        , workorderNum: $("#workorderNum").val()
                        , cusName: $("#cusName").val()
                        , phoneNumber: $("#phoneNumber").val()
                        , userInfo: $("#userInfo").val()
                        , bussType: $("#bussType").val()
                        , detailType: $("#bussDetail").val()
                        , Content: $("#Content").val()
                      }
                    });
                    layer.close(index);
                  }
                });
              } else {
                layui.layer.alert("驳回失败!", {
                  icon: 2
                });

              }
            },
            error: function (error) {
              return false;
            }
          });
        }
      });

    } else if (obj.event === 'overruleDZ') {
      layer.open({
        type: 1,
        title: '确认驳回么？',
        skin: 'layui-layer-molv',
        closeBtn: 0,
        shadeClose: true,
        shade: false,
        area: ['300px', '200px'],
        content: '<div id="mydiv" style="margin-left:10px;margin-top:10px;">' +
          '<textarea placeholder="请输入驳回内容" id="txtReason" style="width:280px;height:70px;resize:none;border-radius:6px;border-color:#ccc;" >' +
          '</textarea></div>',
        btn: ['确定', '取消']
        , yes: function (index, layero) {
          var txtReason = $.trim(top.$('#txtReason').val());
          if (!txtReason) {
            layer.msg('请输入驳回意见！');
            return
          }
          layer.close(index)
          $.ajax({
            url: "/WorkOrder/OverruleDDZWorkOrder",
            type: "get",
            async: false,//同步请求
            contentType: "application/json",
            dataType: "text",
            cache: false,
            data: {
              workOrderId: data.F_WORKORDERID,
              opinion: txtReason
            },
            success: function (thisResult, result) {

              if (thisResult == "True") {
                layer.open({
                  content: '驳回成功'
                  , icon: 1
                  , btn: ['确定']
                  , yes: function (index, layero) {
                    //执行重载
                    table.reload('recordtable', {
                      page: {
                        curr: 1 //重新从第 1 页开始
                      }
                      , where: {
                        types: 0,
                        dateParty: $("#test10").val()
                        , NowDateTime: new Date()
                        , workorderNum: $("#workorderNum").val()
                        , cusName: $("#cusName").val()
                        , phoneNumber: $("#phoneNumber").val()
                        , userInfo: $("#userInfo").val()
                        , bussType: $("#bussType").val()
                        , detailType: $("#bussDetail").val()
                        , Content: $("#Content").val()
                      }
                    });
                    layer.close(index);
                  }
                });
              } else {
                layui.layer.alert("驳回失败!", {
                  icon: 2
                });

              }
            },
            error: function (error) {
              return false;
            }
          });
        }
      });
    } else if (obj.event === 'withdrawDeal') {
      // /Order/ResetDealedWorkOrder
      layer.open({
        type:1,
        titel:'确认撤回么？',
        closeBtn:0,
        shadeClose:true,
        shade:false,
        area:['300px','200px'],
        content:'<div id="mydiv" style="margin-left:10px;margin-top:10px;">' +
        '<textarea placeholder="请输入撤回内容" id="txtReason" style="width:280px;height:70px;resize:none;border-radius:6px;border-color:#ccc;" >' +
        '</textarea></div>',
        btn:['确定','取消'],
          yes: function (index, layero){
          var textReason = top.$('#txtReason').val();
          layer.close(index)
          $.ajax({
            url: "/Order/ResetDealedWorkOrder",
            type: "get",
            async: false,//同步请求
            contentType: "application/json",
            dataType: "text",
            cache: false,
            data: {
              workOrderId: data.F_WORKORDERID,
                reason: textReason
            },
            success: function (thisResult, result) {
            if (thisResult == "True") {
              layer.open({
                content: '提交撤回成功'
                , icon: 1
                , btn: ['确定']
                , yes: function (index, layero) {
                  //执行重载
                  table.reload('recordtable', {
                    page: {
                      curr: 1 //重新从第 1 页开始
                    }
                    , where: {
                      types: 0,
                      dateParty: $("#test10").val()
                      , NowDateTime: new Date()
                      , workorderNum: $("#workorderNum").val()
                      , cusName: $("#cusName").val()
                      , phoneNumber: $("#phoneNumber").val()
                      , userInfo: $("#userInfo").val()
                      , bussType: $("#bussType").val()
                      , detailType: $("#bussDetail").val()
                      , Content: $("#Content").val()
                    }
                  });
                  layer.close(index);
                }
              });
            } else {
                layui.layer.alert("提交撤回失败!", {
                  icon: 2
                });
  
              }
            },
            error: function (error) {
              return false;
            }
          });
        },

      })

    } else if (obj.event === 'withdrawVisit') {
      layer.open({
        type:1,
        titel:'确认撤回么？',
        closeBtn:0,
        shadeClose:true,
        shade:false,
        area:['300px','200px'],
        content:'<div id="mydiv" style="margin-left:10px;margin-top:10px;">' +
        '<textarea placeholder="请输入撤回内容" id="txtReason" style="width:280px;height:70px;resize:none;border-radius:6px;border-color:#ccc;" >' +
        '</textarea></div>',
        btn:['确定','取消'],
          yes: function (index, layero){
          var textReason = top.$('#txtReason').val();
          layer.close(index)
          $.ajax({
            url: "/Order/ResetVisitedWorkOrder",
            type: "get",
            async: false,//同步请求
            contentType: "application/json",
            dataType: "text",
            cache: false,
            data: {
              workOrderId: data.F_WORKORDERID,
                reason: textReason
            },
            success: function (thisResult, result) {
            if (thisResult == "True") {
              layer.open({
                content: '提交撤回成功'
                , icon: 1
                , btn: ['确定']
                , yes: function (index, layero) {
                  //执行重载
                  table.reload('recordtable', {
                    page: {
                      curr: 1 //重新从第 1 页开始
                    }
                    , where: {
                      types: 0,
                      dateParty: $("#test10").val()
                      , NowDateTime: new Date()
                      , workorderNum: $("#workorderNum").val()
                      , cusName: $("#cusName").val()
                      , phoneNumber: $("#phoneNumber").val()
                      , userInfo: $("#userInfo").val()
                      , bussType: $("#bussType").val()
                      , detailType: $("#bussDetail").val()
                      , Content: $("#Content").val()
                    }
                  });
                  layer.close(index);
                }
              });
            } else {
                layui.layer.alert("提交撤回失败!", {
                  icon: 2
                });
  
              }
            },
            error: function (error) {
              return false;
            }
          });
        },

      })

    }
  });

  table.reload('recordtable', {
    done: function (res, rurr, count) {
      $(".layui-table-body [data-field='F_USERNAME']").children().each(function (i, n) {

        // var operationHtml ='<a class="layui-btn layui-btn-primary layui-btn-xs btnBj" lay-event="edit">编辑</a>'+
        // '<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="view">查看详情</a';

        if (res.data[i].F_WORKORDERTYPEID === 1 && orderStateM === 2) {

          $(this).html('<a class="layui-btn layui-btn-primary layui-btn-xs btnBj" lay-event="withdrawDeal">撤回</a>' +
            '<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="view">查看详情</a')

        } else if (res.data[i].F_REPAIRREQUEST == "待回访" && orderStateM === 3) {

          $(this).html('<a class="layui-btn layui-btn-primary layui-btn-xs btnBj" lay-event="edit">编辑</a>' +
            '<a class="layui-btn layui-btn-primary layui-btn-xs btnBj" lay-event="overrule">驳回</a>' +
            '<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="view">查看详情</a')

        } else if (res.data[i].F_WORKORDERTYPEID === 1 && res.data[i].F_REPAIRREQUEST == "待定责" && orderStateM === 4) {

          $(this).html('<a class="layui-btn layui-btn-primary layui-btn-xs btnBj" lay-event="withdrawVisit">撤回</a>' +
            '<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="view">查看详情</a')

        } else if (res.data[i].F_REPAIRREQUEST == "待定责" && orderStateM === 5) {

          $(this).html('<a class="layui-btn layui-btn-primary layui-btn-xs btnBj" lay-event="edit">编辑</a>' +
            '<a class="layui-btn layui-btn-primary layui-btn-xs btnBj" lay-event="overruleDZ">驳回</a>' +
            '<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="view">查看详情</a')

        } else {

          $(this).html('<a class="layui-btn layui-btn-primary layui-btn-xs btnBj" lay-event="edit">编辑</a>' +
            '<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="view">查看详情</a')

        }
      })
    }
  })
  function recordtableMethod () {
    //执行重载
    table.reload('recordtable', {
      page: {
        curr: 1 //重新从第 1 页开始
      }
      , where: {
        types: 0,
        dateParty: $("#test10").val()
        , NowDateTime: new Date()
        , workorderNum: $("#workorderNum").val()
        , cusName: $("#cusName").val()
        , phoneNumber: $("#phoneNumber").val()
        , userInfo: $("#userInfo").val()
        , bussType: $("#bussType").val()
        , detailType: $("#bussDetail").val()
        , Content: $("#Content").val()
        , F_RETURNVISITRESULT: $("#FromType").val()
      }
    });
  }

  var $ = layui.$, active = {
    //查询按钮
    reload: function () {

      //执行重载
      table.reload('recordtable', {
        page: {
          curr: 1 //重新从第 1 页开始
        }
        , where: {
          types: 0,
          dateParty: $("#test10").val()
          , NowDateTime: new Date()
          , workorderNum: $("#workorderNum").val()
          , cusName: $("#cusName").val()
          , phoneNumber: $("#phoneNumber").val()
          , userInfo: $("#userInfo").val()
          , bussType: $("#bussType").val()
          , detailType: $("#bussDetail").val()
          , Content: $("#Content").val()
          , F_RETURNVISITRESULT: $("#FromType").val()
        }
      });
    }
    //一周
    , oneWeek: function () {
      var dataParty = getWeekStartDate() + ' - ' + formatDate(now);
      $(".dayParty").val(dataParty);
      //执行重载
      table.reload('recordtable', {
        page: {
          curr: 1 //重新从第 1 页开始
        }
        , where: {
          types: 1
          , NowDateTime: new Date()
          , workorderNum: $("#workorderNum").val()
          , cusName: $("#cusName").val()
          , phoneNumber: $("#phoneNumber").val()
          , userInfo: $("#userInfo").val()
          , bussType: $("#bussType").val()
          , detailType: $("#bussDetail").val()
          , Content: $("#Content").val()
          , F_RETURNVISITRESULT: $("#FromType").val()

        }
      });
    }
    //一月
    , oneMonth: function () {
      var dataParty = getMonthStartDate() + ' - ' + formatDate(now);
      $(".dayParty").val(dataParty);
      //执行重载
      table.reload('recordtable', {
        page: {
          curr: 1 //重新从第 1 页开始
        }
        , where: {
          types: 2
          , NowDateTime: new Date()
          , workorderNum: $("#workorderNum").val()
          , cusName: $("#cusName").val()
          , phoneNumber: $("#phoneNumber").val()
          , userInfo: $("#userInfo").val()
          , bussType: $("#bussType").val()
          , detailType: $("#bussDetail").val()
          , Content: $("#Content").val()
          , F_RETURNVISITRESULT: $("#FromType").val()
        }
      });
    }
    //一年
    , oneYear: function () {
      var dataParty = getYearStartDate() + ' - ' + formatDate(now);
      $(".dayParty").val(dataParty);
      //执行重载
      table.reload('recordtable', {
        page: {
          curr: 1 //重新从第 1 页开始
        }
        , where: {
          types: 3
          , NowDateTime: new Date()
          , workorderNum: $("#workorderNum").val()
          , cusName: $("#cusName").val()
          , phoneNumber: $("#phoneNumber").val()
          , userInfo: $("#userInfo").val()
          , bussType: $("#bussType").val()
          , detailType: $("#bussDetail").val()
          , Content: $("#Content").val()
          , F_RETURNVISITRESULT: $("#FromType").val()
        }
      });
    }
  };

  function saveAs (blob, filename) {
    var type = blob.type;
    var force_saveable_type = 'application/octet-stream';
    if (type && type != force_saveable_type) { // 强制下载，而非在浏览器中打开
      var slice = blob.slice || blob.webkitSlice || blob.mozSlice;
      blob = slice.call(blob, 0, blob.size, force_saveable_type);
    }

    var url = URL.createObjectURL(blob);
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href = url;
    save_link.download = filename;

    var theevent = document.createEvent('MouseEvents');
    theevent.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(theevent);
    URL.revokeObjectURL(url);
  }
  //回车执行
  document.onkeydown = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (e && e.keyCode == 13) {
      //执行重载
      table.reload('recordtable', {
        page: {
          curr: 1 //重新从第 1 页开始
        }
        , where: {
          types: 0,
          dateParty: $("#test10").val()
          , NowDateTime: new Date()
          , workorderNum: $("#workorderNum").val()
          , cusName: $("#cusName").val()
          , phoneNumber: $("#phoneNumber").val()
          , userInfo: $("#userInfo").val()
          , bussType: $("#bussType").val()
          , detailType: $("#bussDetail").val()
          , Content: $("#Content").val()
          , F_RETURNVISITRESULT: $("#FromType").val()
        }
      });
    }
  };


  $('.searchfilter .layui-btn').on('click', function () {
    var type = $(this).data('type');
    active[type] ? active[type].call(this) : '';
  });
  //高级查询折叠
  $('#advanceBtn').on('click', function () {
    $('.collapsible_box').slideToggle(200);
  })
  //导出到excel
  $('#ExToExcel').on('click', function () {
    urlExcel = "/Order/ExToExcelDZ"
    ExToExcel()
  })

  function ExToExcel () {
    var img = $("#progressImgage");
    var mask = $("#maskOfProgressImage");
    var dataModel = {
      dateParty: $("#test10").val()
      , workorderNum: $("#workorderNum").val()
      , cusName: $("#cusName").val()
      , phoneNumber: $("#phoneNumber").val()
      , userInfo: $("#userInfo").val()
      , status: $("#status").val()
      , bussType: $("#bussType").val()
      , detailType: $("#bussDetail").val()
      , Content: $("#Content").val()
      , F_RETURNVISITRESULT: $("#FromType").val()
      , GoType: $("#GoType").val()
      , FromType: $("#FromType").val()
      , F_HASTENCOUNTS: $("#F_HASTENCOUNTS").val()
    }
    var para = JSON.stringify(dataModel);

    $.ajaxLoading({
      url: urlExcel,
      type: "post",
      async: true,
      contentType: "application/json;charset=utf-8",
      dataType: "json",
      cache: false,
      data: para,
      success: function (dataContent, result) {

        if (dataContent.Code == "0") {
          var datajson = dataContent.Data.replace(/&quot;/g, "\"");
          var ItemList = JSON.parse(datajson);
          // alert(ItemList);
          var bytes = window.atob(ItemList);      //转换为byte  
          //处理异常,将ascii码小于0的转换为大于0  
          var ab = new ArrayBuffer(bytes.length);
          var ia = new Uint8Array(ab);
          for (var i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
          }

          var blob = new Blob([ab], { type: 'application/vnd.ms-excel' })
          var fileName = '工单数据.xls';

          if (dataContent.Message != null && dataContent.Message != "") {
            fileName = dataContent.Message;
          }

          //获取浏览器信息
          var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
          var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
          var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
          var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
          if (isIE || isEdge || isIE11) {
            navigator.msSaveBlob(blob, fileName);
          }
          else {
            saveAs(blob, fileName);
          }
        }
        else {
          layer.msg('数据转换失败');
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        layer.msg(textStatus);
        layer.msg(errorThrown);
      }
    });

  }

  //.监听当前 select，动态改变子项
  form.on('select(fcoptype)', function (d) {
    $.ajax({
      url: "/WorkOrder/GetBussType",
      type: "get",
      contentType: "application/json",
      dataType: "text",
      cache: false,
      data: { "bussnessType": d.value },
      success: function (result, status) {
        if (status) {
          $("#bussDetail").empty();
          $("#bussDetail").append("<option value='' ></option>");
          var list = eval("(" + result + ")");
          if (list.length > 0) {
            for (var i = 0; i < list.length; i++) {
              $("#bussDetail").append("<option  value='" + list[i].F_WorkOrderTypeId + "'>" + list[i].F_Name + "</option>");
            }
          }

          form.render('select');
        }
        else {
          layui.layer.alert("获取信息失败!", {
            icon: 2
            , offset: '40%'
          });
        }

      }
    });
  });

});