<template>
  <div class="periodictasks_container body_container">
    <a-spin :spinning="loading">
      <a-row>
        <a-col :span="19">
          <span class="search_label first"> 任务名称：</span>
          <a-input-search
            class="middle"
            allowClear
            v-model="pager.queryParams.F_jobDesc_like"
            placeholder="请输入任务名称"
            @search="querySearch"
          />
          <span class="search_label"> 任务类型：</span>
          <a-select
            allowClear
            class="middle"
            placeholder="请选择"
            v-model="appType"
            :options="appTypeList"
            @change="querySearch"
          >
          </a-select>
          <span class="search_label">
            <a-checkbox @change="changeDelList">已删除</a-checkbox>
          </span>
        </a-col>
        <a-col :span="5" align="right">
          <template v-if="pager.queryParams.F_scheduleType_eq == 'CRON'">
            <a-button type="primary" icon="profile" @click="batchScheduleConf"
              >设置周期</a-button
            >
            &nbsp;
          </template>
          <template v-if="pager.queryParams.F_scheduleType_eq == 'REALTIME'">
            <a-button type="primary" icon="profile" @click="batchStartTasks"
              >批量启动</a-button
            >
            &nbsp;
          </template>
          <a-button type="primary" icon="plus" @click="editFlow('')"
            >新增</a-button
          >
        </a-col>
      </a-row>
      <a-row class="filter_list">
        <a-col :span="24">
          <span class="search_label first"> 运行状态：</span>
          <a-select
            allowClear
            class="middle"
            placeholder="请选择"
            v-model="pager.queryParams.F_triggerStatus_eq"
            :options="statusList"
            @change="querySearch"
          >
          </a-select>
          <span class="search_label"> JobHandler：</span>
          <a-select
            allowClear
            class="middle"
            placeholder="请选择"
            :dropdownMatchSelectWidth="false"
            dropdownClassName="handler-select-dropdown"
            v-model="pager.queryParams.F_executorHandler_eq"
            :options="HandlerList"
            @change="querySearch"
          >
          </a-select>
        </a-col>
      </a-row>
      <div class="table_list" ref="listCont">
        <vxe-table
          ref="tableList"
          show-overflow
          show-header-overflow
          border
          resizable
          :row-config="{ isHover: true }"
          :checkbox-config="{ checkMethod: checkboxType }"
          :data="lists"
          :key="pager.queryParams.F_scheduleType_eq"
          height="auto"
        >
          <vxe-column
            type="checkbox"
            field="checkbox"
            width="60"
            align="center"
            key="checkbox"
            v-if="
              pager.queryParams.F_scheduleType_eq == 'REALTIME' ||
              pager.queryParams.F_scheduleType_eq == 'CRON'
            "
          ></vxe-column>
          <vxe-column
            type="seq"
            field="seq"
            title="序号"
            width="60"
            align="center"
            key="seq"
          ></vxe-column>
          <vxe-column field="jobDesc" title="任务名称" min-width="180">
          </vxe-column>
          <vxe-column field="jobType" title="任务类型" min-width="110">
            <template #default="{ row }">
              {{ appTypeListForRow(row.jobType) }}
            </template>
          </vxe-column>
          <vxe-column
            field="scheduleConf"
            title="调度周期"
            v-if="pager.queryParams.F_scheduleType_eq == 'CRON'"
            min-width="220"
          >
            <template #default="{ row }">
              {{ row.translateScheduleConf }}
            </template>
          </vxe-column>
          <vxe-column field="createBy" title="负责人" width="110"> </vxe-column>
          <vxe-column field="triggerStatus" title="状态" min-width="110">
            <template #default="{ row }">
              <a-tag v-if="row.triggerStatus == 1" class="tag_value"
                >运行中</a-tag
              >
              <a-tag v-else class="tag_entry">已停止</a-tag>
              <!-- 数据集成-运行中显示转换列表 -->
              <template
                v-if="row.triggerStatus == 1 && row.jobType == 'transfer'"
              >
                <a-icon
                  v-if="row.allRun"
                  class="converted_icon"
                  type="check-circle"
                  title="全部转换列表"
                  @click="showConverted(row)"
                />
                <a-icon
                  v-else
                  class="converted_icon"
                  type="issues-close"
                  title="部分转换列表"
                  @click="showConverted(row)"
                />
              </template>
            </template>
          </vxe-column>
          <vxe-column title="操作" width="350" align="center" fixed="right">
            <template #default="{ row }">
              <a-button class="btn" type="link" @click="editFlow(row)"
                >编辑</a-button
              >
              <a-button class="btn" type="link" @click="toLog(row)"
                >查询日志</a-button
              >

              <template v-if="pager.queryParams.F_isDel_eq == 1">
                <a-popconfirm
                  :title="`确认要恢复[${row.jobDesc}]吗?`"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="restoreFlow(row)"
                >
                  <a-button class="btn" type="link">恢复</a-button>
                </a-popconfirm>
              </template>
              <template v-else>
                <!-- 运行中不可删除 -->
                <a-popconfirm
                  v-if="row.triggerStatus != 1"
                  :title="`确认要删除[${row.jobDesc}]吗?`"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="deleteFlow(row)"
                >
                  <a-button class="btn a_danger" type="link">删除</a-button>
                </a-popconfirm>
                <a-button
                  v-else
                  class="btn a_danger"
                  type="link"
                  @click="deleteFlow(row)"
                  >删除</a-button
                >
              </template>

              <template
                v-if="pager.queryParams.F_scheduleType_eq != 'REALTIME'"
              >
                <a-button class="btn" type="link" @click="triggerHandle(row)"
                  >执行一次</a-button
                >
              </template>
              <!-- 周期任务启动/停止 -->
              <template v-if="pager.queryParams.F_scheduleType_eq == 'CRON'">
                <a-popconfirm
                  v-if="row.triggerStatus == 1"
                  :title="`确认要停止[${row.jobDesc}]吗?`"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="statusFlow(row)"
                >
                  <a-button class="btn" type="link">停止</a-button>
                </a-popconfirm>
                <template v-else>
                  <a-popconfirm
                    v-if="row.jobType != 'transfer' && row.jobType != 'datadev'"
                    :title="`确认要启动[${row.jobDesc}]吗?`"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="statusFlow(row)"
                  >
                    <a-button class="btn" type="link">启动</a-button>
                  </a-popconfirm>
                  <a-button
                    class="btn"
                    type="link"
                    v-else
                    @click="cronStartFlow(row)"
                    >启动</a-button
                  >
                </template>
              </template>
              <!-- 实时任务启动/停止 -->
              <template
                v-if="pager.queryParams.F_scheduleType_eq == 'REALTIME'"
              >
                <a-popconfirm
                  v-if="row.triggerStatus == 1"
                  :title="`确认要停止[${row.jobDesc}]吗?`"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="stopFlow(row)"
                >
                  <a-button class="btn" type="link">停止</a-button>
                </a-popconfirm>
                <a-button
                  class="btn"
                  type="link"
                  v-if="row.triggerStatus == 0"
                  @click="realStartFlow(row)"
                  >启动</a-button
                >
              </template>
              <a-dropdown>
                <a-button class="btn" type="link"
                  >更多<a-icon style="margin-left: 0px" type="caret-down"
                /></a-button>
                <a-menu slot="overlay">
                  <a-menu-item @click="copyFlow(row)">
                    <a-icon type="copy" />复制
                  </a-menu-item>
                  <a-menu-item @click="showTxt('address', row)">
                    <a-icon type="link" />注册节点
                  </a-menu-item>
                  <a-menu-item
                    v-if="pager.queryParams.F_scheduleType_eq != 'REALTIME'"
                    @click="showTxt('trigger', row)"
                  >
                    <a-icon type="calendar" />下次执行时间
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>
          </vxe-column>
          <template #empty>
            <a-empty
              :image-style="{
                height: '80px',
              }"
            >
              <span slot="description"> 暂无数据 </span>
            </a-empty>
          </template>
        </vxe-table>
      </div>
      <vxe-pager
        background
        :current-page.sync="pager.pageNum"
        :page-size.sync="pager.pageSize"
        :total="total"
        @page-change="getFlowList"
        :layouts="['Total', 'PrevJump', 'JumpNumber', 'NextJump', 'FullJump']"
      >
      </vxe-pager>
    </a-spin>
    <a-modal
      v-model="txtFlag"
      :title="txtType == 'address' ? '注册节点' : '下次执行时间'"
      :footer="null"
      :width="300"
    >
      <template v-if="txtType == 'address'">
        <p
          style="line-height: 26px"
          v-for="(item, index) in addList"
          :key="item"
        >
          {{ index + 1 }}. {{ item }}
        </p>
      </template>
      <template v-if="txtType == 'trigger'">
        <p style="line-height: 26px" v-for="item in triggerList" :key="item">
          {{ item }}
        </p>
      </template>
    </a-modal>

    <detail
      :visible.sync="editFlag"
      :item="curData"
      :type="pager.queryParams.F_scheduleType_eq"
      @callBack="querySearch"
    ></detail>
    <converted-list
      :show.sync="convertedInfo.show"
      :info="convertedInfo.info"
    ></converted-list>
    <batchsratttask
      :show.sync="batchStart.show"
      :info="batchStart.info"
      @callback="querySearch"
    >
    </batchsratttask>
    <batchScheduleConf
      :show.sync="batchSchedule.show"
      :info="batchSchedule.info"
      @callback="querySearch"
    >
    </batchScheduleConf>
    <executeOnce
      :show.sync="triggerInfo.show"
      :info="triggerInfo.info"
      @callback="getFlowList"
    ></executeOnce>
    <cronJobStart
      :show.sync="cronStartInfo.show"
      :info="cronStartInfo.info"
      @callback="getFlowList"
    >
    </cronJobStart>
    <realtimeJobStart
      :show.sync="realStartInfo.show"
      :info="realStartInfo.info"
      @callback="getFlowList"
    ></realtimeJobStart>
  </div>
