TimingTask.vue 28.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
<!-- 定时任务 -->
<template style="background:#e6ebf5;z-index:100;">
  <div class="app-container">
    <!-- 标题 -->
    <div class="main-title" style="padding:10px 0;">
        <i class="el-icon-date" style="color:#1890ff"></i>
        <span style="padding:0 10px;">定时任务</span>
    </div>
    <!-- 分割线 -->
    <div class="border-line"></div>
    <!-- 表单查询条件 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      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
        label="任务地址"
        prop="jobAddr"
      >
        <el-input
          v-model="queryParams.jobAddr"
          placeholder="请输入任务地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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-button
          icon="el-icon-refresh-right"
          size="mini"
          @click="handleRefresh"
        >刷新</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作栏 -->
    <el-row
      id="operDom"
      :gutter="10"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="ExportExcel"
        >生成模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>
    <!-- 表格分页列表 -->
    <el-table
       v-loading="loading"
      :data="showData"
      :height="tableHeight"
      @selection-change="handleSelectionChange"
      style="width:100%"
      v-tableHeight="{bottomOffset:60}"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        label="任务编号"
        align="center"
        prop="jobId"
      />
      <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"
        prop="jobAddr"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="执行日期"
        align="center"
        prop="jobDates"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.jobDates.length===1">{{scope.row.jobDates[0]}}</span>
          <span v-if="scope.row.jobDates.length>1">{{scope.row.jobDates.join(' , ')}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="执行时间"
        align="center"
        prop="jobTime"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="状态"
        align="center"
      >
        <template slot-scope="scope">
          <el-switch
            :value="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="250"
        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)"
          >执行一次</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleSingleDel(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleLog(scope.row)"
          >日志</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      v-show="total>0"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!-- 脚垫 -->
    <div style="height:10px;"></div>
    <!-- 添加或修改定时任务对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="700px"
      append-to-body
    >
      <el-form
        ref="addform"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="任务名称"
              prop="jobName"
            >
              <el-input
                v-model="form.jobName"
                placeholder="请输入任务名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="任务分组"
              prop="jobGroup"
            >
              <el-select
                v-model="form.jobGroup"
                placeholder="请选择"
              >
                <el-option
                  v-for="dict in jobGroupOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="任务地址"
              prop="jobAddr"
            >
              <el-input
                v-model="form.jobAddr"
                placeholder="请输入任务地址(如:C:\XXX.bat)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="执行日期"
              prop="jobDates"
            >
                <el-tooltip class="item" effect="dark" :content="datesTip" placement="top">
                    <el-date-picker
                      @change="datePickerChange"
                      style="width:100%;"
                      type="dates"
                      v-model="form.jobDates"
                      value-format="yyyy-MM-dd"
                      :picker-options="startDatePicker"
                      placeholder="选择一个或多个日期">
                    </el-date-picker>
                </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="执行时间"
              prop="jobTime"
            >
              <el-time-picker
                v-model="form.jobTime"
                :picker-options="{
                  selectableRange: '00:00:00 - 23:59:59'
                }"
                value-format="HH:mm:ss"
                placeholder="选择时间">
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </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="upload.title" :visible.sync="upload.open" :width="upload.width" append-to-body>
        <FileUpload :upload="upload" @onFileSubmit="dealFile"></FileUpload>
    </el-dialog>
  </div>
</template>

