{% extends "base.html" %}
{%load staticfiles%}

{% block css %}
<link rel="stylesheet" href="{% static 'bower_components/select2/dist/css/select2.min.css' %}">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css" >
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

{% endblock %}

{% block content %}
<!-- Content Header (Page header) -->
<section class="content-header">
    <h1>
      工作流管理
      <small>执行脚本管理</small>
    </h1>
    <ol class="breadcrumb">
      <li><a href="/manage/workflow_manage"><i class="fa fa-dashboard"></i> 工作流管理</a></li>
    </ol>
  </section>
  <div class="row">
    <section class="content-header">
      <div class="col-md-12">
        <div class="box box-default">
            <button type="button" class="btn btn-success" data-toggle="modal" data-target="#runScriptModal">
                新增
            </button>
          <table id="run_script_table" class="table table-striped table-bordered dataTable no-footer" >
            <thead>
              <tr>
                  <th>ID</th>
                  <th>名称</th>
                  <th>描述</th>
                  <th>存储文件名</th>
                  <th>可用</th>
                  <th>创建人</th>
                  <th>创建时间</th>
                  <th>操作</th>
              </tr>
            </thead>
            <tbody>   
            </tbody>
          </table>      
        </div>                
      <!-- </div> -->
      </div>
      <div class="modal fade" id="runScriptModal">
          <div class="modal-dialog" style="width: 980px;">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">工作流脚本</h4>
              </div>
              <div class="modal-body">
                  <form class="form-horizontal" id='run_script_form'>
                      <div class="box-body">
                        <div class="form-group">
                          <label for="scriptName" class="col-sm-3 control-label">名称</label> 
                          <div class="col-sm-9">
                            <input type="text" class="form-control" id="scriptName" placeholder="请输入工作流名称">
                          </div>
                        </div>
                        <div class="form-group">
                            <label for="scriptDesc" class="col-sm-3 control-label">描述</label> 
                            <div class="col-sm-9">
                              <input type="text" class="form-control" id="scriptDesc" placeholder="请输入工作流描述">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="WorkflowScriptFile" class="col-sm-3 control-label">选择脚本</label>
                            <div class="col-sm-9">
                              <input type="file" id="WorkflowScriptFile" accept=".py">
                              <p class="help-block" id=nowScriptFile></p>   
                              <p class="help-block">仅支持python脚本,media/workflow_script/demo_script.py为示例脚本，请参考编写</p>
                            </div>
                        </div>
                        <div class="checkbox">
                            <label for="isActive" class="col-sm-3 control-label">可用</label>
                              <div class="col-sm-9">
                                <input type="checkbox" id='isActive' checked>
                                <p class="help-block">开启后，该脚本才可以被选择和被实际执行</p>
                              </div>
                              <input type="text" class="form-control" id="WorkflowScriptId" style="display:none">
                              
                            </label>
                          </div>
                      </div>
                      <!-- /.box-body -->
                      <div class="box-footer">
                        <!-- <button type="submit" class="btn btn-info pull-right">确定</button> -->
                        <input type="button" value="保存" class="btn btn-info pull-right" onclick = "submitWorkflowScript();" />
                      </div>
                      <!-- /.box-footer -->
                    </form>
              </div>
            </div>
            <!-- /.modal-content -->
          </div>
          <!-- /.modal-dialog -->
      </div>


      
    </section>
      <!-- /.box -->
  </div>
  </section>
      <!-- /.col -->
   
  <!-- /.content -->
  
</div>

<!-- /.content-wrapper -->

{% endblock %}

{% block js %}
<!-- jQuery 3 -->
<script src="{% static 'bower_components/jquery/dist/jquery.min.js' %}"></script>
<!-- Bootstrap 3.3.7 -->
<script src="{% static 'bower_components/bootstrap/dist/js/bootstrap.min.js' %}"></script>
<!-- AdminLTE App -->
<script src="{% static 'dist/js/adminlte.min.js' %}"></script>
<script src="{% static 'bower_components/select2/dist/js/select2.full.min.js' %}"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap.min.js"></script>

