// 设备列表
$(function () {
  var ERROK = 200;
  var contextPath = $("#contextPath").val()
  var table;
  template.config("escape", false);
  var orgId = $("#orgId").val();
  var tpl = {
    "modifyTpl": '<div class="dialog-wp">\
    <div class="mask"></div>\
    <div class="dialog dialog-account-con modify">\
      <div class="title-wp">\
        <span>编辑常用选项</span>\
        <span class="close-btn"></button>\
      </div>\
      <div class="dialog-account-wp ">\
         <div class="account-list">\
          <div class="account-item required clearfloat">\
            <div class="item-tip"><span class="red">*</span>名称：</div>\
            <div class="item-con">\
              <div class="layui-input-inline">\
                <input class="default-select apart-id layui-input" name="companyId" id="companyId" autocomplete="off" value="<%=groupName%>" disabled/>\
              </div>\
            </div>\
          </div>\
          <div class="account-item required clearfloat">\
            <div class="item-tip">所属功能：</div>\
            <div class="item-con">\
              <div class="layui-input-inline">\
                <input class="default-select apart-id layui-input" name="apartId" id="apartId" autocomplete="off" value="<%=funcName%>"/>\
              </div>\
            </div>\
          </div>\
          <div class="account-item required clearfloat">\
            <div class="item-tip">常用选项：</div>\
            <div class="item-con use-option">\
              <ul class="useList">\
                <li class="title"><span class="sort-use">排序</span><span>常用选项</span></li>\
                <%if(setting){%>\
                  <% for(var i=0;i<setting.length;i++){%>\
                    <li class="lis" data-id="<%=setting[i].id%>">\
                      <div class="sort-use">\
                        <input class="sort" type="text" value="<%=(i+1)%>"/>\
                      </div>\
                      <div class="con-use">\
                        <input class="item-name" type="text" value="<%=setting[i].itemname%>"/>\
                      </div>\
                      <div class="del-use">\
                        <span class="del-use-btn"></span>\
                      </div>\
                    </li>\
                  <%}%>\
                <%}%>\
              </ul>\
              <div class="add-ele-again">+继续添加</div>\
            </div>\
          </div>\
          <div class="dialog-btns">\
            <button class="sure-add-btn btn-red">确定</button>\
          </div>\
         </div>\
      </div>\
    </div>\
  </div>',

  };
  var api = {
    init: function () {
      this.render();
      this.bindEvent();
    },
    render: function () {
      this.rendertable();
      this.ajaxUpdate();
    },
    bindEvent: function () {
      var _this = this;
      //重置
      $(".set-btn").on("click", function () {
        $("#conditionform input,#conditionform select").val("");
        _this.againRenderTable();
      });
      // 模糊搜索
      _this.search_vague(1); //校区
    },
    // 模糊搜索校区
    search_vague: function (type) {
      var $elem;
      type == 1 ? $elem = $('body #conditionform') : $elem = $('body .dialog-wp');
      $elem.on("input", '#orgId', function (event) {
        var _this = $(this)
        cjqt.search_vague.event_input(_this, 'org__id', 'org__span', contextPath, '/admin/templ/getOrgListByName', type)
      });
      $elem.on("focus", '#orgId', function (event) {
        var _this = $(this)
        cjqt.search_vague.event_focus(_this, 'org__id', 'org__span', contextPath, '/admin/templ/getOrgListByName', type)
      });
      $elem.on('blur', '#orgId', function (event) {
        var _this = $(this)
        cjqt.search_vague.event_blur(_this, 'org__id', type)
      });
      $elem.on('click', '.select_wrap>.org__span', function (event) {
        event.preventDefault();
        event.stopPropagation();
        /* Act on the event */
        var _this = $(this)
        cjqt.search_vague.event_click(_this, 'org__id', '#orgId', type)
      });
    },
    rendertable: function () {
      var _this = this;
      layui.use(['table', 'laydate', 'form'], function () {
        table = layui.table;
        var form = layui.form,
          layer = layui.layer,
          laydate = layui.laydate;
        //日期
        laydate.render({
          elem: '#date1'
        });
        //方法级渲染
        table.render({
          elem: '#LAY_table_user',
          url: $("#contextPath").val() + "/system/elementgroup/orgSettingList",
          method: "post",
          where: {
            orgId: $("#conditionform #orgId").attr("org__id")
          },
          skin: 'nob' //行边框风格
            ,
          even: true //开启隔行背景
            ,
          size: 'lg' //小尺寸的表格
            ,
          cols: [
            [{
              field: 'index',
              title: '序号',
              width: '80',
              templet: '#indexTpl'
            }, {
              field: 'orgName',
              title: '校区',
              width: 200
            }, {
              field: 'groupname',
              title: '名称',
              minWidth: 200
            }, {
              field: 'funcName',
              title: '所属功能',
              minWidth: 120
            }, {
              field: 'setting',
              title: '常用选项',
              width: 200
            }, {
              title: '操作',
              fixed: 'right',
              width: 80,
              align: 'center',
              templet: function (data) {
                var str = "<div class='operate'>";
                str += "<span class='op_edit_btn' lay-event='edit' data-groupid='" + data.groupId + "'  data-orgid='" + data.orgId + "'><i class='edit'></i><i class='op_hover'>修改</i></span>";
                str += "</div>";
                return str;
              }
            }]
          ],
          id: 'testReload',
          page: true,
          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) {
            $(".edit,.delete").mouseover(function () {
              $(this).next().show();
            })
            $(".edit,.delete").mouseout(function () {
              $(this).next().hide();
            })
            //如果是异步请求数据方式，res即为你接口返回的信息。
            //修改
            $(".op_edit_btn").on("click", function () {
              var groupId = $(this).data("groupid");
              var orgId = $(this).data("orgid");
              _this.ajaxDetail(groupId, orgId, function (data) {
                $("body").append(template.render(tpl.modifyTpl)(data));
                // 继续添加选项
                $(".add-ele-again").on("click", function () {
                  var str = "<li class='lis' data-id=''><div class='sort-use'> <input class='sort'  type='text' value=''/></div><div class='con-use'> <input class='item-name' type='text' value=''/> </div><div class='del-use'><span class='del-use-btn'></span></div></li>";
                  $(".useList").append(str);
                });
                // 删除添加的选项
                $("body").on("click", ".del-use-btn", function () {
                  $(this).parent().parent().remove();
                });
                //关闭弹窗
                $(".close-btn,.cancel-add-btn").on("click", function () {
                  $(".dialog-wp").remove();
                });
                //确认添加
                $(".sure-add-btn").on("click", function () {
                  var elements = [];
                  for(var i=0;i < $(".dialog-wp .lis").length;i++){
                    let param = {};
                    param.id = $(".dialog-wp .lis")[i].getAttribute("data-id");
                    param.sort = $(".dialog-wp .lis")[i].getElementsByClassName("sort")[0].value;
                    param.itemname = $(".dialog-wp .lis")[i].getElementsByClassName("item-name")[0].value;
                    elements.push(param);
                  }
                  _this.submitAdd(function () {
                    $(".dialog-wp").remove();
                    layer.msg("修改成功！");
                    _this.againRenderTable();
                  }, groupId, orgId,elements);
                })
              });
            });
          }
        });
        //查询
        $('.search-btn').on('click', function () {
          _this.againRenderTable();
        });
      });
    },
    /*重新渲染table*/
    againRenderTable: function () {
      table.reload('testReload', {
        where: {
          orgId: $("#conditionform #orgId").attr("org__id"),
          groupName: $("#conditionform #companyId").val(),
          funcId: $("#conditionform #apartId").val()
        },
        page: {
          curr: 1 //重新从第 1 页开始
        }
      });
    },
    /**
     * 请求详情
     * @param id
     * @param callback
     */
    ajaxDetail: function (groupId, orgId, callback) {
      var _this = this;
      $.ajax({
        type: "post",
        url: contextPath + "/system/elementgroup/orgSettingDetail",
        data: {
          groupId: groupId,
          orgId: orgId
        },
        success: function (data) {
          if (data.code == ERROK) {
            callback(data.data)
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    /**
     * 新增或修改
     * @param callback
     * @param id
     */
    submitAdd: function (callback, groupId, orgId,params) {
      var elements = JSON.stringify(params);
      $.ajax({
        type: "post",
        url: $("#contextPath").val() + "/system/elementgroup/saveUpdateOrgSetting",
        data: {
          groupId: groupId,
          orgId: orgId,
          elements: elements
        },
        dataType: "json",
        success: function (data) {
          if (data.code == 200) {
            callback();
          } else {
            layer.msg(data.msg)
          }
        },
        error: function () {
          // layer.msg('系统繁忙.....')
        }
      });
    },
    /**
     * 获取所属功能列表
     * @param data
     * @param callbck
     */
    ajaxUpdate: function () {
      $.ajax({
        type: "post",
        url: $("#contextPath").val() + "/system/elementgroup/funcList",
        success: function (data) {
          if (data.code == 200) {
            var str = "";
            $.each(data.data, function (index, item) {
              str += "<option value='" + item.id + "'>" + item.itemname + "</option>"
            })
            $("#conditionform #apartId").append(str);
          } else {
            layer.msg(data.msg)
          }
        },
        error: function () {
          // layer.msg('系统繁忙.....')
        }
      });
    }
  };
  api.init();
})