<template>
  <div class="container-fluid">
    <Navbar title="任务管理" :is-go-back="false" />
    <a-button type="primary" @click="showDrawer"> 创建任务 </a-button>
    <a-button type="dashed" style="margin-left: 8px" @click="loadTaskTemplate">
      加载任务模板
    </a-button>
    <a-drawer
      v-model:visible="visible"
      class="custom-class"
      :title="taskDefineDto.id == null ? '创建任务' : '编辑任务'"
      placement="right"
      width="650"
    >
      <div id="myTabContent" class="tab-content">
        <div v-if="step == 1" class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">
              <b>1.基本配置</b>
            </h3>
          </div>
          <div class="panel-body">
            <form class="form-horizontal" role="form">
              <div class="form-group">
                <label for="firstname" class="col-sm-2 control-label">
                  <font color="red">*</font>名称
                </label>
                <div class="col-sm-10">
                  <input
                    id="firstname"
                    v-model="taskDefineDto.taskName"
                    autocomplete="off"
                    type="text"
                    class="form-control"
                    placeholder="请输入任务名称"
                  />
                </div>
              </div>
              <div class="form-group">
                <label for="lastname" class="col-sm-2 control-label">
                  <font color="red">*</font>描述
                </label>
                <div class="col-sm-10">
                  <input
                    id="lastname"
                    v-model="taskDefineDto.taskDescription"
                    autocomplete="off"
                    type="text"
                    class="form-control"
                    placeholder="请填写任务描述"
                  />
                </div>
              </div>
              <div class="form-group">
                <label for="lastname" class="col-sm-2 control-label">
                  <font color="red">*</font>任务类型
                </label>
                <div class="col-sm-10">
                  <v-select
                    v-model="taskDefineDto.selectedTaskType"
                    :options="taskTypes"
                    :label="'value'"
                    placeholder="请选择任务类型"
                  />
                </div>
              </div>
              <div
                v-if="
                  taskDefineDto.selectedTaskType &&
                    taskDefineDto.selectedTaskType.value == '流程'
                "
                class="form-group"
              >
                <label for="lastname" class="col-sm-2 control-label">
                  <font color="red">*</font>流程编号
                </label>
                <div class="col-sm-10">
                  <a-select
                    v-model:value="taskDefineDto.processNo"
                    :options="processNos"
                    style="width: 100%"
                    @change="processNoChang"
                  />
                </div>
              </div>
              <div
                v-if="
                  taskDefineDto.selectedTaskType &&
                    taskDefineDto.selectedTaskType.value == '流程'
                "
                class="form-group"
              >
                <label for="lastname" class="col-sm-2 control-label">
                  <font color="red">*</font>流程参数
                </label>
                <div class="col-sm-10" style="margin-bottom: 6px" />
                <div
                  class="col-sm-10"
                  style="margin-left: 100px; margin-bottom: 70px"
                >
                  <a-table
                    :columns="processColumns"
                    :data-source="processDatas"
                    :pagination="false"
                  >
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.dataIndex === 'defaultValue'">
                        <EditTableCell
                          :record="record"
                          :param-name="'defaultValue'"
                          :control-type="'input'"
                          @change-all="tableDataChange"
                        />
                      </template>
                    </template>
                  </a-table>
                </div>
              </div>
              <div
                v-if="
                  taskDefineDto.selectedTaskType != null &&
                    taskDefineDto.selectedTaskType.value == '流程报表'
                "
                class="form-group"
              >
                <label for="lastname" class="col-sm-2 control-label">
                  <font color="red">*</font>流程报表文件编码
                </label>
                <div class="col-sm-10">
                  <input
                    id="lastname"
                    v-model="taskDefineDto.processReportNo"
                    autocomplete="off"
                    type="text"
                    class="form-control"
                    placeholder="请填写流程报表文件编码"
                  />
                </div>
              </div>
              <div
                v-if="
                  taskDefineDto.selectedTaskType != null &&
                    taskDefineDto.selectedTaskType.value == '流程报表'
                "
                class="form-group"
              >
                <label for="lastname" class="col-sm-2 control-label">
                  <font color="red">*</font>流程报表名称
                </label>
                <div class="col-sm-10">
                  <input
                    id="lastname"
                    v-model="taskDefineDto.processReportName"
                    autocomplete="off"
                    type="text"
                    class="form-control"
                    placeholder="请填写流程报表名称"
                  />
                </div>
              </div>
              <div
                v-if="
                  taskDefineDto.selectedTaskType != null &&
                    taskDefineDto.selectedTaskType.value == 'HTTP任务'
                "
                class="form-group"
              >
                <label for="lastname" class="col-sm-2 control-label">
                  <font color="red">*</font>HTTP请求类型
                </label>
                <div class="col-sm-10">
                  <v-select
                    v-model="taskDefineDto.selectedRequestType"
                    :options="requestTypes"
                    :label="'value'"
                    placeholder="请选择HTTP请求类型"
                  />
                </div>
              </div>
              <div
                v-if="
                  taskDefineDto.selectedTaskType != null &&
                    taskDefineDto.selectedTaskType.value == 'HTTP任务'
                "
                class="form-group"
              >
                <label for="lastname" class="col-sm-2 control-label">
                  <font color="red">*</font>HTTP请求地址
                </label>
                <div class="col-sm-10">
                  <input
                    id="lastname"
                    v-model="taskDefineDto.httpRequestUrl"
                    autocomplete="off"
                    type="text"
                    class="form-control"
                    placeholder="请填写HTTP请求地址"
                  />
                </div>
              </div>
              <div
                v-if="
                  taskDefineDto.selectedTaskType != null &&
                    taskDefineDto.selectedTaskType.value == 'HTTP任务'
                "
                class="form-group"
              >
                <label for="lastname" class="col-sm-2 control-label">HTTP参数（json）</label>
                <div class="col-sm-10">
                  <input
                    id="lastname"
                    v-model="taskDefineDto.httpRequestParam"
                    autocomplete="off"
                    type="text"
                    class="form-control"
                    placeholder="请填写HTTP参数"
                  />
                </div>
              </div>
              <div
                v-if="
                  taskDefineDto.selectedTaskType &&
                    taskDefineDto.selectedTaskType.value !== '流程'
                "
                class="form-group"
              >
                <label for="lastname" class="col-sm-2 control-label">接收人</label>
                <div class="col-sm-10">
                  <v-select
                    v-model="taskDefineDto.selectedUser"
                    :options="users"
                    multiple
                    :label="'value'"
                    placeholder="请选择接收人"
                  />
                </div>
              </div>
              <div
                v-if="
                  taskDefineDto.selectedTaskType &&
                    taskDefineDto.selectedTaskType.value !== '流程'
                "
                class="form-group"
              >
                <label for="lastname" class="col-sm-2 control-label">接收用户组</label>
                <div class="col-sm-10">
                  <v-select
                    v-model="taskDefineDto.selectedGroup"
                    :options="groups"
                    multiple
                    :label="'value'"
                    placeholder="请选择接收用户组"
                  />
                </div>
              </div>
            </form>
          </div>

          <div class="panel-footer">
            <ul class="pager" style="margin: 5px 0">
              <li>
                <a class="pull-right" @click="saveCheck">下一步</a>
              </li>
            </ul>
          </div>
        </div>
        <div v-if="step == 2" class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">
              <b>2.定时配置</b>
            </h3>
          </div>
          <div class="panel-body">
            <form class="form-horizontal" role="form">
              <div class="form-group">
                <label for="lastname" class="col-sm-2 control-label">
                  <font color="red">*</font>时间类型
                </label>
                <div class="col-sm-10">
                  <v-select
                    v-model="taskDefineDto.selectedTimeType"
                    :options="timeTypes"
                    :label="'value'"
                    placeholder="请选择时间类型"
                  />
                </div>
              </div>
              <div
                v-if="
                  taskDefineDto.selectedTimeType != null &&
                    taskDefineDto.selectedTimeType.value == 'cron'
                "
                class="form-group"
              >
                <label for="cron" class="col-sm-2 control-label">
                  <font color="red">*</font>cron表达式
                </label>
                <div class="col-sm-10">
                  <input
                    v-model="taskDefineDto.cron"
                    autocomplete="off"
                    type="text"
                    class="form-control"
                    placeholder="请填写cron表达式"
                  />
                </div>
              </div>
            </form>
          </div>
          <div class="panel-footer">
            <ul class="pager" style="margin: 5px 0">
              <li>
                <a class="pull-left" @click="step = step - 1">上一步</a>
              </li>
              <li>
                <a class="pull-right" @click="saveCheck">下一步</a>
              </li>
            </ul>
          </div>
        </div>
        <div v-if="step == 3" class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">
              <b>3.报警配置</b>
            </h3>
          </div>
          <div class="panel-body">
            <form class="form-horizontal" role="form">
              <div class="form-group">
                <label for="firstname" class="col-sm-2 control-label">
                  <font color="red">*</font>超时报警
                </label>
                <div class="col-sm-10">
                  <Switches
                    v-model="taskDefineDto.timeoutAlarm"
                    :selected="taskDefineDto.timeoutAlarm"
                    :show-text="false"
                    style="width: 50px"
                    color="green"
                    type-bold="true"
                  />
                </div>
              </div>
              <div class="form-group">
                <label for="lastname" class="col-sm-2 control-label">超时时间</label>
                <div class="col-sm-10">
                  <input
                    id="lastname"
                    v-model="taskDefineDto.timeout"
                    autocomplete="off"
                    type="number"
                    class="form-control"
                    placeholder="超时时间(s),默认2小时"
                  />
                </div>
              </div>
              <div class="form-group">
                <label for="lastname" class="col-sm-2 control-label">
                  <font color="red">*</font>超时终止
                </label>
                <div class="col-sm-10">
                  <Switches
                    v-model="taskDefineDto.timeoutTermination"
                    :selected="taskDefineDto.timeoutTermination"
                    :show-text="false"
                    style="width: 50px"
                    color="green"
                    type-bold="true"
                  />
                </div>
              </div>
              <div class="form-group">
                <label for="firstname" class="col-sm-2 control-label">
                  <font color="red">*</font>失败报警
                </label>
                <div class="col-sm-10">
                  <Switches
                    v-model="taskDefineDto.failureAlarm"
                    :selected="taskDefineDto.failureAlarm"
                    :show-text="false"
                    style="width: 50px"
                    color="green"
                    type-bold="true"
                  />
                </div>
              </div>
              <div class="form-group">
                <label for="lastname" class="col-sm-2 control-label">报警联系人</label>
                <div class="col-sm-10">
                  <v-select
                    v-model="taskDefineDto.selectedAlarmUser"
                    :options="users"
                    multiple
                    :label="'value'"
                    placeholder="请选择报警联系人"
                  />
                </div>
              </div>
            </form>
          </div>
          <div class="panel-footer">
            <ul class="pager" style="margin: 5px 0">
              <li>
                <a class="pull-left" @click="step = step - 1">上一步</a>
              </li>
              <li>
                <a class="pull-right" @click="saveCheck">下一步</a>
              </li>
            </ul>
          </div>
        </div>
        <div v-if="step == 4" class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">
              <b>4.其他配置</b>
            </h3>
          </div>
          <div class="panel-body">
            <form class="form-horizontal" role="form">
              <div class="form-group">
                <label for="firstname" class="col-sm-2 control-label">状态</label>
                <div class="col-sm-10">
                  <v-select
                    v-model="taskDefineDto.selectedStatus"
                    :options="status"
                    :label="'value'"
                    placeholder="请设置任务状态"
                  />
                </div>
              </div>
            </form>
          </div>
          <div class="panel-footer">
            <ul class="pager" style="margin: 5px 0">
              <li>
                <a class="pull-left" @click="step = step - 1">上一步</a>
              </li>
              <li>
                <a class="pull-right" @click="saveCheck">保存</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </a-drawer>
    <CommonTable
      :total="pagination.total"
      :columns="columns"
      :data-source="taskDefineDtos"
      @get-page="getPageParams"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key == 'taskType'">
          {{
            record.taskType == null
              ? ""
              : record.taskType == "HTTP"
                ? "HTTP"
                : record.taskType == "PROCESS"
                  ? "流程"
                  : "流程报表"
          }}
        </template>
        <template v-if="column.key == 'receiveUserNames'">
          {{
            record.receiveUserNames != null &&
              record.receiveUserNames.length > 0
              ? record.receiveUserNames.join(",")
              : ""
          }}
        </template>
        <template v-if="column.key == 'receiveGroupNames'">
          {{
            record.receiveGroupNames != null &&
              record.receiveUserNames.length > 0
              ? record.receiveGroupNames.join(",")
              : ""
          }}
        </template>
        <template v-if="column.key == 'taskStatus'">
          {{ record.taskStatus == "ENABLE" ? "启用" : "禁用" }}
        </template>
        <template v-if="column.key == 'operation'">
          <a-button
            v-if="record.taskStatus == 'DISABLE'"
            :size="size"
            @click="updateStatus(record, 'ENABLE')"
          >
            启用
          </a-button>
          <a-button
            v-if="record.taskStatus == 'ENABLE'"
            :size="size"
            @click="updateStatus(record, 'DISABLE')"
          >
            禁用
          </a-button>
          <a-button type="primary" :size="size" @click="edit(record)">
            编辑
          </a-button>
          <a-button
            type="danger"
            :size="size"
            @click="deleteTaskBefore(record)"
          >
            删除
          </a-button>
          <a-button
            v-if="record.taskType != 'HTTP' && record.taskType != 'PROCESS'"
            type="dashed"
            :size="size"
            @click="manualExecutionProcess(record.id)"
          >
            执行
          </a-button>
        </template>
      </template>
    </CommonTable>
    <Modal v-model:show="modal" small="true" @ok="deleteTask">
      <template #header> 删除任务提醒 </template>
      <div class="container row" style="text-align: center">
        您确认要删除该任务吗？
      </div>
    </Modal>
    <Loading v-if="loading" />
  </div>