<script>
  $("#runScriptModal").on("hidden.bs.modal", function() {
    $(this).removeData("bs.modal");
    $("#run_script_form")[0].reset();
    // $("#scriptName").attr("value",'');
    // $("#scriptDesc").attr("value",'');
    $("#nowScriptFile").html('');
    $("#WorkflowScriptId").attr("value", null);
    // $("#isActive").attr("value",false);
    
});
  $('#noticeScriptSelect').select2({placeholderOption: "first", allowClear:true});
  function submitWorkflowScript(){
    let WorkflowScriptId = document.getElementById("WorkflowScriptId").value;
    if (!WorkflowScriptId){
      addWorkflowScript()
    }
    else{
      // 编辑
      editWorkflowScript();
    }
  };
  function addWorkflowScript() {
    var form_data = new FormData();
    var file_info = $('#WorkflowScriptFile')[0].files[0];
    var scriptName = $("#scriptName").val()
    var scriptDesc = $("#scriptDesc").val()
    var is_active = 0

    // if ($('#isActive').attr('checked')) {  // 发现用此方法获取后值有问题
    if (document.getElementById("isActive").checked) {
      is_active = 1
    }
    form_data.append('file',file_info);
    form_data.append('script_name',scriptName);
    form_data.append('script_desc',scriptDesc);
    form_data.append('is_active',is_active);
    if(file_info===undefined){
      alert('请选择python文件');
      return false
    }
    // 提交ajax的请求
    $.ajax({
        url:"/api/v1.0/workflows/run_scripts",
        type:'POST',
        data: form_data,
        processData: false,
        contentType: false,
        success: function(callback) {
          $('#runScriptModal').modal('hide')
          swal({
              title: "编辑成功!",
              text: "2s自动关闭",
              icon: "success",
              showConfirmButton: false,
              timer:2000
            })
          $('#run_script_table').dataTable()._fnAjaxUpdate(); 
        }
    }); // end ajax
  }

  function editWorkflowScript() {
    var form_data = new FormData();
    var file_info = $('#WorkflowScriptFile')[0].files[0];
    var scriptName = $("#scriptName").val()
    var scriptDesc = $("#scriptDesc").val()
    var WorkflowScriptId = $("#WorkflowScriptId").val()
    var is_active = 0

    // if ($('#isActive').attr('checked')) {  // 发现用此方法获取后值有问题
    if (document.getElementById("isActive").checked) {
      is_active = 1
    }
    form_data.append('file',file_info);
    form_data.append('script_name',scriptName);
    form_data.append('script_desc',scriptDesc);
    form_data.append('is_active',is_active);
    
    // 提交ajax的请求
    $.ajax({
        url:"/api/v1.0/workflows/run_scripts/" + WorkflowScriptId,
        type:'POST', // 本来准备用patch的。但是发现非json提交过来获取不到数据(因为要传文件，所以不能用json)
        data: form_data,
        processData: false,
        contentType: false,
        success: function(callback) {
          $('#runScriptModal').modal('hide')
          swal({
              title: "编辑成功!",
              text: "2s自动关闭",
              icon: "success",
              showConfirmButton: false,
              timer:2000
            })
          $('#run_script_table').dataTable()._fnAjaxUpdate(); 
        }
    }); // end ajax
  };



  function showEditForm(data){
    $("#scriptName").attr("value",data.name);
    $("#scriptDesc").attr("value",data.description);
    // $("#WorkflowScriptFile").attr("value",data.saved_name);
    nowScriptFileContent= "<a href=" + "/media/" + data.saved_name + ">" + data.saved_name + "</a>";
    $("#nowScriptFile").html(nowScriptFileContent);
    $("#WorkflowScriptId").attr("value",data.id);
    
    $("#isActive").attr("value",data.is_active);
    if (data.is_active) {
      $('#isActive').attr('checked', true);
    } else {
      $('#isActive').attr('checked', false);
    };
    $('#runScriptModal').modal('show');
  }

  $('#run_script_table').DataTable({
  ordering: false,
  "serverSide":true,
  "bFilter":true,
  "lengthMenu": [10, 25, 50, 100 ],
  "language": {
    "searchPlaceholder": "名称或描述模糊搜索"
  },

  ajax: function (data, callback, settings) {
    console.log(data);
    var param = {};
    param.per_page = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
    param.page = (data.start / data.length)+1;//当前页码
    param.search_value=data.search.value;
    console.log(param);    
    $.ajax({
      type: "GET",
      url: "/api/v1.0/workflows/run_scripts",
      cache: false,  //禁用缓存
      data: param,  //传入组装的参数
      dataType: "json",
      success: function (result) {
        var returnData = {};
        returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
        returnData.recordsTotal = result.data.total;//返回数据全部记录
        returnData.recordsFiltered = result.data.total;//后台不实现过滤功能，每次查询均视作全部结果
        returnData.data = result.data.value;//返回的数据列表
        //console.log(returnData);
        //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
        //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
        callback(returnData);
        },
      
    })
    
  },
  columns: [
      { "data": "id"},
      { "data": "name" },
      { "data": "description" },
      { "data": "saved_name" },
      { "data": "is_active", render: function(data, type, full){if(data){return '是'}return '否'}},
      { "data": "creator" },
      { "data": "gmt_created" },
      {render: function(data, type, full){var rosJson=JSON.stringify(full).replace(/"/g, '&quot;');return ('<div><a  onclick="showEditForm(' + rosJson + ')' + '"' + '>编辑</a>/<a onclick="delRunScript(' + full.id + ')' + '"'+  '>删除</a></div>')}}
      // { "data": "parent_dept_info", render: function(data, type, full) {return data.parent_dept_name}},
      // { "data": "leader_info", render: function(data, type, full) {return data.leader_alias + "(" + data.leader_username  +")"} },
      // { "data": "approver_info", render: function(data, type, full) { if(data.length){return (data.map(function(value,index,array){return value.approver_alias +"(" + value.approver_name +")"}).join(','))} else {return ''}  }},
      // { "data": "label" },
      // { "data": "creator_info", render: function(data, type, full) {if(data.creator_alias){return data.creator_alias}else{return data.creator_username}}},

  ]
  
})

function delRunScript(runScriptId){
    swal({
      title: "是否真的要删除此记录?",
      text: "本删除操作只标记记录的删除状态，脚本文件不会实际删除",
      icon: "warning",
      buttons: true,
      dangerMode: true,
    })
    .then((willDelete) => {
      if (willDelete) {
        // 删除操作
        $.ajax({
        type: "DELETE",
        url: "/api/v1.0/workflows/run_scripts/" + runScriptId,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
          if (result.code===0){
            // 刷新数据
            $('#run_script_table').dataTable()._fnAjaxUpdate(); 
            // 关闭modal
            swal({
              title: "删除成功!",
              text: "2s自动关闭",
              icon: "success",
              showConfirmButton: false,
              timer:2000
            })
            }
          }
        });
      }
    });
  }
</script>
{% endblock %}
