/**
 * app公告发布 发送历史
 * 2018/4/20 by liufang
 */

var userType = '';
var companyArr = []; // 运营中心列表
var companyId = '';
var orgArr = []; // 项目列表

$(function () {

  var tpl = {
    "auditTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-audit-con">\
					<div class="title-wp">\
						<%if(status==24){%>\
							<span>审核</span>\
						<%}%>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-audit-wp">\
						<div class="audit-con">\
							<div class="audit-top">\
								<div class="audit-top-left">\
									<span class="icon"></span>\
									<span class="code">空调单号:<%=code%></span>\
								</div>\
								<div class="audit-top-right">\
									待审核\
								</div>\
							</div>\
							<div class="audit-list">\
								<div class="audit-item">\
									<div class="item-tip">公司名称:</div>\
									<div class="item-con"><%=virtualName%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">企业账号:</div>\
									<div class="item-con"><%=virAccountNo%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">申请时间:</div>\
									<div class="item-con"><%=applyTime%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">申请人:</div>\
									<div class="item-con"><%=applyUser%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">联系电话:</div>\
									<div class="item-con"><%=applyTel%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">申请位置:</div>\
									<div class="item-con"><%=roomNames%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">申请面积:</div>\
									<div class="item-con"><%=applyArea%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">使用时间:</div>\
									<div class="item-con"><%=useDisplayTime%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">使用时长:</div>\
									<div class="item-con"><%=useLengthTime%>小时</div>\
								</div>\
							</div>\
							<div class="audit-list audit-list-right">\
								<div class="audit-item">\
									<div class="item-tip">单价:</div>\
									<div class="item-con"><%=priceDisplay%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">费用明细:</div>\
									<div class="item-con"><%=freeDetail%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">费用总结:</div>\
									<div class="item-con"><%=freeTotal%>元</div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">月结费用:</div>\
									<div class="item-con"><%=monthlyFree%>元</div>\
								</div>\
							</div>\
							<% if(operateDto.length>0){%>\
								<% for(var i=0;i<operateDto.length;i++){%>\
                                    <div class="audit-list audit-list-long">\
										<div class="audit-item">\
											<div class="item-tip">审核时间:</div>\
											<div class="item-con"><%=operateDto[i].auditTime%></div>\
										</div>\
										<div class="audit-item">\
											<div class="item-tip">审核人:</div>\
											<div class="item-con"><%=operateDto[i].auditUser%></div>\
										</div>\
										<div class="audit-item">\
											<div class="item-tip">审核结果:</div>\
											<div class="item-con red"><%=operateDto[i].auditResult%></div>\
										</div>\
										<div class="audit-item">\
											<div class="item-tip">审核意见:</div>\
											<div class="item-con"><%=operateDto[i].remark%></div>\
										</div>\
									</div>\
								<%}%>\
							<%}%>\
							<div class="audit-reason-wp">\
								<span>审核结果：</span>\
								<div class="radio-wp">\
								   <span class="radio-input">\
									 <input type="radio" id="pass" class="radio-item audit-pass" data-status="1" name="result" />\
									  <span class="radio-inner"></span>\
								   </span>		\
								   <label class="radio-con" for="pass">通过</label>\
								</div>\
								<div class="radio-wp">\
								   <span class="radio-input">\
									 <input type="radio" id="no_pass" class="radio-item audit-no-pass" data-status="0" name="result"/>\
									  <span class="radio-inner"></span>\
								   </span>		\
								   <label class="radio-con" for="no_pass">不通过</label>\
								</div>\
							</div>\
							<% if(status==24){%>\
								<div  class="audit-person-wp">\
									<div class="person-title">指定开关空调人员：</div>\
									<div class="person-list">\
										<% for(var k=0;k<persons.length;k++){%>\
											<div class="radio-wp" >\
											   <span class="radio-input">\
												 <input type="radio" id="person_<%=k%>" class="radio-item audit-person" data-id="<%=persons[k].switchUserId%>" name="person" />\
												  <span class="radio-inner"></span>\
											   </span>		\
											   <label class="radio-con" for="person_<%=k%>"><%=persons[k].name%></label>\
											</div>\
										<%}%>\
									</div>\
								</div>\
							<%}%>\
							<div class="audit-suggest">\
								<div class="suggest-title">审核意见:</div>\
								<textarea class="suggest-text" placeholder="请输入审核意见"></textarea>\
							</div>\
						</div>\
						<div class="dialog-btm">\
							<button class="cancel-add-btn btn-white">取消</button>\
							<button class="sure-add-btn btn-red">保存</button>\
						</div>\
					</div>\
				</div>\
			</div>	',
    "detailTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-audit-con">\
					<div class="title-wp">\
						<span>空调加时详情</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-audit-wp">\
						<div class="audit-con">\
							<div class="audit-top">\
								<div class="audit-top-left">\
									<span class="icon"></span>\
									<span class="code">空调单号:<%=code%></span>\
								</div>\
								<div class="audit-top-right">\
									<%if(status==24){%>\
										待审核\
									<%}else if(status==31){%>\
										待使用\
									<%}else if(status==32){%>\
										已使用\
									<%}else if(status==33){%>\
										已取消\
									<%}else if(status==34){%>\
										已拒绝\
									<%}else if(status==35){%>\
										无效\
									<%}%>\
								</div>\
							</div>\
							<div class="audit-list">\
								<div class="audit-item">\
									<div class="item-tip">公司名称:</div>\
									<div class="item-con"><%=virtualName%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">企业账号:</div>\
									<div class="item-con"><%=virAccountNo%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">订单来源:</div>\
									<div class="item-con">\
										<%if(billSource==1){%>\
											空调加时\
										<%}else if(billSource==2){%>\
											预定会议室\
										<%}%>\
									</div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">申请时间:</div>\
									<div class="item-con"><%=applyTime%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">申请人:</div>\
									<div class="item-con"><%=applyUser%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">联系电话:</div>\
									<div class="item-con"><%=applyTel%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">申请位置:</div>\
									<div class="item-con"><%=roomNames%></div>\
								</div>\
								<% if(!!preBookUser){%>\
									<div class="audit-item">\
										<div class="item-tip">代订人:</div>\
										<div class="item-con"><%=preBookUser%></div>\
									</div>\
								<%}%>\
								<div class="audit-item">\
									<div class="item-tip">申请面积:</div>\
									<div class="item-con"><%=applyArea%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">使用时间:</div>\
									<div class="item-con"><%=useDisplayTime%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">使用时长:</div>\
									<div class="item-con"><%=useLengthTime%>小时</div>\
								</div>\
							</div>\
							<div class="audit-list audit-list-right">\
								<div class="audit-item">\
									<div class="item-tip">单价:</div>\
									<div class="item-con"><%=priceDisplay%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">费用明细:</div>\
									<div class="item-con"><%=freeDetail%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">费用总结:</div>\
									<div class="item-con"><%=freeTotal%>元</div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">月结费用:</div>\
									<div class="item-con"><%=monthlyFree%>元</div>\
								</div>\
							</div>\
							<% if(operateDto.length>0){%>\
								<% for(var i=0;i<operateDto.length;i++){%>\
									<div class="audit-list audit-list-long">\
										<div class="audit-item">\
											<div class="item-tip">审核时间:</div>\
											<div class="item-con"><%=operateDto[i].auditTime%></div>\
										</div>\
										<div class="audit-item">\
											<div class="item-tip">审核人:</div>\
											<div class="item-con"><%=operateDto[i].auditUser%></div>\
										</div>\
										<div class="audit-item">\
											<div class="item-tip">审核结果:</div>\
											<div class="item-con red"><%=operateDto[i].auditResult%></div>\
										</div>\
										<div class="audit-item">\
											<div class="item-tip">审核意见:</div>\
											<div class="item-con"><%=operateDto[i].remark%></div>\
										</div>\
									</div>\
								<%}%>\
							<%}%>\
							<div class="audit-list audit-list-long">\
								<div class="audit-item">\
									<div class="item-tip">开关负责人:</div>\
									<div class="item-con"><%=switchUser%></div>\
								</div>\
								<div class="audit-item">\
									<div class="item-tip">联系电话:</div>\
									<div class="item-con"><%=switchTel%></div>\
								</div>\
							</div>\
							<%if(status==33 || status==35 ){%>\
								<div class="audit-list audit-list-long">\
									<div class="audit-item">\
										<div class="item-tip">取消时间:</div>\
										<div class="item-con"><%=cancelTime%></div>\
									</div>\
									<div class="audit-item">\
										<div class="item-tip">取消操作人:</div>\
										<div class="item-con"><%=cancelUser%></div>\
									</div>\
									<div class="audit-item">\
										<div class="item-tip">取消原因:</div>\
										<div class="item-con"><%=cancelReason%></div>\
									</div>\
								</div>\
				  			<%}%>\
						</div>\
					</div>\
				</div>\
			</div>	',
    "cancelTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-cancel-con">\
					<div class="title-wp">\
						<span>空调加时取消</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-audit-wp">\
						<div class="cancel-con">\
							<div class="audit-suggest">\
								<div class="suggest-title">取消原因:</div>\
								<textarea class="suggest-text cancel-reason" placeholder="请输入取消原因"></textarea>\
							</div>\
						</div>\
						<div class="dialog-btm">\
							<button class="cancel-cel-btn btn-white">取消</button>\
							<button class="sure-cel-btn btn-red">保存</button>\
						</div>\
					</div>\
				</div>\
			</div>	'
  }
  template.config("escape", false);
  var contextPath = $("#contextPath").val();
  var table;
  var appSend = {
    init: function () {
      userType = $("#userType").val();
      this.render();
      this.bindEvent();
    },
    render: function () {
      this.rendertable();
    },
    bindEvent: function () {
      var _this = this;
      layui.use('laydate', function () {
        var laydate = layui.laydate;

        //执行一个laydate实例
        laydate.render({
          elem: '#startTime' //提交开始时间

        });
        laydate.render({
          elem: '#endTime' //提交结束时间
        });

        //执行一个laydate实例
        laydate.render({
          elem: '#useStartTime' //提交开始时间

        });
        laydate.render({
          elem: '#useEndTime' //提交结束时间
        });

      });
      //重置
      $(".set-btn").on("click", function () {
        $("#conditionform select").val("");
        $("#conditionform .companyName").val("");
        $("#conditionform .code").val("");
        $("#conditionform #startTime").val("");
        $("#conditionform #endTime").val("");
        $("#conditionform #useStartTime").val("");
        $("#conditionform #useEndTime").val("");

        let contextPath = window.location.hostname === 'localhost' ? '//wx.palmnest.com/super_cloud' : "/super_cloud"
        if (userType == 1 || userType == 2|| userType == 6) {
          $('#comdId').val(companyArr[0].label).attr('comd__id', companyArr[0].value).attr('meetCode', companyArr[0].meetCode);
          companyId = $("#conditionform #comdId").attr('comd__id');
          _this.setOrgData(contextPath);
        } else {
          companyId = localStorage.getItem("companyId")
          _this.setOrgData(contextPath);
        }
      })

      let contextPath = window.location.hostname === 'localhost' ? '//wx.palmnest.com/super_cloud' : "/super_cloud"
      if (userType == 1 || userType == 2|| userType == 6) {
        _this.getCompanyList({}, contextPath)
        $('body').on("focus", '#comdId', function (event) {
          _this.setOrgCompanyData($('#comdId'), 'comd__id', 'comd__span' , companyArr);
        });
        $('body').on('blur', '#comdId', function (event) {
          var _that = $(this)
          cjqt.search_fuzzy.event_blur(_that, 'comd__id')
        });
        $('body').on('click', '.select_wrap>.comd__span', function (event) {
          event.preventDefault();
          event.stopPropagation();
          /* Act on the event */
          var _that = $(this)
          cjqt.search_fuzzy.event_click(_that, 'comd__id', '#comdId')
          companyId = $("#conditionform #comdId").attr('comd__id')
          _this.setOrgData(contextPath);
        });
        $('body').on("input",'#comdId',function(event){ // input内容变化执行
          _this.setFuzzyFilter($('#comdId').val(), companyArr, backData => {
            _this.setOrgCompanyData($('#comdId'), 'comd__id', 'comd__span' , backData);
          })
        });
      } else {
        companyId = localStorage.getItem("companyId")
        _this.setOrgData(contextPath);
      }

    },
    setOrgData: function(contextPath) {
      var _this = this;
      _this.getOrgList({
        pageNo: 1,
        pageSize: 9999,
        "conditions[companyId]": companyId
      }, contextPath)
      $('body').on("focus", '#orgId', function (event) {
        _this.setOrgCompanyData($('#orgId'), 'org__id', 'org__span' , orgArr);
      });
      $('body').on('blur', '#orgId', function (event) {
        var _that = $(this)
        cjqt.search_fuzzy.event_blur(_that, 'org__id')
      });
      $('body').on('click', '.select_wrap>.org__span', function (event) {
        event.preventDefault();
        event.stopPropagation();
        /* Act on the event */
        var _that = $(this)
        cjqt.search_fuzzy.event_click(_that, 'org__id', '#orgId')
      });
      $('body').on("input",'#orgId',function(event){
        _this.setFuzzyFilter($('#orgId').val(), orgArr, backData => {
          _this.setOrgCompanyData($('#orgId'), 'org__id', 'org__span' , backData);
        })
      });
    },
    // 获取运营中心数据
    getCompanyList: function (obj, contextPath) {
      var _this = this;
      companyArr = [];
      $.ajax({
        url: contextPath + '/api/organisation/company/getselectlist',
        type: "POST",
        dataType: "json",
        data: obj,
        success: function (data) {
          if (data.code == 200 && data.data) {
            companyArr = data.data;
            _this.setInputData($('#comdId'), 'comd__id', 'comd__span' , companyArr);
            companyId = $("#conditionform #comdId").attr('comd__id')
            _this.setOrgData(contextPath);
          } else {
            layer.msg(data.msg);
          }
        }
      });
    },
    // 获取项目数据
    getOrgList(obj, contextPath) {
      var _this = this;
      orgArr = [];
      $.ajax({
        url: contextPath + '/api/organisation/organization/getselectlist',
        type: "POST",
        dataType: "json",
        data: obj,
        success: function (data) {
          if (data.code == 200 && data.data) {
            orgArr = data.data;
            _this.setInputData($('#orgId'), 'org__id', 'org__span', orgArr);
          } else {
            layer.msg(data.msg);
          }
        }
      });
    },
    setInputData: function(_this, attrName, liClassName, dataArr) {
      // 先清空
      _this.attr(attrName, '')
      var html = ''
      if (dataArr.length) {
        _this.val(dataArr[0].label).attr(attrName, dataArr[0].value).attr('meetCode', dataArr[0].meetCode);
        if (attrName == 'org__id') {
          $('#conditionform  .search-btn').click();
        }
        $.each(dataArr, function (index, el) {
          var meetCode = el.meetCode || ''
          html += '<span class="' + liClassName + '" id="' + el.value + '" meetCode="' + meetCode + '">'
          html += el.label
          html += '</span>'
        });
        _this.parent().find('.select_wrap').empty().append(html);
      } else {
        _this.val('').attr(attrName, '').attr('meetCode', '');
        _this.parent().find('.select_wrap').empty().hide()
      }
    },
    setOrgCompanyData: function(_this, attrName, liClassName, dataArr) {
      var html = ''
      if (dataArr.length) {
        _this.parent().find('.select_wrap').show()
        $.each(dataArr, function (index, el) {
          var meetCode = el.meetCode || ''
          html += '<span class="' + liClassName + '" id="' + el.value + '" meetCode="' + meetCode + '">'
          html += el.label
          html += '</span>'
        });
        _this.parent().find('.select_wrap').empty().append(html)
      } else {
        _this.parent().find('.select_wrap').empty().hide()
      }
    },
    setFuzzyFilter: function (strLabel, dataArr, backData) {
      const fuzzyArr = dataArr; // 内容省略
      const objArr = [];
      fuzzyArr.forEach(item => {
        if (item.label.includes(strLabel)) {
          objArr.push(item);
        }
      });
      backData(objArr);
    },
    rendertable: function () {
      var _this = this;
      layui.use('table', function () {
        table = layui.table;

        //方法级渲染
        table.render({
          elem: '#LAY_table_user'
          , skin: 'nob' //行边框风格
          , even: true //开启隔行背景
          , size: 'lg' //小尺寸的表格
          , cols: [[
            {
//				    		   field:'billId',
//				    		   title: 'ID',
//				    		   minWidth:80
//				    	  },{
              field: 'code',
              title: '订单号',
              minWidth: 200
            }, {
              field: 'virtualName',
              title: '企业名称',
              minWidth: 200
//		    			  },{
//		    				  field:'fullName',
//		    				  title: '企业账号',
//		    				  width:120
            }, {
              field: 'roomNames',
              title: '房间号',
              minWidth: 200
            }, {
              field: 'applyArea',
              title: '面积',
              minWidth: 140
            }, {
              field: 'useDisplayTime',
              title: '使用时间',
              minWidth: 250
            }, {
              field: 'useLengthTime',
              title: '使用时长（小时）',
              minWidth: 180
            }, {
              field: 'priceDisplay',
              title: '单价',
              minWidth: 200
            }, {
              field: 'freeTotal',
              title: '总价（元）',
              minWidth: 120
            }, {
              field: 'applyUser',
              title: '申请人',
              minWidth: 120
            }, {
              field: 'applyTime',
              title: '申请时间',
              minWidth: 200
            }, {
              field: 'billSource',
              title: '订单来源',
              minWidth: 200,
              templet: function (data) {
                if (data.billSource == 1) {
                  return "空调加时"
                } else if (data.billSource == 2) {
                  return '预定会议室'
                }
              }
            }, {
              field: 'billStatus',
              title: '状态',
              minWidth: 200,
              templet: function (data) {
                //\待客服专员审核21\待客服主管审核22\待工程主管审核23\待使用31\已使用32\已取消33\已拒绝34\无效35
                if (data.billStatus == 21) {
                  return "待审核（客服专员）"
                } else if (data.billStatus == 22) {
                  return "待审核（客服主管）"
                } else if (data.billStatus == 23) {
                  return "待审核（工程主管）"
                } else if (data.billStatus == 24) {
                  return "待审核"
                } else if (data.billStatus == 31) {
                  return "待使用"
                } else if (data.billStatus == 32) {
                  return "已使用"
                } else if (data.billStatus == 33) {
                  return "已取消"
                } else if (data.billStatus == 34) {
                  return "已拒绝"
                } else if (data.billStatus == 35) {
                  return "无效"
                } else {
                  return ''
                }
              }
            }, {
              field: 'auditRoleName',
              title: '待审核角色',
              minWidth: 200
            },
            //   {
            //   field:'approval_user',
            //   title: '查看详情',
            //   minWidth:120,
            //   templet: function(data){
            // 		 return "<span data-id="+data.billId+" class='check-blue-btn check-detail'>详情<span>"
            //   }
            // },
            {
              field: 'id',
              title: '操作',
              fixed: "right",
              minWidth: 150,
              templet: function (data) {
                var str = "<span data-id=" + data.billId + " class='check-blue-btn check-detail'>详情</span>";
                if (data.billStatus == 24) {
                  str += "<span data-id=" + data.billId + " data-status=" + data.billStatus + " class='check-audit-btn audit-btn'>审核</span>"
                }
                if (data.billStatus == 31||data.billStatus == 32) {
                  str += '<perm:hasPermission permCode="pc:airOvertime:cancel">'
                  str += "<span data-id=" + data.billId + " data-status=" + data.billStatus + " class='red cancel-btn'>取消</span>"
                  str += '</perm:hasPermission>'
                }
                return str;
              }
            }
          ]]
          , id: 'testReload'
          , page: true,
          method: 'post',
          response: {
            statusName: 'code' //数据状态的字段名称，默认：code
            , statusCode: 200 //成功的状态码，默认：0
            , countName: "count"//数据总数的字段名称，默认：count
            , dataName: "data" //数据列表的字段名称，默认：data
          },
          request: {
            pageName: 'pageNo' //页码的参数名称，默认：page
            , limitName: 'pageSize' //每页数据量的参数名，默认：limit
          },
          done: function (res, curr, count) {
            //如果是异步请求数据方式，res即为你接口返回的信息。
            //审核
            $(".audit-btn").on("click", function () {
              var id = $(this).data("id");
              var status = $(this).data("status")
              //显示审核弹窗
              _this.showAuditDialog(id, status, true)
            });
            //详情
            $(".check-detail").on("click", function () {
              var id = $(this).data("id");

              //显示详情弹窗
              _this.showDetailDialog(id)
            });
            //取消
            $(".cancel-btn").on("click", function () {
              var id = $(this).data("id");
              var status = $(this).data("status")
              //显示取消弹窗
              _this.showCancelDialog(id, status)
            })
          }
        });
        //查询
        $('#conditionform  .search-btn').on('click', function () {
          var org_Id = $("#conditionform #orgId").attr('org__id');
          if (!org_Id&&userType!=1&&userType!=2) {
            layer.msg('请选择项目')
            return;
          }
          _this.againRenderTable();
        });
      });
    },
    /*重新渲染table*/
    againRenderTable: function () {
      table.reload('testReload', {
        url: contextPath + "/air/list",
        where: {
          orgId: $("#conditionform #orgId").attr('org__id'),
          code: $("#conditionform .code").val(),
          companyName: $("#conditionform .companyName").val(),
          endTime: $("#conditionform #endTime").val(),
          startTime: $("#conditionform #startTime").val(),
          useStartTime: $("#conditionform #useStartTime").val(),
          useEndTime: $("#conditionform #useEndTime").val(),
          status: $("#conditionform .status").val(),
        },
        page: {
          curr: 1 //重新从第 1 页开始
        }
      });
    },
    /**
     * 显示审核弹窗
     * @param id 单id
     * @param status 单状态  //\待客服专员审核21\待客服主管审核22\待工程主管审核23\待使用31\已使用32\已取消33\已拒绝34\无效35
     * @param isAir 是否可添加开关人员
     */
    showAuditDialog: function (id, status, isAir) {
      var _this = this;
      _this.ajaxDetail(id, function (data) {
        if (isAir) {
          _this.ajaxPersons(function (persons) {
            data.persons = persons;
            $("body").append(template.render(tpl.auditTpl)(data));
            // 空调加时审批 同意或不同意申请
            $(".dialog-wp .sure-add-btn").on("click", function () {
              var $this = $(this);
              $this.attr("disabled", true);
              _this.auditAjax(id, status, function () {
                _this.againRenderTable();
                $this.attr("disabled", false);
                $(".dialog-wp").remove();
              });
            });

            //关闭弹窗
            $(".close-btn,.dialog-wp .cancel-add-btn ").on("click", function () {
              $(".dialog-wp").remove();
            });
            //审核意见
            $(".audit-reason-wp .radio-wp").on("click", function () {
              var auditResult = $(".radio-wp .radio-item[name='result']:checked").data("status");
              if (auditResult == 1) {
                $(".suggest-text").val("同意")
              } else {
                $(".suggest-text").val("")
              }
              ;
            })
          });
        } else {
          $("body").append(template.render(tpl.auditTpl)(data));
          //关闭弹窗
          $(".close-btn,.dialog-wp .cancel-add-btn ").on("click", function () {
            $(".dialog-wp").remove();
          });
          // 空调加时审批 同意或不同意申请
          $(".dialog-wp .sure-add-btn").on("click", function () {
            var $this = $(this);
            $this.attr("disabled", true);
            _this.auditAjax(id, status, function () {
              _this.againRenderTable();
              $this.attr("disabled", false);
              $(".dialog-wp").remove();
            });
          })
          //审核意见
          $(".audit-reason-wp .radio-wp").on("click", function () {
            var auditResult = $(".radio-wp .radio-item[name='result']:checked").data("status");
            if (auditResult == 1) {
              $(".suggest-text").val("同意")
            } else {
              $(".suggest-text").val("")
            }
            ;
          })
        }


      })
    },
    /**
     * 显示详情弹窗
     * @param id
     */
    showDetailDialog: function (id) {
      var _this = this;
      _this.ajaxDetail(id, function (data) {

        $("body").append(template.render(tpl.detailTpl)(data));
        //关闭弹窗
        $(".close-btn").on("click", function () {
          $(".dialog-wp").remove();
        })
      })

    },
    ajaxDetail: function (id, callback) {
      var _this = this;
      $.ajax({
        type: "post",
        url: contextPath + "/air/getDetail",
        data: {
          "id": id
        },
        success: function (data) {
          if (data.code == 200) {
            callback(data.data);
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    /**
     * 获取空调加时指定开关空调人员
     *
     */
    ajaxPersons: function (callback) {
      var _this = this;
      $.ajax({
        type: "post",
        url: contextPath + "/air/getAirSwitchUser",
        success: function (data) {
          if (data.code == 200) {
            callback(data.data);
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    /**
     * 空调加时审批 同意或不同意申请
     * @param id
     * @param status 状态 //\待客服专员审核21\待客服主管审核22\待工程主管审核23\待使用31\已使用32\已取消33\已拒绝34\无效35
     * @param callback 刷新列表回调
     */
    auditAjax: function (id, status, callback) {
      var _this = this;
      var result = {
        billId: id,//单据ID
        currentBillStatus: status,//当前单据状态 防止重复提交
        auditResult: '',
        auditOpinion: '',
        switchUserId: ''
      }
      //审核结果 0不同意 1 同意
      var auditResult = $(".radio-wp .radio-item[name='result']:checked").data("status");
      if (auditResult != 1 && auditResult != 0) {
        layer.msg('请勾选审核结果！');
        return false;
      }
      ;
      result['auditResult'] = auditResult;
      //空调开关人员ID
      var switchUserId = $(".radio-wp .radio-item[name='person']:checked").data("id");
      if (status == 24) {
        if (!switchUserId) {
          layer.msg('请选择空调开关人员！');
          return false;
        }
      }
      result['switchUserId'] = !!switchUserId ? switchUserId : '';
      //审核意见
      var auditOpinion = $(".suggest-text").val();
      if (!auditOpinion) {
        layer.msg('请输入审核意见！');
        return false;
      }
      ;
      result['auditOpinion'] = auditOpinion;

      $.ajax({
        type: "post",
        url: contextPath + "/air/audit",
        data: result,
        success: function (data) {
          if (data.code == 200) {
            callback();
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    /**
     * 空调加时取消
     * @param id
     * @param status 状态 //\待客服专员审核21\待客服主管审核22\待工程主管审核23\待使用31\已使用32\已取消33\已拒绝34\无效35
     */
    showCancelDialog: function (id, status) {
      var _this = this;
      $("body").append(template.render(tpl.cancelTpl));
      //关闭弹窗
      $(".close-btn ,.dialog-wp .cancel-cel-btn").on("click", function () {
        $(".dialog-wp").remove();
      });
      // 确定取消
      $(".dialog-wp .sure-cel-btn").on("click", function () {
        var $this = $(this);
        var cancelReason = $(".cancel-reason").val();
        if (cancelReason) {
          $this.attr("disabled", true)
        }
        _this.cancelAjax(id, status, function (isYN) {
          _this.againRenderTable();
          $this.attr("disabled", false)
          $(".dialog-wp").remove();
        });
      })

    },
    /**
     * 空调加时取消
     * @param id
     * @param status 状态 //\待客服专员审核21\待客服主管审核22\待工程主管审核23\待使用31\已使用32\已取消33\已拒绝34\无效35
     * @param callback 刷新列表回调
     */
    cancelAjax: function (id, status, callback) {
      var _this = this;
      var result = {
        billId: id,//单据ID
        currentBillStatus: status,//当前单据状态 防止重复提交
        cancelReason: ''
      }
      //取消原因
      var cancelReason = $(".cancel-reason").val();
      if (!cancelReason) {
        layer.msg('请输入取消原因！');
        return false;
      }
      ;
      result['cancelReason'] = cancelReason;

      $.ajax({
        type: "post",
        url: contextPath + "/air/cancel",
        data: result,
        success: function (data) {
          if (data.code == 200) {
            callback(true);
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    }
  };
  appSend.init();
})
