<template>
  <div class="app-container autocontol-job-wrap">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="任务名称" prop="jobName">
        <el-input
          v-model="queryParams.jobName"
          placeholder="请输入任务名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="任务组名" prop="jobGroup">
        <el-select v-model="queryParams.jobGroup" placeholder="请选择任务组名" clearable size="small">
          <el-option
            v-for="dict in jobGroupOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>-->
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </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="['device:job:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['device:job:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-s-operation"
          size="mini"
          @click="handleJobLog"
          v-hasPermi="['device:job:query']"
        >日志</el-button>
        <!-- <el-button size="mini" type="primary" @click="open1 = true">测试</el-button> -->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="jobList">
      <el-table-column type="index" label="序号" align="center" :index="indexFormatter" width="80px"></el-table-column>
      <el-table-column label="任务名称" align="center" prop="jobName" :show-overflow-tooltip="true" />
      <!-- <el-table-column
        label="任务组名"
        align="center"
        prop="jobGroup"
        :formatter="jobGroupFormat"
      />-->
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            v-hasPermi="['device:job:changeStatus']"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
          <span v-if="scope.row.status === '0'" style="margin-left: 5px;">正常</span>
          <span v-else>暂停</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="250px"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-caret-right"
            @click="handleRun(scope.row)"
            v-hasPermi="['device:job:changeStatus']"
          >执行一次</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:job:edit']"
          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            @click="handleDetails(scope.row)"
            v-hasPermi="['device:job:edit']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:job: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
      class="eldialog-wrap"
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="open"
      @close="detailsShow = false"
      width="880px"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务名称:" prop="jobName">
              <el-input :disabled="detailsShow" v-model="form.jobName" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="执行时间:" prop="cronExpression">
              <el-input :disabled="true" v-model="form.cronExpression" />
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <div>
              <easy-cron
                :hideSecond="false"
                :disabled="detailsShow"
                style="width: 100%;"
                v-model="form.cronExpression"
                :exeStartTime="exeStartTime"
              ></easy-cron>
            </div>
          </el-col>
          <el-col :span="24">
            <div style="margin-top: 20px;">
              <el-button
                size="mini"
                v-show="detailsShow === false"
                type="primary"
                @click="addDeviceInfo"
              >添加设备</el-button>
              <device-param-wrap
                ref="paramsWrap"
                :disabled="detailsShow"
                v-for="(item,index) in relationList"
                :tempIndex="item.guid"
                :deleteButtonD="relationList.length < 2"
                :key="item.guid"
                :appInfo="appInfo"
                :paramsDevcie="item"
                @delInfo="delInfo"
                @resultEvent="resultEvent"
                :style="item.isSubmit === false ? 'border: 1px solid #ff4949;' : ''"
              >{{item.isSubmit}}</device-param-wrap>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" v-show="detailsShow" @click="detailsShow = false">编辑</el-button>
        <el-button size="mini" type="primary" v-show="detailsShow === false" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listJob,
  getJob,
  delJob,
  addJob,
  updateJob,
  exportJob,
  runJob,
  changeJobStatus
} from "@/api/iot/deviceJob";
import EasyCron from "@/components/EasyCron";
import CronValidator from "@/components/EasyCron/validator";
// import CronValidator from './easy-cron/validator'
import DeviceParamWrap from "./profile/deviceParam";
import md5 from "js-md5";
export default {
  name: "DeviceJob",
  components: {
    EasyCron,
    DeviceParamWrap
  },
  data() {
    return {
      exeStartTime: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      open1: false,
      cronExpression: "",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 定时任务表格数据
      jobList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详细弹出层
      openView: false,
      // 任务组名字典
      jobGroupOptions: [],
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jobName: undefined,
        jobGroup: undefined,
        status: undefined
      },
      detailsShow: false,
      // 表单参数
      form: {},
      appInfo: {
        appkey: "",
        sign: "",
        timestamp: ""
      },
      intervalInfo: null,
      // 表单校验
      rules: {
        jobName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        invokeTarget: [
          { required: true, message: "调用目标字符串不能为空", trigger: "blur" }
        ],
        cronExpression: [
          // { validator: CronValidator }
        ]
      },
      relationList: [], // 设备执行关系模块列表
      updateMD5List: ""
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_job_group").then(response => {
      this.jobGroupOptions = response.data;
    });
    this.getDicts("sys_job_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    getGuid() {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(
        c
      ) {
        var r = (Math.random() * 16) | 0,
          v = c == "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    },
    delInfo(index) {
      var arr = [];
      this.relationList.forEach(v => {
        if (v.guid !== index) {
          arr.push(v);
        }
      });
      this.relationList = [];
      this.relationList = arr;
      this.$forceUpdate();
    },
    resultEvent(data) {
      for (var i = 0; i < this.form.list.length; i++) {
        if (this.form.list[i].guid === data.index) {
          this.form.list[i] = data.result;
          break;
        }
      }
    },
    addDeviceInfo() {
      this.relationList.push({
        cmdKey: "",
        deviceId: "",
        prodId: "",
        property: "",
        isSubmit: false,
        guid: this.getGuid()
      });
    },
    /** 查询定时任务列表 */
    getList() {
      this.loading = true;
      listJob(this.queryParams).then(response => {
        this.jobList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 任务组名字典翻译
    jobGroupFormat(row, column) {
      return this.selectDictLabel(this.jobGroupOptions, row.jobGroup);
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        jobName: undefined,
        invokeTarget: undefined,
        cronExpression: "0 * * * * ? *",
        misfirePolicy: 1,
        concurrent: 1,
        list: []
      };
      this.exeStartTime = this.parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}");
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.jobId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 任务状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm(
        '确认要"' + text + '""' + row.jobName + '"任务吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return changeJobStatus(row.jobId, row.status);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    /* 立即执行一次 */
    handleRun(row) {
      this.$confirm('确认要立即执行一次"' + row.jobName + '"任务吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return runJob(row.jobId, row.jobGroup);
        })
        .then(() => {
          this.msgSuccess("执行成功");
        });
    },
    /** 任务详细信息 */
    handleView(row) {
      getJob(row.jobId).then(response => {
        this.form = response.data;
        this.openView = true;
      });
    },
    /** 任务日志列表查询 */
    handleJobLog() {
      this.$router.push("/job/device/log");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.relationList = [];
      this.open = true;
      this.title = "添加任务";
    },
    // 查看详情
    handleDetails(row) {
      this.detailsShow = true;
      this.handleUpdate(row);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.updateMD5List = "";
      getJob(row.jobId).then(response => {
        this.form = response.data;
        this.relationList = this.form.list;
        this.relationList.forEach(v => {
          v.guid = this.getGuid();
        });
        this.updateMD5List = md5(JSON.stringify(this.relationList));
        this.open = true;
        this.title = "修改任务";
        // setTimeout(() =>{
        //   this.form.cronExpression = "0 1 * 10 * ? *";
        // }, 500)
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (!this.relationList || this.relationList.length <= 0) {
            this.msgError("至少需要一条设备数据！");
            return;
          }
          for (var i = 0; i < this.relationList.length; i++) {
            if (this.relationList[i]["isSubmit"] === false) {
              this.msgError(
                "至少有一条设备数未选择设备或者分组，请看红色提示字体！"
              );
              return;
            }
          }
          if (this.form.jobId != undefined) {
            const listA = [...this.relationList];
            this.form.list =
              this.updateMD5List === md5(JSON.stringify(this.relationList))
                ? []
                : this.relationList;
            updateJob(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.list = this.relationList;
            addJob(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const jobIds = row.jobId;
      this.$confirm("是否删除该选项", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delJob(jobIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有定时任务数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportJob(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    }
  }
};
</script>
<style lang="scss">
.autocontol-job-wrap {
  .exe-pre-panel .p-left {
    text-align: center;
  }
}
</style>