</template>
<script>
/**
 * @Author: y_zp
 * @description: 调度任务-周期任务
 */
const detail = require("./detail").default;
const selectCron = require("./components/selectcron.vue").default;
const convertedList = require("./components/convertedlist.vue").default;
const executeOnce = require("./executeonce/index.vue").default;
const cronJobStart = require("./cronjobstart/index.vue").default;
const realtimeJobStart = require("./realtimejobstart/index.vue").default;
const batchsratttask = require("./batchstarttask").default;
const batchScheduleConf = require("./batchscheduleconf").default;
const $dispatchcenter = require("@/api/dispatchcenter");
const $dataIntegration = require("@/api/dataIntegration");
const $appService = require("w-vue-middle/api/appService");

export default {
  components: {
    detail,
    selectCron,
    convertedList,
    executeOnce,
    cronJobStart,
    realtimeJobStart,
    batchsratttask,
    batchScheduleConf,
  },
  data() {
    return {
      loading: false,
      total: 1,
      appType: undefined,
      appTypeList: [],
      HandlerList: [],
      statusList: [
        {
          label: "已停止",
          value: 0,
        },
        {
          label: "运行中",
          value: 1,
        },
      ],
      pager: {
        pageNum: 1,
        pageSize: 15,
        queryParams: {
          F_jobInfoId_eq: undefined,
          F_triggerStatus_eq: undefined,
          F_jobDesc_like: undefined,
          F_executorHandler_eq: undefined,
          F_scheduleType_eq: undefined,
          F_isDel_eq: 0,
        },
      },
      lists: [],
      clusterList: [],
      editFlag: false,
      curData: {},
      txtFlag: false,
      txtType: "",
      addList: [],
      triggerList: [],
      triggerInfo: {
        show: false,
        info: {},
      },
      cronStartInfo: {
        show: false,
        info: {},
      },
      realStartInfo: {
        show: false,
        info: {},
      },
      convertedInfo: {
        show: false,
        info: {},
      },
      batchStart: {
        show: false,
        info: [],
      },
      batchSchedule: {
        show: false,
        info: [],
      },
    };
  },
  watch: {
    $route(val) {
      this.initData(val);
    },
  },
  created() {
    this.initData(this.$route);
  },
  computed: {
    appTypeListForRow(jobType) {
      return function (jobType) {
        let appType = this.appTypeList.find((item) => item.value == jobType);
        if (appType) {
          return appType.label;
        }
        return "--";
      };
    },
  },
  methods: {
    /**
     * @Author: y_zp
     * @description: 初始化
     */
    initData(val) {
      //CRON【周期】 REALTIME【实时】 MANUAL【手动】
      this.pager.queryParams.F_scheduleType_eq = val.meta.type;
      //数据质量-》作业监控-重新执行跳转此页面
      if (val.query.scheduleJobId) {
        this.pager.queryParams.F_jobInfoId_eq = val.query.scheduleJobId;
        this.pager.queryParams.F_scheduleType_eq = val.query.type;
      } else {
        this.pager.queryParams.F_jobInfoId_eq = undefined;
      }
      this.pager.pageNum = 1;
      this.getFlowList();
      this.getAppType();
      this.getHandler();
    },
    /**
     * @Author: y_zp
     * @description: 获取列表
     */
    getFlowList() {
      this.loading = true;
      $dispatchcenter
        .getJobInfo(this.pager, this.appType)
        .then((req) => {
          this.total = Number(req.count);
          this.lists = req.data;
          if (this.$route.params.scheduleJobId && this.lists.length == 0) {
            this.$message.warn("该任务已删除");
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * @Author: y_zp
     * @description: 获取任务类型列表
     */
    getAppType() {
      $appService
        .getSysDictData({
          pageNum: 1,
          pageSize: 1000000,
          queryParams: { F_dictType_eq: "job_type" },
        })
        .then((req) => {
          this.appTypeList = req.data.map((item) => {
            return {
              label: item.dictLabel,
              value: item.dictValue,
            };
          });
        });
    },
    /**
     * @Author: y_zp
     * @description: 获取JobHandler列表
     */
    getHandler() {
      $appService
        .getSysDictData({
          pageNum: 1,
          pageSize: 1000000,
          queryParams: { F_dictType_eq: "schedule_handler" },
        })
        .then((req) => {
          this.HandlerList = req.data.map((item) => {
            return {
              label: item.dictLabel,
              value: item.dictValue,
            };
          });
        });
    },

    /**
     * @Author: y_zp
     * @description: 查询
     */
    querySearch() {
      this.pager.pageNum = 1;
      this.getFlowList();
    },
    /**
     * @Author: y_zp
     * @description: 周期任务批量设置调度周期，实时任务集成作业才可批量启动
     */
    checkboxType({ row }) {
      return (
        this.pager.queryParams.F_scheduleType_eq == "CRON" ||
        (this.pager.queryParams.F_scheduleType_eq == "REALTIME" &&
          row.jobType == "transfer")
      );
    },
    /**
     * @Author: y_zp
     * @description: 批量启动
     */
    batchStartTasks() {
      let list = this.$refs.tableList.getCheckboxRecords();
      if (list.length == 0) {
        this.$message.warn("请选择数据");
        return false;
      } else {
        this.batchStart = {
          show: true,
          info: list,
        };
      }
    },
    /**
     * @Author: y_zp
     * @description: 批量设置调度周期
     */
    batchScheduleConf() {
      let list = this.$refs.tableList.getCheckboxRecords();
      if (list.length == 0) {
        this.$message.warn("请选择数据");
        return false;
      } else {
        this.batchSchedule = {
          show: true,
          info: list,
        };
      }
    },

    statusFlow(row) {
      if (row.triggerStatus == 0) {
        this.startFlow(row);
      } else {
        this.stopFlow(row);
      }
    },
    /**
     * @Author: y_zp
     * @description: 任务启用
     */
    startFlow(row) {
      $dispatchcenter
        .jobInfoStart({ jobId: row.jobInfoId })
        .then((req) => {
          this.$message.success("启动成功！");
        })
        .finally(() => {
          this.getFlowList();
        });
    },
    /**
     * @Author: y_zp
     * @description: 任务停用
     */
    stopFlow(row) {
      $dispatchcenter
        .jobInfoStop({ jobId: row.jobInfoId })
        .then((req) => {
          this.$message.success("停用成功！");
        })
        .finally(() => {
          this.getFlowList();
        });
    },
    /**
     * @Author: y_zp
     * @description: 周期任务启用
     */
    cronStartFlow(row) {
      let params = row.executorParam ? row.executorParam.split(",") : [];
      this.cronStartInfo = {
        show: true,
        info: {
          ...row,
          newJobId: params[0] || "",
          operatingMode: params[1] || "",
          clusterId: params[2] || undefined,
          otherTaskId: params[3] || "",
          transforms: [],
          executeLocation: "",
        },
      };
    },
    /**
     * @Author: y_zp
     * @description: 实时任务启用
     */
    realStartFlow(row) {
      let params = row.executorParam ? row.executorParam.split(",") : [];
      this.realStartInfo = {
        show: true,
        info: {
          ...row,
          start: undefined,
          newJobId: params[0] || "",
          operatingMode: params[1] || "",
          clusterId: params[2] || undefined,
          otherTaskId: params[3] || "",
          transforms: [],
          executeLocation: "",
        },
      };
    },

    /**
     * @Author: y_zp
     * @description: 编辑
     */
    editFlow(row) {
      this.curData = row.jobInfoId ? { ...row } : {};
      this.editFlag = true;
    },

    /**
     * @Author: y_zp
     * @description: 复制
     */
    copyFlow(row) {
      this.curData = { ...row, isCopy: "copy" };
      this.editFlag = true;
    },

    /**
     * @Author: y_zp
     * @description: 删除
     */
    deleteFlow(row) {
      if (row.triggerStatus == 1) {
        this.$message.warn(`请先停止[${row.jobDesc}]`);
        return false;
      }
      $dispatchcenter
        .deleteJobInfo({ ids: row.jobInfoId })
        .then((req) => {
          this.$message.success("删除成功！");
        })
        .finally(() => {
          this.getFlowList();
        });
    },

    /**
     * @Author: y_zp
     * @description: 注册节点/下次执行
     */
    showTxt(type, row) {
      if (type == "address") {
        this.addList = [];
        $dispatchcenter.jobExcutorDetail({ id: row.jobGroup }).then((req) => {
          this.addList = req.data.addressList.split(",");
        });
      } else {
        this.triggerList = [];
        $dispatchcenter.getJobInfoDetail(row.jobInfoId).then((req) => {
          let info = req.data;
          console.log(info);
          let { scheduleConf, scheduleType } = info;
          $dispatchcenter
            .jobInfoNextTrigger({ scheduleConf, scheduleType })
            .then((req) => {
              this.triggerList = req.data;
            });
        });
      }
      this.txtType = type;
      this.txtFlag = true;
    },

    /**
     * @Author: y_zp
     * @description: 执行一次
     */
    triggerHandle(row) {
      let params = row.executorParam ? row.executorParam.split(",") : [];
      this.triggerInfo = {
        show: true,
        info: {
          ...row,
          newJobId: params[0] || "",
          operatingMode: params[1] || "",
          clusterId: params[2] || undefined,
          otherTaskId: params[3] || "",
          transforms: [],
          executeLocation: "",
        },
      };
    },

    /**
     * @Author: y_zp
     * @description: 查询日志
     */
    toLog(row) {
      let name =
        this.pager.queryParams.F_scheduleType_eq == "REALTIME"
          ? "/realtimeTasksLog"
          : this.pager.queryParams.F_scheduleType_eq == "MANUAL"
          ? "/manualTasksLog"
          : "/periodicTasksLog";
      this.parentRouter.push({
        path: name,
        query: {
          type: this.pager.queryParams.F_scheduleType_eq,
          jobId: row.jobInfoId,
        },
      });
    },
    /**
     * @Author: y_zp
     * @description: 数据集成-运行状态，显示已转换列表
     */
    showConverted(row) {
      this.convertedInfo = {
        show: true,
        info: row,
      };
    },
    /**
     * @Author: y_zp
     * @description: 已删除切换
     */
    changeDelList(e) {
      let val = e.target.checked;
      this.pager.queryParams.F_isDel_eq = val ? 1 : 0;
      this.querySearch();
    },
    /**
     * @Author: y_zp
     * @description: 恢复数据
     */
    restoreFlow(row) {
      $dispatchcenter
        .jobInfoSave({
          ...row,
          isDel: 0,
          _X_ROW_KEY: undefined,
        })
        .then(() => {
          this.$message.success("恢复成功");
          this.getFlowList();
        });
    },
  },
};
</script>
<style lang="less">
@import "/src/themes/config.less";
.periodictasks_container {
  .search_label {
    width: 80px;
    display: inline-block;
  }
  .search_label.first {
    margin-left: 0;
  }
  .ant-select.middle {
    width: 220px;
  }
  .ant-select-dropdown {
    &.handler-select-dropdown {
      width: 160px;
    }
  }
  .filter_icon {
    font-size: 20px;
    color: rgba(0, 0, 0, 0.65);
    vertical-align: middle;
    margin-bottom: 3px;
  }
  .filter_list {
    margin-top: 12px;
  }
  .ant-badge .ant-badge-dot {
    background: #2d5afa;
  }
  .table_list {
    width: 100%;
    height: calc(100vh - 274px);
    display: inline-block;
    margin-top: 16px;
    .btn {
      padding: 0 5px;
    }
    .converted_icon {
      font-size: 18px;
      color: @main;
    }
  }
}
.ant-popover-inner-content .one {
  line-height: 30px;
  width: 90px;
  cursor: pointer;
}
</style>
