<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="计划名称" prop="planName">
        <el-input v-model="queryParams.planName" placeholder="请输入计划名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="机器人名称" prop="robotName">
        <el-input v-model="queryParams.robotName" placeholder="请输入计划执行的机器人名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="应用名称" prop="appName">
        <el-input v-model="queryParams.appName" placeholder="请输入应用名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="执行类型" prop="excType">
        <el-select v-model="queryParams.excType" placeholder="请选择执行类型" clearable>
          <el-option v-for="dict in dict.type.exc_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:ctApplyPlan:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['business:ctApplyPlan:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:ctApplyPlan:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['business:ctApplyPlan:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ctApplyPlanList" @selection-change="handleSelectionChange">
      <!-- :summary-method="getSummaries" show-summary -->
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="序号" width="55" align="center" fixed="left">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="计划名称" align="center" prop="planName" width="150" />
      <el-table-column label="应用名称" align="center" prop="appName" width="250" />
      <el-table-column label="调度方式" align="center" prop="planType" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.plan_type" :value="scope.row.planType" />
        </template>
      </el-table-column>
      <el-table-column label="机器人名称" align="center" prop="robotName" width="150" />
      <el-table-column label="应用类型名称" align="center" prop="appTypeName" width="100" />
      <el-table-column label="appid" align="center" prop="appId" width="300" />
      <el-table-column label="应用类型枚举" align="center" prop="appType" width="100" />
      <el-table-column label="计划参数" align="center" prop="planParams" width="100">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p> {{ scope.row.planParams }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">显示参数</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="等待超时时间" align="center" prop="waitTimeout" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wait_timeout" :value="scope.row.waitTimeout" />
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority" width="100" />
      <el-table-column label="执行类型" align="center" prop="excType" width="200">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.exc_type" :value="scope.row.excType" />
        </template>
      </el-table-column>
      <el-table-column label="执行时间" align="center" prop="excTime" width="100" />
      <el-table-column label="执行表达式" align="center" prop="cronExpression" width="100" />
      <el-table-column label="任务执行状态" align="center" fixed="right" prop="taskStatus" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.plan_run_status" :value="scope.row.taskStatus" />
        </template>
      </el-table-column>
      <el-table-column label="上次执行时间" align="center" prop="lastExecTime" width="170" />
      <el-table-column label="下次执行时间" align="center" prop="nextExecTime" width="170" />
      <el-table-column label="任务运行uuid" align="center" prop="taskUuid" width="300" />
      <el-table-column label="开始时间" align="center" fixed="right" prop="startTime" width="100" />
      <el-table-column label="结束时间" align="center" fixed="right" prop="endTime" width="100" />
      <el-table-column label="人工耗时" align="center" fixed="right" prop="manualTime" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.manualTime }} 分钟</span>
        </template>
      </el-table-column>
      <el-table-column label="实际耗时" align="center" fixed="right" prop="planTime" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.planTime != null">{{ scope.row.planTime }} 分钟</span>
        </template>
      </el-table-column>
      <el-table-column label="节约时间" align="center" fixed="right" prop="timeSaving" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.timeSaving != null">{{ scope.row.timeSaving }} 分钟</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" fixed="right" prop="createBy" width="100" />
      <el-table-column label="创建时间" align="center" fixed="right" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" width="200" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" v-if="scope.row.taskStatus == 'await_create' && scope.row.supportParam != 0"
            type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:ctApplyPlan:edit']">设置参数</el-button>
          <el-button size="mini" v-if="scope.row.taskStatus == 'await_create'" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)" v-hasPermi="['business:ctApplyPlan:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:ctApplyPlan:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改应用执行计划管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="form.planName" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调度方式" prop="planType">
              <el-select v-model="form.planType" placeholder="请选择调度方式">
                <el-option v-for="dict in dict.type.plan_type" :key="dict.value" :label="dict.label"
                  :disabled="dict.value == 0" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="应用名称" prop="appName">
              <el-select v-model="form.appId" multiple filterable collapse-tags style="margin-left: 20px;"
                placeholder="请选择机器人">
                <el-option v-for="apply in applyList" :key="apply.appId" :label="apply.appName" :value="apply.appId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="等待超时时间" prop="waitTimeout">
              <el-select v-model="form.waitTimeout" placeholder="请选择等待超时时间">
                <el-option v-for="dict in dict.type.wait_timeout" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-input-number v-model="form.priority" label="请输入预计人工用时"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行类型" prop="excType">
              <el-select v-model="form.excType" placeholder="请选择执行类型">
                <el-option v-for="dict in dict.type.exc_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item v-if="form.excType == 1" label="执行时间" prop="excTime">
              <el-date-picker clearable v-model="form.excTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss" placeholder="请选择执行时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.excType == 2" label="cron表达式" prop="cronExpression">
              <el-input v-model="form.cronExpression" placeholder="请输入cron执行表达式">
                <template slot="append">
                  <el-button type="primary" @click="handleShowCron">
                    生成表达式
                    <i class="el-icon-time el-icon--right"></i>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="计划参数" prop="planParams">
              <el-input v-model="form.planParams" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-row :gutter="24">
              <el-col style="margin-bottom: 10px;" :span="24"><el-button type="primary" size="mini"
                  @click="showAddParam">添加参数</el-button></el-col>
              <el-col :span="24"><el-button type="primary" size="mini" @click="clearAddParam">清空参数</el-button></el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="Cron表达式生成器" :visible.sync="openCron" append-to-body destroy-on-close class="scrollbar">
      <crontab @hide="openCron=false" @fill="crontabFill" :expression="expression"></crontab>
    </el-dialog>

    <!-- 添加参数 -->
    <el-dialog title="添加参数" :visible.sync="addParamVisible" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="参数类型" prop="type">
              <el-select v-model="param.type" placeholder="请选择参数类型">
                <el-option v-for="dict in dict.type.app_param_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>

            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="参数键" prop="name">
              <el-input v-model="param.name" type="text" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col v-if="param.type == null || param.type == 'str'" :span="8">
            <el-form-item label="参数值" prop="value">
              <el-input v-model="param.value" type="text" placeholder="请输入参数值" />
            </el-form-item>
          </el-col>
          <el-col v-if="param.type == 'int'" :span="8">
            <el-form-item label="参数值" prop="value">
              <el-input-number v-model="param.value" :precision="0" placeholder="请输入参数值"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col v-if="param.type == 'float'" :span="8">
            <el-form-item label="参数值" prop="value">
              <el-input-number v-model="param.value" :precision="2" placeholder="请输入参数值"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col v-if="param.type == 'bool'" :span="8">
            <el-form-item label="参数值" prop="value">
              <el-switch v-model="param.value" active-text="真" inactive-text="假" active-value="true"
                inactive-value="false" />
            </el-form-item>
          </el-col>
          <el-col v-if="param.type == 'file'" :span="8">
            <el-form-item label="参数值" prop="value">
              <file-upload v-model="param.value" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addParam">确 定</el-button>
        <el-button @click="addParamVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCtApplyPlan, getCtApplyPlan, delCtApplyPlan, addCtApplyPlan, updateCtApplyPlan } from "@/api/business/ctApplyPlan";
import { listRebotAll } from "@/api/business/ctRebot";
import { listApplyAll } from "@/api/business/ctApply";
import Crontab from '@/components/Crontab'


export default {
  components: { Crontab },
  name: "CtApplyPlan",
  dicts: ['plan_type', 'wait_timeout', , 'exc_type', 'plan_run_status', 'app_param_type'],
  data() {
    return {
      // 是否显示Cron表达式弹出层
      openCron: false,
      // 传入的表达式
      expression: "",
      // 添加参数
      addParamVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应用执行计划管理表格数据
      ctApplyPlanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planName: null,
        planType: null,
        robotName: null,
        appTypeName: null,
        appName: null,
        appId: null,
        appType: null,
        manualTime: null,
        planParams: null,
        waitTimeout: null,
        priority: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 机器人列表
      rebotList: [],
      // 应用列表
      applyList: [],
      // 参数集
      params: [],
      // 单个参数对象
      param: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 添加参数
    addParam() {
      this.params.push(this.param);
      this.form.planParams = JSON.stringify(this.params);
      this.addParamVisible = false;
    },
    // 清空参数
    clearAddParam() {
      this.form.planParams = ''
      this.params = [];
      this.param = {};
    },
    // 打开添加参数
    showAddParam() {
      this.addParamVisible = true;
      this.param = {};
    },
    /** 查询应用执行计划管理列表 */
    getList() {
      this.loading = true;
      listCtApplyPlan(this.queryParams).then(response => {
        this.ctApplyPlanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询所有应用 */
    listAll() {
      this.listRebotAll();
      this.listApplyAll();
    },
    /** 查询所有可用机器人 */
    listRebotAll() {
      listRebotAll({}).then(res => {
        this.rebotList = res.data;
      });

    },
    /** 查询应用 */
    listApplyAll() {
      listApplyAll({}).then(res => {
        this.applyList = res.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        planName: null,
        planType: null,
        robotName: null,
        appTypeName: null,
        appName: null,
        appId: null,
        appType: null,
        manualTime: null,
        planParams: null,
        waitTimeout: null,
        priority: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        deleted: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.listAll();
      this.open = true;
      this.title = "添加应用执行计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.listAll();
      const id = row.id || this.ids
      getCtApplyPlan(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改应用执行计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCtApplyPlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCtApplyPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除应用执行计划管理编号为"' + ids + '"的数据项？').then(function () {
        return delCtApplyPlan(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/ctApplyPlan/export', {
        ...this.queryParams
      }, `ctApplyPlan_${new Date().getTime()}.xlsx`)
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计时间';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 分钟';
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },
    /** cron表达式按钮操作 */
    handleShowCron() {
      this.expression = this.form.cronExpression;
      this.openCron = true;
    },
    /** 确定后回传值 */
    crontabFill(value) {
      this.form.cronExpression = value;
    },
  }
};
</script>