<!DOCTYPE html>
<!--suppress ALL-->
<html lang="en" xmlns:th="https://www.thymeleaf.org/">
<head>
  <meta charset="UTF-8">
  <title th:if="${type == 'add'}">新增控制策略</title>
  <title th:if="${type == 'detail'}">查看控制策略</title>
  <!-- 引入 layui.css -->
  <link href="../static/layui-v2.8.11/css/layui.css" rel="stylesheet">
  <!-- 引入 layui.js -->
  <script src="../static/jquery/jquery-3.2.1.min.js"></script>
  <script src="../static/layui-v2.8.11/layui.js"></script>
  <!-- 加载 Select2 -->
  <link href="../static/select2/4.0.8/css/select2.min.css" rel="stylesheet" />
  <script src="../static/select2/4.0.8/js/select2.min.js"></script>
  <style>
    body {
      background-color: #f5f5f5;
      margin: 0;
      padding: 0;
    }

    .body {
      padding: 23.8px;
    }

    .left-title {
      font-size: 22px;
      margin-bottom: 15px;
      margin-top: 15px;
    }

    .z-body {
    }

    .z-body .layui-form-label {
      font-size: 14px;
    }

    .layui-input-inline{
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .z-body .layui-input-inline .layui-btn {
      padding: 0;
      height: 36px;
      width: 80px;
      line-height: 0px;
    }

    .z-search .layui-form-item {
      margin: 10px 0px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    table th {
      background-color: #fafafa;
      color: #2c2a29;
    }

    .layui-form-onswitch {
      border-color: #1890ff;
      background-color: #1890ff;
    }

    .layui-table-body .layui-table-cell {
      height: 56px;
      line-height: 41px;
    }

    .layui-table-column {
      display: flex;
      justify-content: flex-end;
    }
    /*单选按钮颜色*/
    .layui-form-radio:hover>*, .layui-form-radioed, .layui-form-radioed>i{
      color: #1890ff;
    }
    .layui-form-radio{
      padding-right: 35px;
    }
    .layui-input-split{
      /*border-color: #7f6666 !important;*/
      /*border-width:1px;*/
    }

    /*设置奇数行颜色*/
    table tr:nth-child(odd)
    {
      /*background: #f5f5f5;*/
    }
    /*设置偶数行颜色*/
    table tr:nth-child(even)
    {
      /*background: #f5f5f5;*/
    }
    .layui-col-md7 {
        width: 50.6%;
    }
    .layui-laydate-linkage .layui-laydate-content td.laydate-selected>div {
      background-color: #83bdf5;
    }
    .select2{
      width: 50.6% !important;
    }
    .select2-selection__choice__remove{
      float: right !important;
    }
    .select2-container--default .select2-selection--multiple{
      border: 1px solid #eee !important;
    }
    /* 设置只展示时分，隐藏秒那一列 */
    .laydate-time-list {
      padding-bottom: 0;
      overflow: hidden;
    }

    .laydate-time-list > li {
      width: 50% !important;
    }

    .laydate-time-list > li:last-child {
      display: none;
    }

    .laydate-time-list ol li {
      width: 100% !important;
      padding-left: 0 !important;
      text-align: center !important;
    }
    /* #1890ff-> #16b777*/
    /*旧的颜色#16baaa*/
    /*.layui-badge-rim, .layui-border, .layui-colla-content, .layui-colla-item, .layui-collapse, .layui-elem-field, .layui-form-pane .layui-form-item[pane], .layui-form-pane .layui-form-label, .layui-input, .layui-input-split, .layui-panel, .layui-quote-nm, .layui-select, .layui-tab-bar, .layui-tab-card, .layui-tab-title, .layui-tab-title .layui-this:after, .layui-textarea {
      border-color: #c1c1c1;
    }*/
  </style>
</head>
<body>
<div class="body">
  <div class="left-title layui-row">
    <div class="layui-col-md6 layui-col-xs6 layui-col-sm6 layui-col-lg6 layui-col-xl6">
      <p th:if="${type == 'add'}">新增控制策略</p>
      <p th:if="${type == 'detail'}">查看控制策略</p>
    </div>
    <div class="layui-col-md6 layui-col-xs6 layui-col-sm6 layui-col-lg6 layui-col-xl6">
      <!--<button type="button" class="layui-btn" style="font-size: 16px;float: right;background-color: #41a69a">返回</button>-->
    </div>
  </div>
  <div class="z-body">
    <div class="layui-card layui-panel">
      <div class="layui-card-body z-search">
        <form>
        <table class="layui-table">
          <colgroup>
            <col width="150">
            <col>
          </colgroup>
          <tbody>
          <tr>
            <td>策略名称：</td>
            <td>
              <div class="layui-col-md7">
                <div class="layui-form">
                  <input type="hidden" th:value="${detail.celueid}" id="celueid"/>
                  <input type="text" name="name" id="celueName" placeholder="请填写策略名称···" class="layui-input" th:value="${detail.name}">
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td>选择设备：</td>
            <td>
              <input id="devids" th:value="${detail.devid}" type="hidden"/>
              <select id="id_select2_demo1" class="layui-col-md7" multiple="multiple">
                <!--　　<optgroup label="Group 1" class="group-1">
                　　　　<option value="1-1">Option 1.1</option>
                　　　　<option value="1-2">Option 1.2</option>
                　　　　<option value="1-3">Option 1.3</option>
                　　</optgroup>
                　　<optgroup label="Group 2" class="group-2">
                　　　　<option value="2-1">Option 2.1</option>
                　　　　<option value="2-2">Option 2.2</option>
                　　　　<option value="2-3">Option 2.3</option>
                　　</optgroup>-->
              </select>
            </td>
          </tr>
          <tr>
            <td>操作类型</td>
            <td>
              <input type="hidden" id="status" th:value="${detail.status}"/>
              <div class="layui-form layui-row layui-col-space16">
                <div class="layui-col-md3">
                  <input type="hidden" th:value="${detail.type}" id="typeValue"/>
                  <select id="type" th:readonly="${type=='detail'}">
                    <option value="">请选择</option>
                    <option value="1">开灯/放电</option>
                    <option value="0">关灯/断电</option>
                  </select>
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td>执行周期：</td>
            <td>
              <div class="layui-form">
                <input type="hidden" id="timeTypeValue" th:value="${detail.timeType}"/>
                <input type="radio" name="timeType" value="everyDay" lay-filter="demo-radio-filter" title="每天" th:checked="${detail.timeType=='everyDay' || type == 'add'}">
                <input type="radio" name="timeType" value="weekly" lay-filter="demo-radio-filter" title="每周" th:checked="${detail.timeType=='weekly'}">
                <input type="radio" name="timeType" value="day" lay-filter="demo-radio-filter" title="单日" th:checked="${detail.timeType=='day'}">
                <input type="radio" name="timeType" value="date" lay-filter="demo-radio-filter" title="日期段" th:checked="${detail.timeType=='date'}">
                <!--<input type="radio" name="AAA" value="3" title="禁用" disabled>-->
              </div>
            </td>
          </tr>
          <tr id="weeklyTr" th:hidden="${type=='add' || detail.timeType!='weekly'}">
            <!--周-->
            <td>选择日期：</td>
            <td>
              <div class="layui-col-md6" id="weeklyDiv">
                <div class="layui-form">
                  <input id="weeklyd" type="hidden" th:value="${detail.weeklyDay}"/>
                  <input type="checkbox" name="weeklyDay" title="星期一" value="1" id="weeklyDay1">
                  <input type="checkbox" name="weeklyDay" title="星期二" value="2" id="weeklyDay2">
                  <input type="checkbox" name="weeklyDay" title="星期三" value="3" id="weeklyDay3">
                  <input type="checkbox" name="weeklyDay" title="星期四" value="4" id="weeklyDay4">
                  <input type="checkbox" name="weeklyDay" title="星期五" value="5" id="weeklyDay5">
                  <input type="checkbox" name="weeklyDay" title="星期六" value="6" id="weeklyDay6">
                  <input type="checkbox" name="weeklyDay" title="星期日" value="7" id="weeklyDay7">
                    <!--<input type="checkbox" name="weeklyDay" lay-text="选中" checked>
                    <input type="checkbox" name="weeklyDay" title="禁用" disabled>-->
                </div>

              </div>
            </td>
          </tr>
          <tr id="dayTr" th:hidden="${type=='add' || detail.timeType!='day'}">
            <!--单日-->
            <td>选择日期：</td>
            <td>
              <div class="layui-col-md3" id="dayDiv">
                <div class="layui-input-wrap">
                  <input type="text" class="layui-input" id="ID-laydate-demo" placeholder="选择策略执行时间"  th:value="${detail.startTime}">
                  <div class="layui-input-split layui-input-suffix" style="background-color: #f5f5f5">
                    <i class="layui-icon layui-icon-time"></i>
                  </div>
                </div>
              </div>
            </td>
          </tr>
          <tr id="dateTr" th:hidden="${type=='add' || detail.timeType!='date'}">
            <!--范围-->
            <td>选择日期：</td>
            <td>
              <div id="ID-laydate-rangeLinked">
                <div class="layui-col-md3" style="margin-right: 0.5%">
                  <div class="layui-input-wrap">
                    <input type="text" autocomplete="off" id="ID-laydate-start-date-1" class="layui-input" placeholder="选择策略执行开始日期" th:value="${detail.startTime}">
                    <div class="layui-input-split layui-input-suffix" style="background-color: #f5f5f5">
                      <i class="layui-icon layui-icon-date"></i>
                    </div>
                  </div>
                </div>
                <div class="layui-col-md3">
                  <div class="layui-input-wrap">
                    <input type="text" autocomplete="off" id="ID-laydate-end-date-1" class="layui-input" placeholder="选择策略执行结束日期" th:value="${detail.endTime}">
                    <div class="layui-input-split layui-input-suffix" style="background-color: #f5f5f5">
                      <i class="layui-icon layui-icon-date"></i>
                    </div>
                  </div>
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td>执行时段：</td>
            <td>
              <div class="layui-col-md3">
                <div class="layui-input-wrap">
                  <input type="text" class="layui-input laydate-time-list" id="ID-laydate-type-time" placeholder="选择策略开始时间" th:value="${detail.exeTime}">
                  <div class="layui-input-split layui-input-suffix" style="background-color: #f5f5f5">
                    <i class="layui-icon layui-icon-time"></i>
                  </div>
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td>备注信息：</td>
            <td>
              <div class="layui-col-md7">
                <div class="layui-form">
                  <textarea name="detail" id="detail" placeholder="请填写备注文字···" class="layui-textarea" th:text="${detail.description}"></textarea>
                </div>
              </div>
            </td>
          </tr>
          </tbody>
        </table>
          <div class="layui-input-inline" th:if="${type == 'add'}">
            <button type="button" onclick="sub('add')" class="layui-btn layui-btn-normal">提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
          </div>
          <div class="layui-input-inline" th:if="${type == 'detail'}">
            <button type="button" onclick="sub('edit')" class="layui-btn layui-btn-normal">提交</button>
            <button type="button" class="layui-btn layui-btn-primary" onclick="back()">返回</button>
          </div>
        </form>

      </div>
    </div>
  </div>
</div>

<script>
  var laypage;
  var name='';
  var status='';
  getDeviceList()
  function getDeviceList(){
    $.ajax({
      type: "GET",
      url: "/device/listAll",
      success: function(res){
        console.log(res)
        if(res.success){
          var selectorx = $('#id_select2_demo1').select2();
          //var data=[{"id":"1","text":"1F左侧走廊照明灯组"},{"id":2,"text":"1F右侧走廊照明灯组"},{"id":3,"text":"2F左侧走廊照明灯组"},{"id":4,"text":"2F右侧走廊照明灯组"}];
          $("#id_select2_demo1").select2({
            data:res.result
          });
          changeSelect()
        }else{}
      }
    });
  }
  function changeSelect(){
    /*select2 回显*/
    var str=$("#devids").val();
    var arr=str.split(',');
    console.log(arr)
    var select2d = $("#id_select2_demo1").select2();
    select2d.val(arr).trigger('change')
  }
  loadTable();
  var form;

  /*详情页,加载列表颜色*/
  var timeTypeValue = $("#timeTypeValue").val();
  if(timeTypeValue!=null &&timeTypeValue!=undefined &&timeTypeValue!=''){
    rowColor(timeTypeValue)
  }else{
    /*新增页，默认每天*/
    rowColor('everyDay')
  }

  function loadTable(){
    layui.use('table', function () {
      var table = layui.table;
      var $=layui.$;
      var util = layui.util;
      var laydate = layui.laydate;
      form = layui.form;

      // 时间选择器
      laydate.render({
        elem: '#ID-laydate-demo'
      });
      laydate.render({
        elem: '#ID-laydate-type-time',
        type: 'time',
        format: 'HH:mm', //设置日期格式
      });
      // 日期范围 - 左右面板联动选择模式
      laydate.render({
        elem: '#ID-laydate-rangeLinked',
        range: ['#ID-laydate-start-date-1', '#ID-laydate-end-date-1'],
        rangeLinked: true // 开启日期范围选择时的区间联动标注模式 ---  2.8+ 新增
      });
      /*$("#weeklyTr").hide();
      $("#dayTr").hide();
      $("#dateTr").hide();*/
      /*$('#dayTr').hide();
      $('#dayTr2').show();*/

      //周 回显
      let weeklyd = $("#weeklyd").val();
      if (weeklyd != null && weeklyd != '') {
        let split = weeklyd.split(',');
        $("[name=weeklyDay]").each(function () {
          // 根据值回显
          if (weeklyd.indexOf($(this).val())!=-1) {
            $(this).attr("checked", "checked");
            /*return false;*/
          }
          form.render();
        });
      }
      //操作类型 回显
      $("#type").each(function (){
        var typeValue=$("#typeValue").val();
        // this代表的是<option></option>，对option再进行遍历
        $(this).children("option").each(function() {
          // 判断需要对那个选项进行回显
          if (this.value == typeValue) {
            console.log($(this).text());
            // 进行回显
            $(this).attr("selected","selected");
          }
        });
        form.render();
      })

      // 事件
      // radio 事件
      form.on('radio(demo-radio-filter)', function(data){
        var elem = data.elem; // 获得 radio 原始 DOM 对象
        var checked = elem.checked; // 获得 radio 选中状态
        var value = elem.value; // 获得 radio 值
        var othis = data.othis; // 获得 radio 元素被替换后的 jQuery 对象

        console.log(value)
        if(value=='weekly'){
          $("#weeklyTr").show();
          $("#dayTr").hide();
          $("#dateTr").hide();
        }else if (value == 'day') {
          $("#weeklyTr").hide();
          $("#dayTr").show();
          $("#dateTr").hide();
        }else if(value==='date'){
          $("#weeklyTr").hide();
          $("#dayTr").hide();
          $("#dateTr").show();
        }else{
          $("#weeklyTr").hide();
          $("#dayTr").hide();
          $("#dateTr").hide();
        }
        rowColor(value)
      });
    });
  };

  function rowColor(value){
    var i=0;
    $('tr').each(function(i) {
      $(this).css("background", '');
    });
    //选择每天
    if (value == 'day') {
      $('tr').each(function(i) {
        if ($(this).attr('id') != 'dayTr') {
          i++;
          if (i % 2 == 0) {
            $(this).css("background", "#f5f5f5");
          }
        }
      });
    }else if(value =='weekly'){
      $('tr').each(function(i) {
        i++;
        if(i % 2 ==0){
          $(this).css("background","#f5f5f5");
        }
      });
    }else if(value == 'everyDay'){
      $('tr').each(function() {
        if ($(this).attr('id') != 'dayTr') {
          i++;
          if (i % 2 == 0) {
            $(this).css("background", "#f5f5f5");
          }
        }
      })
    } else{
      $('tr').each(function() {
        i++;
        if ($(this).attr('id') != 'dateTr') {
          if (i % 2 == 0) {
            $(this).css("background", "#f5f5f5");
          }
        }

      })
    }
  }

  function sub(subType){
    //策略名称
    let celueName = $("#celueName").val();
    //选择设备
    let devidList = $("#id_select2_demo1").val();
    let type = $("#type").val();
    //执行周期
    let timeType = null;
    var radio = document.getElementsByName("timeType");
    for (i=0; i<radio.length; i++) {
      if (radio[i].checked) {
        timeType = radio[i].value;
      }
    }
    //执行时段
    let exeTime = $("#ID-laydate-type-time").val();
    //每周-选择日期
    //let weeklyDay=$("#weeklyDay").val();
    let weeklyDay = document.getElementsByName("weeklyDay");
    var weeklyDayList = [];
    if (weeklyDay != null) {
      for(k in weeklyDay){
        if(weeklyDay[k].checked)
          weeklyDayList.push(weeklyDay[k].value);
      }
    }
    //单日-选择日期
    let day=$("#ID-laydate-demo").val();
    //日期段-选择日期
    let startDate = $("#ID-laydate-start-date-1").val();
    let endDate = $("#ID-laydate-end-date-1").val();
    //描述
    let description = $("#detail").val();
    console.log('策略名称:'+celueName)
    console.log('选择设备:'+devidList)
    console.log('执行周期:'+timeType)
    console.log('执行时段:'+exeTime)
    console.log('每周-选择日期:'+weeklyDayList)
    console.log('单日-选择日期:'+day)
    console.log('日期段-选择日期:'+startDate+"-"+endDate)
    if(checkNull(celueName)){
      layer.msg('请输入[策略名称]', {icon: 0}, function(){
        // layer.msg('提示框关闭后的回调');
      });
      return false;
    }
    if(checkArray(devidList)){
      layer.msg('请选择[设备]', {icon: 0}, function(){
        // layer.msg('提示框关闭后的回调');
      });
      return false;
    }

    if(timeType=='weekly'){
      if (checkArray(weeklyDayList)) {
        layer.msg('请选择[选择日期]', {icon: 0}, function(){
          // layer.msg('提示框关闭后的回调');
        });
        return false;
      }
      startDate="";
      endDate="";
    }else if (timeType == 'day') {
      if (checkNull(day)) {
        layer.msg('请选择[选择日期]', {icon: 0}, function(){
          // layer.msg('提示框关闭后的回调');
        });
        return false;
      }
      startDate=day;
      endDate=day;
    }else if(timeType==='date'){
      if(checkNull(startDate)){
        layer.msg('请选择[策略执行开始日期]', {icon: 0}, function(){
          // layer.msg('提示框关闭后的回调');
        });
        return false;
      }
      if(checkNull(endDate)){
        layer.msg('请选择[策略执行结束日期]', {icon: 0}, function(){
          // layer.msg('提示框关闭后的回调');
        });
        return false;
      }
      if (startDate == endDate) {
        layer.msg('请选择[策略执行开始日期-结束日期 不可一致]', {icon: 0}, function(){});
        return false;
      }
    }

    if (checkNull(exeTime)) {
      layer.msg('请选择[执行时段]', {icon: 0}, function(){});
      return false;
    }
    var status = $("#status").val();
    status=checkNull(status)?'0':status;
    var index = layer.load(0, {shade: false});
    var obj = {
      'name':celueName,
      'devidList':devidList,
      'type':type,
      'timeType':timeType,
      'exeTime':exeTime,
      'weeklyDay':weeklyDayList.join(','),
      'day':day,
      'startTime':startDate,
      'endTime':endDate,
      'status':status,
      'description':description
    };
    let ajaxType='POST'//请求类型
    if (subType == 'edit') {
      obj.celueid = $("#celueid").val()
      ajaxType = 'PUT'
    }
    //请求保存
    var jsonObj = JSON.stringify(obj);
    console.log(jsonObj)
    $.ajax({
      type: ajaxType,
      url: "/celue",
      data: jsonObj,
      contentType: 'application/json;charset=utf-8',
      success: function(res){
        console.log(res)
        layer.close(index);
        if (res.success) {
          layer.alert(res.message, {
            time: 2*1000,
            success: function(layero, index){
              var timeNum = this.time/1000, setText = function(start){
                layer.title('<span class="layui-font-red">'+ (start ? timeNum : --timeNum) + '</span> 秒后自动关闭', index);
              };
              setText(!0);
              this.timer = setInterval(setText, 1000);
              if(timeNum <= 0) clearInterval(this.timer);
            },
            end: function(){
              clearInterval(this.timer);
              window.location.href='/';
            }
          });
        }else{
          layer.msg(res.message, {icon: 0,title:'提示'});
        }
      },error:function (res){
        layer.close(index);
        layer.msg(res.message, {icon: 0,title:'提示'});
      }
    });
    setTimeout(function(){
      layer.close(index); // 关闭 loading
    }, 5000);

  }

  function checkNull(o){
    if (o == null || o == undefined || o == '') {
      return true;
    }
    return false;
  }
  function checkArray(a){
    if (a == null || a == undefined || a.length == 0) {
      return true;
    }
    return false;
  }
  function back(){
    window.location.href='/';
  }

</script>


</body>
</html>