</template>

<script>
import vSelect from 'vue-select';
import Common from '../common/Common.js';
import TaskDefineResource from '../api/task/TaskDefineResource.js';
import UserResource from '../api/base/UserResource.js';
import GroupResource from '../api/base/GroupResource.js';
import 'vue-select/dist/vue-select.css';
import { Notify, Uuid } from 'pc-component-v3';
import CommonTable from './CommonTable.vue';
import { message } from 'ant-design-vue';
import EditTableCell from './EditTableCell.vue';
export default {
  components: {
    vSelect,
    CommonTable,
    EditTableCell,
  },
  data: function () {
    return {
      size: 'small',
      processColumns: [
        {
          key: 'name',
          title: '全局参数名称',
          dataIndex: 'name',
          width: 80,
        },
        {
          key: 'defaultValue',
          title: '全局参数值',
          dataIndex: 'defaultValue',
          width: 80,
        },
        {
          key: 'dataType',
          title: '全局参数类型',
          dataIndex: 'dataType',
          width: 80,
        },
        // {
        //   title: '操作',
        //   dataIndex: 'operation',
        //   key: 'operation',
        //   width: 60,
        // },
      ].map(item => ({ ...item, align: 'center' })),
      typeOptions: [
        {
          value: 'java.lang.Boolean',
        },
        {
          value: 'java.lang.Integer',
        },
        {
          value: 'java.lang.Double',
        },
        {
          value: 'java.lang.Long',
        },
        {
          value: 'java.lang.String',
        },
      ],
      processDatas: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          key: 'index',
          customRender: ({ text, record, index }) => `${index + 1}`,
        },
        {
          title: '任务名',
          dataIndex: 'taskName',
          key: 'taskName',
        },
        {
          title: '任务描述',
          dataIndex: 'taskDescription',
          key: 'taskDescription',
        },
        {
          title: '任务类型',
          dataIndex: 'taskType',
          key: 'taskType',
        },
        {
          title: '生效开始时间',
          dataIndex: 'startDate',
          key: 'startDate',
        },
        {
          title: '生效结束时间',
          dataIndex: 'endDate',
          key: 'endDate',
        },
        {
          title: '接收人',
          dataIndex: 'receiveUserNames',
          key: 'receiveUserNames',
        },
        {
          title: '接收用户组',
          dataIndex: 'receiveGroupNames',
          key: 'receiveGroupNames',
        },
        {
          title: '状态',
          dataIndex: 'taskStatus',
          key: 'taskStatus',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          width: 210,
          fixed: 'right',
        },
      ].map(item => ({ ...item, align: 'center' })),
      pagination: {
        total: 0,
        per_page: Common.pageSize, // required
        current_page: 1, // required
        last_page: 0, // required
      },
      step: 1,
      loading: false,
      modal: false,
      selectTaskDefineId: null,
      taskDefineDto: {
        id: null,
        taskName: null, //任务名称
        taskDescription: null, //任务描述
        httpRequestUrl: null, //http请求地址
        httpRequestParam: null, //http请求参数
        processReportNo: null, //流程报表文件编码
        processReportName: null, //流程报表名称
        cron: null, //cron表达式
        selectedTaskType: null, //选择的任务类型
        selectedTimeType: null, //选择的时间类型
        selectedRequestType: null, //选择的http请求类型
        selectedUser: null, //选择的用户
        selectedGroup: null, //选择的用户组
        selectedStatus: {
          value: '启用',
        }, //选择的状态
        timeoutAlarm: false, //是否超时报警
        timeout: null, //超时时间
        timeoutTermination: false, //是否超时终止
        failureAlarm: false, //是否失败报警
        selectedAlarmUser: null, //选择的报警联系人
        processNo: null,
        processParam: null,
      },
      processNos: [],
      taskTypes: [
        {
          value: '流程',
        },
        {
          value: 'HTTP任务',
        },
        {
          value: '流程报表',
        },
      ],
      timeTypes: [
        {
          value: 'none',
        },
        {
          value: 'cron',
        },
      ],
      requestTypes: [
        {
          value: 'get',
        },
        {
          value: 'post',
        },
      ],
      users: [],
      status: [
        {
          value: '启用',
        },
        {
          value: '禁用',
        },
      ],
      groups: [],
      taskDefineDtos: [], //表格数据
      visible: false,
    };
  },

  mounted: function () {
    var _self = this;
    _self.loadProcess();
    _self.getAllUsers();
    _self.getAllGroups();
    _self.getAllTaskDefineDtos();
    $('.fixed-table').tableFixer({
      left: 3,
      head: true,
    });

    $('.fixed-table').colResizable({
      resizeMode: 'overflow',
      partialRefresh: true,
    });
  },

  methods: {
    getPageParams: function (start, length) {
      this.pagination.current_page = start;
      this.pagination.per_page = length;
      this.getAllTaskDefineDtos();
    },
    // 打开编辑或新建抽屉
    showDrawer: function () {
      var _self = this;
      _self.visible = true;
      _self.processDatas = [];
      _self.restore();
    },

    // 获取流程编号
    loadProcess: function () {
      const _self = this;
      _self.processNos = [];
      $.ajax({
        url: Common.getApiURL('ProcessEditResource/list'),
        type: 'get',
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if (data.errorCode == 0) {
            data.datas.forEach(item => {
              _self.processNos.push({
                value: item.no,
                label: item.no + '-' + item.name,
              });
            });
          } else {
            message.warning(data.errorMessage);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    // 流程编号改变获取流程参数
    processNoChang: function (value) {
      const _self = this;
      _self.processDatas = [];
      const params = { processNo: value };
      $.ajax({
        url: Common.getApiURL('ProcessEditResource/uniqueByNo'),
        type: 'get',
        data: params,
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if (data.errorCode == 0) {
            if (data.data && data.data.globalProperty) {
              let jsonStr = JSON.stringify(data.data);
              let datas = JSON.parse(jsonStr);
              let globalProperty  = JSON.parse(datas.globalProperty);
              if(globalProperty.variables && globalProperty.variables.length>0){
                _self.processDatas = globalProperty.variables;
              }
            }
          } else {
            message.warning(data.errorMessage);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    // 更新表格数据
    tableDataChange: function (record, paramName) {
      var _self = this;
      var row = _self.deepClone(record.value);
      var datas = _self.deepClone(_self.processDatas);
      datas.forEach(item => {
        if (item.key == row.key) {
          item[paramName] = row[paramName];
        }
      });
      _self.processDatas = datas;
    },

    loadTaskTemplate: function () {
      $.ajax({
        url: Common.getApiURL('TaskDefineResource/generateTask'),
        type: 'get',
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if (data.errorCode == 0) {
            message.success(data.errorMessage);
          } else {
            message.warning(data.errorMessage);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    // changeCron: function (value) {
    //   var _self = this;
    //   _self.taskDefineDto.cronExpression = value;
    // },
    manualExecutionProcess: function (taskDefineId) {
      var _self = this;
      _self.loading = true;
      TaskDefineResource.manualExecutionProcess(taskDefineId).then(
        successData => {
          _self.loading = false;
          if (successData) {
            if (successData.errorCode == 0) {
              Notify.success('执行成功', successData.errorMessage, false);
            } else {
              Notify.error('执行失败', successData.errorMessage, false);
            }
          }
        },
        errorData => {
          _self.loading = false;
          Common.processException(errorData);
        },
      );
    },
    updateStatus: function (item, status) {
      TaskDefineResource.updateStatus(item.id, status).then(
        successData => {
          if (successData) {
            if (successData.errorCode == 0) {
              Notify.success('成功', successData.errorMessage, false);
              item.taskStatus = status;
            } else {
              Notify.error('失败', successData.errorMessage, false);
            }
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },
    deleteTaskBefore: function (item) {
      var _self = this;
      if (item.taskStatus == 'ENABLE') {
        Notify.error('错误', '启用状态下不能删除', false);
        return;
      }
      _self.selectTaskDefineId = item.id;
      _self.modal = true;
    },
    deleteTask: function () {
      var _self = this;
      _self.modal = false;
      TaskDefineResource.deleteTaskDefine(_self.selectTaskDefineId).then(
        successData => {
          if (successData) {
            if (successData.errorCode == 0) {
              Notify.success('成功', successData.errorMessage, false);
              _self.getAllTaskDefineDtos();
            } else {
              Notify.error('失败', successData.errorMessage, false);
            }
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },
    edit: function (item) {
      var _self = this;
      if (item.taskStatus == 'ENABLE') {
        Notify.error('错误', '启用状态下不能对任务进行编辑', false);
        return;
      }
      // console.log(item);
      _self.taskDefineDto.id = item.id;
      _self.taskDefineDto.taskName = item.taskName;
      _self.taskDefineDto.taskDescription = item.taskDescription;
      _self.taskDefineDto.httpRequestUrl = item.httpRequestUrl;
      _self.taskDefineDto.httpRequestParam = item.httpRequestParam;
      _self.taskDefineDto.processReportNo = item.processReportNo;
      _self.taskDefineDto.processReportName = item.processReportName;
      _self.taskDefineDto.cron = item.cronExpression;
      if (item.taskType == 'HTTP') {
        _self.taskDefineDto.selectedTaskType = {
          value: 'HTTP任务',
        };
      } else if (item.taskType == 'PROCESS_REPORT') {
        _self.taskDefineDto.selectedTaskType = {
          value: '流程报表',
        };
      } else if (item.taskType == 'PROCESS') {
        _self.taskDefineDto.processNo = item.processNo;
        _self.processDatas = JSON.parse(item.processParam);
        _self.taskDefineDto.selectedTaskType = {
          value: '流程',
        };
      }
      if (item.taskTimeType == 'NONE') {
        _self.taskDefineDto.selectedTimeType = {
          value: 'none',
          cron: null,
        };
        item.cronExpression = null;
      } else if (item.taskTimeType == 'CRON') {
        _self.taskDefineDto.selectedTimeType = {
          value: 'cron',
        };
      }
      if (item.httpRequestType == 'GET') {
        _self.taskDefineDto.selectedRequestType = {
          value: 'get',
        };
      } else if (item.httpRequestType == 'POST') {
        _self.taskDefineDto.selectedRequestType = {
          value: 'post',
        };
      }
      if (item.receiveUserIds != null && item.receiveUserIds.length > 0) {
        var selectedUsers = [];
        for (var i = 0; i < item.receiveUserIds.length; i++) {
          var receiveUserId = item.receiveUserIds[i];
          var recriveUserName = _self.getUserName(receiveUserId);
          var selectedUser = {
            id: receiveUserId,
            value: recriveUserName,
          };
          selectedUsers.push(selectedUser);
        }
        _self.taskDefineDto.selectedUser = selectedUsers;
      } else {
        _self.taskDefineDto.selectedUser = null;
      }
      if (item.receiveGroupIds != null && item.receiveGroupIds.length > 0) {
        var selectedGroups = [];
        for (var j = 0; j < item.receiveGroupIds.length; j++) {
          var receiveGroupId = item.receiveGroupIds[j];
          var receiveGroupName = _self.getGroupName(receiveGroupId);
          var selectedGroup = {
            id: receiveGroupId,
            value: receiveGroupName,
          };
          selectedGroups.push(selectedGroup);
        }
        _self.taskDefineDto.selectedGroup = selectedGroups;
      } else {
        _self.taskDefineDto.selectedGroup = null;
      }
      if (item.taskStatus == 'ENABLE') {
        _self.taskDefineDto.selectedStatus = {
          value: '启用',
        };
      } else if (item.taskStatus == 'DISABLE') {
        _self.taskDefineDto.selectedStatus = {
          value: '禁用',
        };
      }
      _self.taskDefineDto.timeoutAlarm = item.timeOutAlarm;
      _self.taskDefineDto.timeout = item.timeOut;
      _self.taskDefineDto.timeoutTermination = item.timeoutTermination;
      _self.taskDefineDto.failureAlarm = item.failureAlarm;
      if (item.alarmUserIds != null && item.alarmUserIds.length > 0) {
        var selectedAlarmUsers = [];
        for (var k = 0; k < item.alarmUserIds.length; k++) {
          var alarmUserId = item.alarmUserIds[k];
          var alarmUserName = _self.getUserName(alarmUserId);
          var selectedAlarmUser = {
            id: alarmUserId,
            value: alarmUserName,
          };
          selectedAlarmUsers.push(selectedAlarmUser);
        }
        _self.taskDefineDto.selectedAlarmUser = selectedAlarmUsers;
      } else {
        _self.taskDefineDto.selectedAlarmUser = null;
      }
      _self.visible = true;
    },
    getUserName: function (id) {
      var userName = '';
      var _self = this;
      for (var i = 0; i < _self.users.length; i++) {
        var user = _self.users[i];
        if (user.id == id) {
          userName = user.value;
          break;
        }
      }
      return userName;
    },
    getGroupName: function (id) {
      var groupName = '';
      var _self = this;
      for (var i = 0; i < _self.groups.length; i++) {
        var group = _self.groups[i];
        if (group.id == id) {
          groupName = group.value;
          break;
        }
      }
      return groupName;
    },
    restore: function () {
      var _self = this;
      _self.step = 1;
      _self.selectTaskDefineId = null;
      _self.taskDefineDto = {
        id: null,
        taskName: null, //任务名称
        taskDescription: null, //任务描述
        httpRequestUrl: null, //http请求地址
        httpRequestParam: null, //http请求参数
        processReportNo: null, //流程报表文件编码
        processReportName: null, //流程报表名称
        cron: null, //cron表达式
        selectedTaskType: null, //选择的任务类型
        selectedTimeType: null, //选择的时间类型
        selectedRequestType: null, //选择的http请求类型
        selectedUser: null, //选择的用户
        selectedGroup: null, //选择的用户组
        selectedStatus: {
          value: '启用',
        }, //选择的状态
        timeoutAlarm: false, //是否超时报警
        timeout: null, //超时时间
        timeoutTermination: false, //是否超时终止
        failureAlarm: false, //是否失败报警
        selectedAlarmUser: null, //选择的报警联系人
      };
    },
    getAllTaskDefineDtos: function () {
      var _self = this;
      var taskDefineSelectRequest = {
        id: null,
        taskName: null,
        taskDescription: null,
        start: (this.pagination.current_page - 1) * this.pagination.per_page,
        length: this.pagination.per_page,
      };
      _self.taskDefineDtos.splice(0, _self.taskDefineDtos.length);
      TaskDefineResource.getAllTaskDefine(taskDefineSelectRequest).then(
        successData => {
          // console.log(successData);
          if (successData && successData.errorCode == 0) {
            _self.taskDefineDtos = successData.datas;
            _self.pagination.total = successData.total;
            // _self.pagination.last_page = Math.ceil(
            //   successData.total / _self.pagination.per_page,
            // );
          }
          // _self.fixedTableHeader();
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },
    /**
     * 保存任务流程
     */
    saveTaskProcess: function () {
      var _self = this;
      if (_self.taskDefineDto.selectedTaskType.value == 'HTTP任务') {
        _self.taskDefineDto.processReportNo = null;
        _self.taskDefineDto.processReportName = null;
        _self.taskDefineDto.processNo = null;
        _self.processDatas = [];
      } else if (_self.taskDefineDto.selectedTaskType.value == '流程报表') {
        _self.taskDefineDto.selectedRequestType = null;
        _self.taskDefineDto.httpRequestUrl = null;
        _self.taskDefineDto.httpRequestParam = null;
        _self.taskDefineDto.processNo = null;
        _self.processDatas = [];
      } else if (_self.taskDefineDto.selectedTaskType.value == '流程') {
        _self.taskDefineDto.processReportNo = null;
        _self.taskDefineDto.processReportName = null;
        _self.taskDefineDto.selectedRequestType = null;
        _self.taskDefineDto.httpRequestUrl = null;
        _self.taskDefineDto.httpRequestParam = null;
        _self.taskDefineDto.selectedUser = [];
        _self.taskDefineDto.selectedGroup = [];
      }
      if (_self.processDatas && _self.processDatas.length > 0) {
        _self.taskDefineDto.processParam = JSON.stringify(_self.processDatas);
      } else {
        _self.taskDefineDto.processParam = null;
      }
      var receiveUserIds = [];
      if (
        _self.taskDefineDto.selectedUser != null &&
        _self.taskDefineDto.selectedUser.length > 0
      ) {
        _self.taskDefineDto.selectedUser.forEach(function (item) {
          receiveUserIds.push(item.id);
        });
      }
      var receiveGroupIds = [];
      if (
        _self.taskDefineDto.selectedGroup != null &&
        _self.taskDefineDto.selectedGroup.length > 0
      ) {
        _self.taskDefineDto.selectedGroup.forEach(function (item) {
          receiveGroupIds.push(item.id);
        });
      }
      var alarmUserIds = [];
      if (
        _self.taskDefineDto.selectedAlarmUser != null &&
        _self.taskDefineDto.selectedAlarmUser.length > 0
      ) {
        _self.taskDefineDto.selectedAlarmUser.forEach(function (item) {
          alarmUserIds.push(item.id);
        });
      }
      var httpRequestType = null;
      if (_self.taskDefineDto.selectedRequestType != null) {
        httpRequestType = _self.taskDefineDto.selectedRequestType.value;
      }
      var requestDto = {
        id: _self.taskDefineDto.id,
        taskName: _self.taskDefineDto.taskName,
        taskDescription: _self.taskDefineDto.taskDescription,
        receiveUserIds: receiveUserIds,
        receiveGroupIds: receiveGroupIds,
        taskType: _self.taskDefineDto.selectedTaskType.value,
        processReportNo: _self.taskDefineDto.processReportNo,
        processReportName: _self.taskDefineDto.processReportName,
        httpRequestType: httpRequestType,
        httpRequestUrl: _self.taskDefineDto.httpRequestUrl,
        httpRequestParam: _self.taskDefineDto.httpRequestParam,
        taskTimeType: _self.taskDefineDto.selectedTimeType.value,
        cronExpression: _self.taskDefineDto.cron,
        timeOutAlarm: _self.taskDefineDto.timeoutAlarm,
        timeOut: _self.taskDefineDto.timeout,
        timeoutTermination: _self.taskDefineDto.timeoutTermination,
        failureAlarm: _self.taskDefineDto.failureAlarm,
        alarmUserIds: alarmUserIds,
        taskStatus: _self.taskDefineDto.selectedStatus.value,
        processNo: _self.taskDefineDto.processNo,
        processParam: _self.taskDefineDto.processParam,
      };
      if (_self.taskDefineDto.selectedTaskType.value == '流程') {
        requestDto.taskType = '流程任务';
      }
      TaskDefineResource.saveTaskDefine(requestDto).then(
        successData => {
          if (successData) {
            if (successData.errorCode == 0) {
              Notify.success('成功', successData.errorMessage, 2000);
            } else {
              Notify.error('失败', successData.errorMessage, false);
            }
            _self.restore();
            _self.getAllTaskDefineDtos();
            _self.visible = false;
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },
    // 第一步检查
    stepCheck1: function () {
      var _self = this;
      var response = {
        errorCode: 0,
        errorMessage: '',
      };
      if (
        _self.taskDefineDto.taskName == null ||
        _self.taskDefineDto.taskName.trim().length == 0
      ) {
        response.errorCode = 1;
        response.errorMessage = '请填写任务名称';
        return response;
      }
      if (
        _self.taskDefineDto.taskDescription == null ||
        _self.taskDefineDto.taskDescription.trim().length == 0
      ) {
        response.errorCode = 2;
        response.errorMessage = '请填写任务描述';
        return response;
      }
      if (_self.taskDefineDto.selectedTaskType == null) {
        response.errorCode = 3;
        response.errorMessage = '请选择任务类型';
        return response;
      } else {
        if (_self.taskDefineDto.selectedTaskType.value == 'HTTP任务') {
          if (_self.taskDefineDto.selectedRequestType == null) {
            response.errorCode = 4;
            response.errorMessage = '请选择HTTP请求类型';
            return response;
          }
          if (
            _self.taskDefineDto.httpRequestUrl == null ||
            _self.taskDefineDto.httpRequestUrl.trim().length == 0
          ) {
            response.errorCode = 5;
            response.errorMessage = '请填写HTTP请求地址';
            return response;
          }
        } else if (_self.taskDefineDto.selectedTaskType.value == '流程报表') {
          if (
            _self.taskDefineDto.processReportNo == null ||
            _self.taskDefineDto.processReportNo.trim().length == 0
          ) {
            response.errorCode = 6;
            response.errorMessage = '请填写流程报表文件编码';
            return response;
          }
          if (
            _self.taskDefineDto.processReportName == null ||
            _self.taskDefineDto.processReportName.trim().length == 0
          ) {
            response.errorCode = 7;
            response.errorMessage = '请填写流程报表名称';
            return response;
          }
        } else if (_self.taskDefineDto.selectedTaskType.value == '流程'){
          if (!_self.taskDefineDto.processNo){
            response.errorCode = 8;
            response.errorMessage = '请选择流程编号';
            return response;
          }
          if(_self.processDatas.length == 0){
            response.errorCode = 9;
            response.errorMessage = '请添加流程参数';
            return response;
          }
        }
      }
      return response;
    },
    // 第二步检查
    stepCheck2: function () {
      var _self = this;
      var response = {
        errorCode: 0,
        errorMessage: '',
      };
      if (_self.taskDefineDto.selectedTimeType == null) {
        response.errorCode = 1;
        response.errorMessage = '请选择时间类型';
        return response;
      } else {
        if (_self.taskDefineDto.selectedTimeType.value == 'cron') {
          if (
            _self.taskDefineDto.cron == null ||
            _self.taskDefineDto.cron.trim().length == 0
          ) {
            response.errorCode = 2;
            response.errorMessage = '请填写cron表达式';
            return response;
          }
        }
      }
      return response;
    },
    // 第三步检查
    stepCheck3: function () {
      var _self = this;
      var response = {
        errorCode: 0,
        errorMessage: '',
      };
      if (_self.taskDefineDto.timeoutAlarm == true) {
        if (_self.taskDefineDto.timeout == null) {
          response.errorCode = 1;
          response.errorMessage = '请填写超时时间';
          return response;
        }
      }
      return response;
    },
    // 第四步检查
    stepCheck4: function () {
      var _self = this;
      var response = {
        errorCode: 0,
        errorMessage: '',
      };
      if (_self.taskDefineDto.selectedStatus == null) {
        response.errorCode = 1;
        response.errorMessage = '请设置任务状态';
        return response;
      }
      return response;
    },
    /**
     * 保存校验
     */
    saveCheck: function () {
      var _self = this;
      var response = null;
      if (_self.step == 1) {
        response = _self.stepCheck1();
      } else if (_self.step == 2) {
        response = _self.stepCheck2();
      } else if (_self.step == 3) {
        response = _self.stepCheck3();
      } else if (_self.step == 4) {
        response = _self.stepCheck4();
      }
      if (response.errorCode > 0) {
        Notify.error('错误', response.errorMessage, false);
        return;
      } else {
        if (_self.step == 4) {
          _self.saveTaskProcess();
        } else {
          _self.step = _self.step + 1;
        }
      }
    },
    /**
     * 冻结表头
     */
    // fixedTableHeader: function () {
    //   const _self = this;
    //   _self.$nextTick(function () {
    //     $('.fixed-table').tableFixer({
    //       left: 3,
    //       head: true,
    //     });
    //   });
    // },
    /**
     * 查询所有用户
     */
    getAllUsers: function () {
      var _self = this;
      _self.users.splice(0, _self.users.length);
      UserResource.getAllUsers().then(
        successData => {
          if (successData && successData.errorCode == 0) {
            successData.datas.forEach(function (item) {
              var user = {
                id: item.id,
                value: item.name,
              };
              _self.users.push(user);
            });
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },
    /**
     * 查询所有用户组
     */
    getAllGroups: function () {
      var _self = this;
      _self.groups.splice(0, _self.groups.length);
      GroupResource.getGroupByClient().then(
        successData => {
          if (successData) {
            successData.forEach(function (item) {
              var group = {
                id: item.id,
                value: item.name,
              };
              _self.groups.push(group);
            });
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },
    // 深拷贝
    deepClone: function (obj) {
      const _self = this;
      if (typeof obj !== 'object' || obj == null) {
        return obj;
      }
      let result = Array.isArray(obj) ? [] : {};
      for (let key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          result[key] = _self.deepClone(obj[key]);
        }
      }
      return result;
    },
  },
};
</script>

<style scoped>
.fixed-table {
  table-layout: fixed;
  width: 1150px !important;
  min-width: 1150px !important;
}
#create {
  width: 65%;
}
</style>