
var permDelete = $("#perm-delete").val();//删除权限
var permEdit = $("#perm-edit").val();//编辑权限
/**
 * 邮箱配置 
 * 2018/5/3 by liufang
 */
$(function () {
  var tpl = {
    "addTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-email-con">\
					<div class="title-wp">\
						<span>添加短信账号</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-email-wp">\
            <div class="d-email-wrapper-top">\
            <h2 class="title"></h2>\
					<% if(list!=null&&list.length>1){ %>\
							<div class="email-item">\
							<span class="tips">项目</span>\
              <input class="orgId e-item-text" id ="orgId" name="orgId"  placeholder="请选择项目" autocomplete="off" />\
              <span class="select_wrap _hide"></span>\
						</div>\
					<%}else if(list!=null&&list.length==1){%>\
						<input type="hidden" id="orgId" value="<%=list[0].id %>" org__id="<%=list[0].id %>"/>\
					<%}%>\
						<div class="email-item">\
								<span class="tips">短信账号</span>\
								<input type="text" class="e-item-text email-address" placeholder="请输入短信账号" />\
								<input type="text"  style="display: none" />\
							</div>\
							<div class="email-item">\
								<span class="tips">密码</span>\
								<input type="password" style="display: none"/>\
								<input type="password" class="e-item-text email-psd" placeholder="请输入密码"/>\
              </div>\
              <div class="email-item">\
                <span class="tips">短信签名</span>\
                <input type="text" style="display: none"/>\
                <input type="text" class="e-item-text email-sign" placeholder="请输入短信签名"/>\
              </div>\
				    </div>\
						<div class="d-email-btns">\
							<button class="sure-add-btn btn-red">保存</button>\
						</div>\
					</div>\
				</div>\
			</div>	',
    "updateTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-email-con">\
					<div class="title-wp">\
						<span>配置短信账号</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-email-wp">\
            <div class="d-email-wrapper-top">\
            <h2 class="title"></h2>\
				<% if(list!=null&&list.length>1){ %>\
					<div class="email-item">\
					   <span class="tips">选择项目</span>\
             <input class="orgId e-item-text" id ="orgId" name="orgId"  placeholder="请选择项目" autocomplete="off" />\
            `<span class="select_wrap _hide"></span>\
					</div>\
				<% }else if(list!=null&&list.length==1){ %>\
					<input type="hidden" id="orgId" value="<%=data.orgId %>" org__id="<%=data.orgId %>"/>\
				<%}%>\
							<div class="email-item">\
								<span class="tips">短信账号</span>\
								<input type="text" class="e-item-text email-address" placeholder="请输入短信账号" value="<%=data.mobileNum%>" data-createtime="<%=data.createTime%>" data-creator="<%=data.creator%>"/>\
							</div>\
							<div class="email-item">\
								<span class="tips">密码</span>\
								<input type="password" class="e-item-text email-psd" placeholder="请输入密码" value="<%=data.password%>"/>\
              </div>\
              <div class="email-item">\
                <span class="tips">短信签名</span>\
                <input type="text" style="display: none"/>\
                <input type="text" class="e-item-text email-sign" placeholder="请输入短信签名" value="<%=data.signature%>" />\
              </div>\
				     	</div>\
						<div class="d-email-btns">\
							<button class="sure-add-btn btn-red">保存</button>\
						</div>\
					</div>\
				</div>\
      </div>	',

    "otherTpl": '<div class="dialog-wp">\
      <div class="mask"></div>\
      <div class="dialog dialog-email-con">\
        <div class="dialog-email-wp">\
          <div class="d-email-wrapper-top">\
            <h2 class="title others">短信剩余量： <span class="other_number"><%=data.data%></span> 条</h2>\
          </div>\
          <div class="d-email-btns">\
            <button class="close-btn btn-red">确定</button>\
          </div>\
        </div>\
      </div>\
    </div>	',


  };

  var layer;
  var table;
  var Index = 0;
  var wxList;
  layui.use('layer', function () {
    layer = layui.layer;
  });
  var appSend = {
    init: function () {
      this.render();
      this.bindEvent();
      this.getOrgList();
    },
    render: function () {
      this.rendertable();

    },
    bindEvent: function () {
      var _this = this;
      var a = $("#orgList").val();
      //重置
      $(".set-btn").on("click", function () {
        $("#conditionform select").val("0");
      });
      //添加模板
      $(".add-temp-btn").on("click", function () {
        //显示 弹窗
        $("body").append(template.render(tpl.addTpl)({
          list: wxList
        }));
        //关闭弹窗
        $(".close-btn,.cancel-add-btn").on("click", function () {
          $(".dialog-wp").remove();
        });
        //确认添加
        $(".sure-add-btn").on("click", function () {
          _this.ajaxAddTemp();
        })

      })
      // 模糊搜索
      _this.search_fuzzy()

    },
    // 模糊搜索事件
    search_fuzzy: function(){
      $('body').on("input",'.default-select.orgId',function(event){
        var _this = $(this)
        cjqt.search_fuzzy.event_input(_this,'org__id','org__span',$("#contextPath").val(),'/admin/templ/getOrgListByName')
      });
      $('body').on("focus",'.default-select.orgId',function(event){
        var _this = $(this)
        cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',$("#contextPath").val(),'/admin/templ/getOrgListByName')
      });
      $('body').on('blur','.default-select.orgId',function(event) {
        var _this = $(this)
        cjqt.search_fuzzy.event_blur(_this,'org__id')
      });
      $('body').on('click','.default-select.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','.default-select.orgId')
      });

      $('body').on("input",'.e-item-text#orgId',function(event){
        var _this = $(this)
        cjqt.search_fuzzy.event_input(_this,'org__id','org__span',$("#contextPath").val(),'/admin/templ/getOrgListByName')
      });
      $('body').on("focus",'.e-item-text#orgId',function(event){
        var _this = $(this)
        cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',$("#contextPath").val(),'/admin/templ/getOrgListByName')
      });
      $('body').on('blur','.e-item-text#orgId',function(event) {
        var _this = $(this)
        cjqt.search_fuzzy.event_blur(_this,'org__id')
      });
      $('body').on('click','.e-item-text#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','.e-item-text#orgId')
      });
    },
    getOrgList: function () {
      $.ajax({
        type: "post",
        url: $("#contextPath").val() + "/admin/templ/getOrgList",
        success: function (data) {
          if (data.code == '200') {
            wxList = data.data;
          }
        },
        error: function () {}
      });
    },
    rendertable: function () {
      var _this = this;
      layui.use('table', function () {
        table = layui.table;

        //方法级渲染
        table.render({
          elem: '#LAY_table_user',
          url: $("#contextPath").val() + "/admin/templ/getMobileList",
          skin: 'nob' //行边框风格
            ,
          even: true //开启隔行背景
            ,
          size: 'lg' //小尺寸的表格
            ,
          cols: [
            [{
              field: 'createTime',
              title: '序号',
              templet: '#indexTpl',
              width: '10%'
            }, {
              field: 'orgName',
              title: '项目名称',
              width: '20%'
            }, {
              field: 'mobileNum',
              title: '账号名称',
              width: '20%'
            }, {
              field: 'signature',
              title: '短信签名',
              width: '20%'
            }, {
              field: 'id',
              title: '操作',
              width: '30%',
              fixed: 'right',
              templet: function (data) {
                var str = '';
                str += '<button class="t-btn t-red-btn t-other-btn" data-id=' + data.id + ' >查询剩余量</button>';
                if (permEdit == 1){
                    str += '<button class="t-btn t-red-btn t-edit-btn" data-id=' + data.id + ' >配置</button>';
                }
                if (permDelete == 1){
                    str += '<button class="t-btn t-white-btn t-del-btn" data-id=' + data.id + ' >删除</button>';
                }
                return str;
              }
            }]
          ],
          id: 'testReload',
          page: true,
          method: 'post',
          where: {
            orgId: $(".orgId").attr('org__id')
          },
          response: {
            statusName: 'code' //数据状态的字段名称，默认：code
              ,
            statusCode: 200 //成功的状态码，默认：0
              ,
            countName: "count" //数据总数的字段名称，默认：count
              ,
            dataName: "data" //数据列表的字段名称，默认：data
          },
          done: function (res, curr, count) {
            //如果是异步请求数据方式，res即为你接口返回的信息。
            console.log(res, 'aaaaaa');
            if (res.userType == 1 || res.userType == 2) {
              $(".add-temp-btn").css("display", "block");
            } else {
              if (res.data.length > 0) {
                $(".add-temp-btn").css("display", "none");
              } else {
                $(".add-temp-btn").css("display", "block");
              }
            }
            //删除
            $(".t-del-btn").on("click", function () {
              var id = $(this).data("id");
              _this.ajaxDelTemp(id, function () {
                Index = 0;
                table.reload('testReload', {
                  page: {
                    curr: 1 //重新从第 1 页开始
                  }
                });
              })
            });
            //编辑
            $(".t-edit-btn").on("click", function () {
              var id = $(this).data("id")
              console.log(id);
              //显示详情弹窗
              _this.showEditDialog(id, function (data) {
                console.log(data);
                //显示 弹窗
                $("body").append(template.render(tpl.updateTpl)({
                  list: wxList,
                  data: data
                }));
                //关闭弹窗
                $(".close-btn,.cancel-add-btn").on("click", function () {
                  $(".dialog-wp").remove();
                });
                //保存
                $(".sure-add-btn").on("click", function () {
                  _this.ajaxAddTemp(id, function () {
                    Index = 0;
                    table.reload('testReload', {
                      page: {
                        curr: 1 //重新从第 1 页开始
                      }
                    });
                  })
                })
              })
            });
            // 查询剩余量
            $(".t-other-btn").on("click", function () {
              var id = $(this).data("id")
              //显示剩余量弹窗
              _this.ajaxSearchOthers(id, function (data) {
                console.log(data, 88888888);
                //显示 弹窗
                $("body").append(template.render(tpl.otherTpl)({
                  list: wxList,
                  data: data
                }));
                //关闭弹窗
                $(".close-btn,.cancel-add-btn").on("click", function () {
                  $(".dialog-wp").remove();
                });
              })
            });
          }
        });
        //查询
        $('#conditionform  .search-btn').on('click', function () {
          Index = 0;
          table.reload('testReload', {
            where: { //设定异步数据接口的额外参数，任意设
              orgId: $(".orgId").attr('org__id')
            },
            page: {
              curr: 1 //重新从第 1 页开始
            }
          });
        });
      });
    },
    /**
     * 删除模板
     * @param id 模板id
     * @param callback
     */
    ajaxDelTemp: function (id, callback) {
      layer.confirm('确定删除?', {
        btn: ['确定', '取消']
      }, function (index, layero) {
        layer.close(index); //如果设定了yes回调，需进行手工关闭
        $.ajax({
          type: "post",
          url: $("#contextPath").val() + "/admin/templ/deleteMobileConfig",
          data: {
            "mobileId": id
          },
          success: function (data) {
            var data = JSON.parse(data);
            if (data.code == 200) {
              callback();
            }
          },
          error: function () {}
        });
      }, function (index) {

      });
    },
    /**
     * 添加模板
     * @param id
     * @param callback
     */
    ajaxAddTemp: function (id, callback) {
      //短信账号
      var mobileNum = $(".email-address").val();
      if (!mobileNum) {
        layer.alert("请输入短信账号");
        return false;
      };
      //密码
      var password = $(".email-psd").val();
      if (!password) {
        layer.alert("请输入密码");
        return false;
      };
      // 短信签名
      var signature = $(".email-sign").val();
      if (!signature) {
        layer.alert("请输入短信签名");
        return false;
      };
      var orgId = $(".dialog-wp #orgId").attr('org__id');
      $.ajax({
        type: "post",
        url: $("#contextPath").val() + "/admin/templ/saveAndUpdateMobileConfig",
        data: {
          "id": id,
          "mobileNum": mobileNum,
          "password": password,
          "signature": signature,
          "orgId": orgId
        },
        success: function (data) {
          var data = JSON.parse(data);
          if (data.code == 200) {
            $(".dialog-wp").remove();
            Index = 0;
            table.reload('testReload', {
              page: {
                curr: 1 //重新从第 1 页开始
              }
            });
          }
        },
        error: function () {}
      });
    },
    /**
     * 编辑模板
     * @param id
     * @param callback
     */
    showEditDialog: function (id, callback) {
      var _this = this;
      $.ajax({
        type: "post",
        url: $("#contextPath").val() + "/admin/templ/getMobileDetail",
        data: {
          "mobileId": id
        },
        success: function (data) {
          if (data.code == "200") {
            callback(data.data);
          }
        },
        error: function () {}
      });
    },
    /**
     * 查询剩余量
     * @param id
     * @param callback
     */
    ajaxSearchOthers: function (id, callback) {
      var _this = this;
      $.ajax({
        type: "post",
        url: $("#contextPath").val() + "/admin/templ/getMobileResidueCount",
        data: {
          "mobileId": id
        },
        success: function (data) {
          // console.log(data,888888888888);
          if (data.code == "200") {
            callback(data);
          }
        },
        error: function () {}
      });
    }
  };
  appSend.init();
})