<script>
// 引入json数据库
import lowdb from 'lowdb'
import schedule from 'node-schedule'
import fileSync from 'lowdb/adapters/FileSync'
let adapter = new fileSync('db.json');
const db = lowdb(adapter);
const {shell} = require('electron')
import {create_uuid,formatDate,arrayToMap,changeArr,dateSort,trim,moment1} from '@/utils/index'
import {exportExcel} from '@/utils/excel'
import FileUpload from "@/components/FileUpload";
export default {
  name:'TimingTask',
  components: {
    FileUpload,
  },
  data () {
    return {
      tableHeight:450,
      //导入参数
      upload: {
        file:'',
        loading: false,
        // 是否显示弹出层(批量导入)
        open: false,
        // 弹出层标题(批量导入)
        title: '导入',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        width:"400px",
        ref:"upload",
        emitEventName:'onFileSubmit',
        submitErrorMsg:'导入数据不为空,请导入正常数据模板!',
        whiteList:['xlsx','xls','csv'],
        formatMsg:'仅支持xlsx、xls、csv格式',
        acceptFile:'.xlsx,.xls,.csv'
      },
      dateTime:['',''],//保存系统时间 dateTime[0] 格式 年-月-日 dateTime[1] 格式 时-分-秒 
      showData:[],//分页数据
      jobMap:{},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 定时任务表格数据
      jobList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详细弹出层
      // openView: false,
      // 任务组名字典
      jobGroupOptions: [],
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: undefined,
        jobName: undefined,
        jobAddr: undefined,
        jobGroup: undefined,
        status: undefined,
      },
      datesTip:'请选择一个或多个日期',
      // 表单参数
      form: {
        status:'1',
        jobDates:'',
        jobTime:'',
        jobName:'',
        jobGroup:'',
        jobAddr:''
      },
      // 表单校验
      rules: {
        jobName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" },
        ],
        jobGroup: [
          {
            required: true,
            message: "任务分组为必填项",
            trigger: "blur",
          },
        ],
        jobAddr: [
          {
            required: true,
            message: "任务地址为必填项",
            trigger: "blur",
          },
          { pattern: /\.bat$/, message: "任务地址输入格式有误", trigger: "blur" },
        ],
        jobDates: [
          {
            required: true,
            message: "执行日期为必填项",
            trigger: "blur",
          },
        ],
        jobTime: [
          {
            required: true,
            message: "执行时间为必填项",
            trigger: "blur",
          },
        ]
      },
    };
  },
  created () {
    db.defaults({taskDB: [],logDB:{}}).write();// 设置默认数据库taskDB 对象数组,logDB 对象Map
    this.jobGroupOptions=[
      {dictLabel:'默认',dictValue:'default'},
      {dictLabel:'系统',dictValue:'system'},
    ];
    this.statusOptions=[
      {dictLabel:'开启',dictValue:'0'},
      {dictLabel:'关闭',dictValue:'1'},
    ];
  },
  mounted () {
    // 清数据库
    // db.get('taskDB').remove().write();
    // db.unset('logDB').write();
    // 获取排序后的总数据
    this.getList();
    // 开启定时任务,每分钟执行一次
    schedule.scheduleJob('* * * * * *', ()=> {
      this.jobList = db.get('taskDB').sortBy('jobTime').value();
      this.dateTime=[moment1('YYYY-MM-DD'),moment1('HH:mm:ss')];
      for(let obj of this.jobList) {
        if(this.runFlag(obj,this.dateTime)){//满足触发条件,执行相应任务
            this.runScheduleJob(obj);
        }
      }
    });
  },
  computed:{
      startDatePicker() {//日期选择过滤 过期禁选
        return {
          disabledDate(time) {
            return (
              formatDate(time,'date') < moment1('YYYY-MM-DD')
            );
          },
        };
    },
  },
  methods: {
    ExportExcel() {//导出excel模板
      exportExcel();
    },    
    runScheduleJob(obj){
        let newObj={
          runStartTime:'',
          runEndTime:'',
          failReason:'',
          jobRangeDateTime:[],
          remark:'',
        };
        newObj.runStartTime=moment1('YYYY-MM-DD HH:mm:ss');
        // 发出通知并弹窗
        new Notification(obj.jobName+'-任务触发', {
          body: '执行任务地址:'+obj.jobAddr
        })
        // 执行子进程
          shell.openPath(obj.jobAddr.replace(/\\/g,"\\")).then((msg)=>{
            newObj.failReason=msg;
            if(newObj.failReason=='Failed to open path'){
              newObj.remark='文件打开失败,原因:找不到文件。';
            }
            newObj.runEndTime=moment1('YYYY-MM-DD HH:mm:ss');
            newObj.jobRangeDateTime=[newObj.runStartTime,newObj.runEndTime];
            // 生成执行日志记录
            newObj=Object.assign(newObj,obj)
            // console.log('newObj',newObj);
            this.saveRunLog(newObj);
          })
        // this.openServer(obj.jobAddr);
        // this.$notify({
        //   title: obj.jobName+'-触发',
        //   // duration:0,//不自动关闭
        //   duration:5000,//5秒后关闭
        //   type: 'warning',
        //   onClose:()=>{
        //     newObj.runEndTime=moment1('YYYY-MM-DD HH:mm:ss');
        //     newObj.jobRangeDateTime=[newObj.runStartTime,newObj.runEndTime]
        //     // 生成执行日志记录
        //     newObj=Object.assign(newObj,obj)
        //     this.saveRunLog(newObj);
        //   },
        // });
    },
    saveRunLog(obj){
      let resData=db.get('logDB').value()[obj.jobId];
      if(!resData){
        db.get('logDB').set(obj.jobId,[obj]).write();
      }
      else{
        resData.push(obj);
        db.get('logDB').update(obj.jobId,resData).write();
      }
    },
    runFlag(obj,dateTime){
      if(obj.jobDates.indexOf(dateTime[0])==-1){//没到这一天不触发
        // console.log('没到这一天不触发');
        return false;
      }
      else if(obj.jobTime!==dateTime[1]){//没到这个时间点不触发
        // console.log('没到这个时间点不触发');
        return false;
      }
      else if(obj.status=='1'){//开关没启动不触发
        // console.log('开关没启动不触发');
        return false;
      }
      else{
        return true;
      }
      
    },
    resetAddForm(){//清空表单
        this.form={
          status:'1',
          jobDates:'',
          jobTime:'',
          jobName:'',
          jobGroup:'',
          jobAddr:''
        };
        this.datesTip='请选择一个或多个日期';
    },
    submitForm(){//添加/修改--确定
      this.$refs['addform'].validate((valid) => {
        if (valid) {
          if(this.validDateTime(this.form)){// 数据写入前判断执行日期执行时间是否有重复
            dateSort(this.form.jobDates);
            let tmp={
                jobId:this.form.jobId?this.form.jobId:create_uuid(null,12),
                // jobDates:this.form.jobDates.join(','),
                jobDates:this.form.jobDates,
                jobName:trim(this.form.jobName),
                jobAddr:trim(this.form.jobAddr),
                jobGroup:this.form.jobGroup,
                status:this.form.status,
                jobTime:this.form.jobTime
            };
            // console.log(tmp);
            if(this.form.jobId){//编辑
              // console.log('编辑',this.form.jobId);
              db.get('taskDB').find({jobId:this.form.jobId}).assign(tmp).write();
            }
            else{//新增
              db.get('taskDB').push(tmp).write();
            }
            // this.getList();//刷新列表
            this.getList()
            // this.$refs['addform'].resetFields();
            this.resetAddForm();//清空表单
            this.$message({
                message: '操作成功',
                duration: 3000,
                type: 'success'
            });
            this.open=false;
          }
          else{
            this.$message.error('当前执行日期,执行时间已添加任务,请选择其他时间!');
            return false;
          }
        }
        else{
          this.$message.info('请检查表单填写规范!');
          return false;
        }
      })
    },
    validDateTime(obj){
      let hasJobTimeData=db.get('taskDB').map({jobTime:obj.jobTime}).value();
      if(hasJobTimeData.length>0){
        let taskDB=db.get('taskDB').sortBy('jobTime').value();
        for(let i=0;i<hasJobTimeData.length;i++){
          if(hasJobTimeData[i]===true&&taskDB[i]['jobId']!==obj.jobId&&obj.jobDates.length>0){//非编辑模式,执行时间相同判断执行日期是否包含相同项
            for(let j=0;j<obj.jobDates.length;j++){
               if(taskDB[i].jobDates.indexOf(obj.jobDates[j])!=-1){//确认存在相同执行日期 抛提示
                  return false
               }
            }
          }
        }
        return true;
      }
      else{
        return true;
      }

    },
    cancel(){
      this.open=false;
    },
    datePickerChange(val){
      this.datesTip=val.length>0?val.join(' , '):'';
    },
    /** 查询定时任务列表 */
    getList(params,fun) {
      this.loading=true;
      params=params||{
          pageNum:this.queryParams.pageNum,
          pageSize:this.queryParams.pageSize,
          type:this.queryParams.type
      }
      // console.log('mergeParams',params);
      // this.loading = true;
      this.jobMap={};//清空jobMap
      this.jobList = db.get('taskDB').sortBy('jobTime').value();
      if(params.type==='filter'){
        this.jobList=this.getFilterData(this.jobList);
      }
      this.jobMap=arrayToMap(this.jobList,'jobId');
      // console.log('this.jobMap',this.jobMap);
      this.showData=[];//清空列表
      this.total = this.jobList.length;
      if(this.total>0){
        this.jobList=changeArr(this.jobList,params.pageSize);//保存分组后的全部数据,默认一页10条
        this.showData=this.jobList[params.pageNum-1];//显示第一页数据
      }
      this.loading=false;
      if(fun){
        fun();
      }
    },
    /** 任务详细信息 */
    handleLog(row) {
      this.$router.push({name:'OperLog',params:{jobId:row.jobId}});
      sessionStorage.setItem('jobId',row.jobId);
    },
    /* 立即执行一次 */
    handleRun(row) {
      this.$confirm('确认要立即执行一次' + ' <' + row.jobName + '> '+'任务吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then( ()=> {
          // 注意如果立刻执行与其他定时任务时间不存在冲突,高并发
          // 注意执行一次与定时任务相互不影响
          // let obj=db.get('taskDB').find({jobId:row.jobId}).value();
          // if(obj.jobDates.indexOf(this.dateTime[0])===-1){//不存在 写入当前执行日期和执行时间
          //   obj.jobDates.push(this.dateTime[0]);
          //   dateSort(obj.jobDates);//给日期排序
          //   db.get('taskDB').find({jobId:row.jobId}).assign({jobDates:obj.jobDates,jobTime:this.dateTime[1]}).write();
          // }
          // else{//已存在 只写入执行时间
          //   db.get('taskDB').find({jobId:row.jobId}).assign({jobTime:this.dateTime[1]}).write();
          // }
          // this.getList(null,()=>{
          //   this.$message.success('已执行!')
          // });
          this.runScheduleJob(row);
        })
        .catch( ()=> {//取消
          // this.$message.error('操作失败!');
           this.$message.error('取消操作!');
        });
    },
    // 任务状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "停用" : "启用";
      this.$confirm(
        '确认要' + text + ' <' + row.jobName + '> '+'任务吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async()=>{
          // todo
          row.status=row.status === "0" ? "1" : "0";
          let modifyRet=db.get('taskDB').find({jobId:row.jobId}).assign({status:row.status}).write();
          if(Object.prototype.toString.call(modifyRet)=='[object Object]'){//判断返回是否为对象
            this.$message.success(text + "成功!");
            // this.getList();
          }
          else{
            this.$message.error("状态修改失败!");
          }
        }).catch(()=> {//取消
            // db.get('taskDB').find({jobId:row.jobId}).update({status:row.status === "0" ? "1" : "0"}).write();
            // this.getList();
            this.$message.error('取消操作!');
        });
    },
    selectDictLabel(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].dictValue == ('' + value)) {
          actions.push(datas[key].dictLabel);
          return true;
        }
      })
      return actions.join('');
    },
    // 任务组名字典翻译
    jobGroupFormat(row) {
      return this.selectDictLabel(this.jobGroupOptions, row.jobGroup);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.jobId);
      // this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleImport(){
      this.upload.title = '导入'
      this.upload.open = true
    },
    dealFile(data){// 处理导入的数据
      // console.log('excelData',data);
      let tmp=[];
      data.map((item)=>{
        if(item['任务名称']&&item['任务地址']){
          db.get('taskDB').push(
            {
              jobId:create_uuid(null,12),
              jobName:trim(item['任务名称']),
              jobAddr:trim(item['任务地址']),
              jobDates:[],
              jobTime:'',
              status:'1',//状态默认关闭
              jobGroup:'default'//任务组名为默认
            }
          ).write();
          tmp.push(item);
        }
      });
      if(tmp.length>0){
        this.upload.open=false;//关闭弹窗
        this.getList(null,()=>{
          this.$message.success('导入成功!');
        });
      }
      else{
        this.$message.error('模板格式有误!');
      }
    },
    handleDelete(){
      if(this.ids.length>0){
        let delArr=[];
        this.ids.map((item)=>{
          if(this.jobMap[item]){
            delArr.push(this.jobMap[item]['jobName']);
          }
        });
        this.$confirm('确定要删除'+delArr.join(' , ')+'?', '提示', { type: 'warning' }).then(
          () => {
            this.ids.map((item)=>{
              //删taskDB数据
              this.delTaskDB(item);
              //删logDB数据
              this.delLogDB(item);
              //刷新列表
              this.getList();
            });
          }
        ).then(()=>{
          this.$message.success('删除成功!');
        }).catch(()=> {//取消
          // this.$message.error('删除失败!');
           this.$message.error('取消操作!');
        });
      }
      else{
        this.$message.error('至少选择一条记录!');
      }
    },
    handleSingleDel(row){//单条删除
      this.$confirm(
        '确认要删除'+' <' + row.jobName + '> '+'任务吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(()=>{
          //删taskDB数据
          let delRet=this.delTaskDB(row.jobId);
          //删logDB数据
          this.delLogDB(row.jobId);
          if(Array.isArray(delRet)){//判断返回为数组
            this.$message.success("删除成功!");
            this.getList();
          }
          else{
            this.$message.error("删除失败!");
          }
        }).catch( ()=> {//取消
           this.$message.error('取消操作!');
        });
    },
    delTaskDB(jobId){
      return db.get('taskDB').remove({jobId:jobId}).write();
    },
    delLogDB(jobId){
      if(db.get('logDB').value()[jobId]){
        db.get('logDB').unset(jobId).write();
      }
    },
    handleUpdate(row){
      this.resetAddForm();//清空表单
      this.open=true;
      this.title="修改任务";
      this.form={
        jobId:row.jobId,
        jobName:row.jobName,
        jobGroup:row.jobGroup,
        jobAddr:row.jobAddr,
        jobDates:row.jobDates,
        jobTime:row.jobTime,
        status:row.status
      };
      this.datesTip=row.jobDates.length>0?row.jobDates.join(' , '):'请选择一个或多个日期';
    },
    handleAdd(){
      this.resetAddForm();//清空表单
      this.open=true;
      this.title="新增任务";
    },
    handleQuery(){
      this.$refs['queryForm'].validate((valid) => {
        if (valid) {
          this.queryParams.type='filter';
          this.getList()
        }
      })
    },
    getFilterData(filterData=[]){
      // 按条件一层层过滤
      //  任务名称
      if(this.queryParams['jobName']){
        filterData=filterData.filter((item)=>{return item.jobName.indexOf(this.queryParams['jobName'])!=-1});
        // console.log('filter-jobName',filterData);
      }
      // 任务组名
      if(this.queryParams['jobGroup']){
        filterData=filterData.filter((item)=>{return item.jobGroup===this.queryParams['jobGroup']});
        // console.log('filter-jobGroup',filterData);
      }
      // 执行状态
      if(this.queryParams['status']!==undefined){
        filterData=filterData.filter((item)=>{return item.status===this.queryParams['status']});
        // console.log('filter-status',filterData);
      }
      // 任务地址
      if(this.queryParams['jobAddr']){
        filterData=filterData.filter((item)=>{return item.jobAddr.indexOf(this.queryParams['jobAddr'])!=-1});
        // console.log('filter-jobAddr',filterData);
      }
      return filterData;
    },
    handleRefresh () {
      location.reload()
    },
    resetQuery () {
      this.$refs['queryForm'].resetFields()
      this.queryParams={
        pageNum: 1,
        pageSize: 10,
        type: undefined,
        jobName: undefined,
        jobAddr: undefined,
        jobGroup: undefined,
        status: undefined
      },
      this.getList()
    },
    handleSizeChange (val) {
      this.queryParams.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.queryParams.pageNum = val
      this.getList()
    },
  }
}
</script>