<template>
  <div>
    <div class="spread">
      <span class="headline" @click="handlecollapse">
        <span>任务信息</span>
        <i class="el-icon-arrow-down"></i>
      </span>
      <div class="mission" v-show="collapse">
        <div class="mission_left">
          <div class="min">
            <div class="execute">执行频率</div>
            <div class="wrapper">
              <div class="expression">
                <!-- 上 -->
                <div class="expression-top">
                  <span>crontab表达式</span>
                </div>
                <!-- 中 -->
                <div class="expression-centre">
                  <div class="time">
<!--                    <el-input style="width: 100px" v-model="inputItem.value" v-for="(inputItem, index) in inputGroup" :key="index">-->
<!--                      <template slot="suffix">{{ inputItem.label }}</template>-->
<!--                    </el-input>-->
                    <el-input v-model="form.crontab" @input="updateExecutionTimes" placeholder="请输入crontab表达式" />
                  </div>
                </div>
                <!-- 下 -->
                <div class="expression-below">
                  <span>crontab表达式展示 0 1 10 * * ?</span>
                </div>
              </div>
              <div class="executiontime">
                <span>最近三次执行时间</span>
                <div v-for="(item, index) in executionTimeList" :key="index">
                  {{ item.time }}
                </div>
              </div>
            </div>
          </div>
          <div class="footer">
            <span>用例执行方式</span>
            <template>
              <el-radio v-model="form.async" :label="2">串行</el-radio>
              <el-radio v-model="form.async" :label="0">并行</el-radio>
            </template>
          </div>
        </div>
        <div class="mission_right">
          <el-form ref="form" :model="form" label-width="120px">
            <el-form-item label="启动定时任务">
              <el-switch v-model="form.status"></el-switch>
            </el-form-item>
            <el-form-item label="失败用例重试">
              <el-switch v-model="form.retry"></el-switch>
            </el-form-item>
            <el-form-item label="最大重试次数">
              <el-input v-model="form.retryCount" style="width: 100px"></el-input>
              <span class="restrict">最小1次，最大10次</span>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <div>
      <div class="selected">
        <span class="headline" @click="handlecollapse1">
          <span>已选用例列表</span>
          <i class="el-icon-arrow-down"></i>
        </span>
      </div>
      <div class="form-container" v-show="collapse1">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addCase">添加用例</el-button>
          </el-col>
          <right-toolbar @queryTable="getCaseList"></right-toolbar>
        </el-row>
        <!-- 表格头部 -->
        <div class="table-header">
          <span>用例名称</span>
          <span>执行顺序</span>
          <span>创建人</span>
          <span>操作</span>
        </div>
        <!-- 使用 draggable 控制数据列表 -->
        <draggable v-model="caseList" @end="onDragEnd">
          <transition-group>
            <div v-for="item in caseList" :key="item.id" class="table-row">
              <!-- 手动构建表格行的内容 -->
              <span>{{ item.name }}</span>
              <span>{{ item.sort }}</span>
              <span>{{ item.createBy }}</span>
              <span>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="delCase(item.id)">删除</el-button>
          </span>
            </div>
          </transition-group>
        </draggable>
      </div>

    </div>
    <el-dialog :visible.sync="dialogFormVisible" title="添加用例" width="80%">
      <caseTable :caseList="caseList" :taskId="form.id" @success="getCaseList"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <div class="footer">
      <el-button type="primary" @click="submit">提 交</el-button>
    </div>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import cronParser from "cron-parser";
import caseTable from "./caseTable.vue";
import {delTaskCase, updateTaskCase} from "@/api/test/taskCase";

export default {
  components: {
    caseTable,
    draggable,
  },
  props: {
    task: {
      type: Object,
    },
    caseList: {
      type: Array,
    }
  },
  watch: {
    'form.crontab': {
      handler(newVal) {
        if (newVal) {
          this.updateExecutionTimes();
        }
      },
      immediate: true, // 立即触发一次
    },
    task: {
      handler(val) {
        if (val !== this.form) {
          this.form = val;
          this.form.status = val.status === 0;
          this.form.retry = val.retry === 0;
        }
      },
    },
  },
  data() {
    return {
      loading: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupId: null,
      },
      collapse: true,
      collapse1: true,
      collapse2: true,
      dialogFormVisible: false,
      input2: "0",
      radio: "1",
      inputGroup: [
        {
          label: "秒",
          value: "00",
        },
        {
          label: "分",
          value: "00",
        },
        {
          label: "时",
          value: "00",
        },
        {
          label: "日",
          value: "00",
        },
        {
          label: "月",
          value: "00",
        },
        {
          label: "周",
          value: "00",
        },
      ],
      executionTimeList: [
        {
          time: "2025-02-18 10:00:00",
        },
        {
          time: "2025-02-19 10:00:00",
        },
        {
          time: "2025-02-20 10:00:00",
        },
      ],
      value: "",
      form: {
        crontab: '', // 用户输入的crontab表达式
        delivery1: false,
        delivery2: false,
        name: "",
      },
    };
  },
  methods: {
    // 拖拽结束后更新排序值
    onDragEnd() {
      this.updateSortValues();
    },
    // 更新每行数据的 sort 值
    updateSortValues() {
      this.caseList.forEach((item, index) => {
        item.sort = index + 1;
        updateTaskCase({
          taskId: this.form.id,
          caseId: item.id,
          sort: item.sort,
        })
      });
    },
    // 根据crontab表达式更新执行时间
    updateExecutionTimes() {
      const crontab = this.form.crontab.trim();
      if (!crontab) {
        this.executionTimeList = [];
        return;
      }

      try {
        // 解析crontab表达式
        const interval = cronParser.parseExpression(crontab);
        const times = [];

        // 获取最近三次执行时间
        for (let i = 0; i < 3; i++) {
          const nextTime = interval.next().toDate(); // 获取 Date 对象
          const formattedTime = this.formatDate(nextTime); // 格式化时间
          times.push({ time: formattedTime });
        }

        this.executionTimeList = times;
      } catch (error) {
        console.error('无效的crontab表达式:', error);
        this.executionTimeList = [{ time: '无效的crontab表达式' }];
      }
    },
    // 格式化日期为 YYYY-MM-DD HH:mm:ss
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    getCaseList() {
      this.$emit("getData");
    },
    addCase() {
      this.dialogFormVisible = !this.dialogFormVisible;
    },
    delCase(id) {
      console.log(id)
      delTaskCase({
        taskId: this.task.id,
        caseId: id,
      }).then(res => {
        this.$modal.msgSuccess("删除成功");
        this.getCaseList();
      })
    },
    handlecollapse() {
      this.collapse = !this.collapse;
    },
    handlecollapse1() {
      this.collapse1 = !this.collapse1;
    },
    submit() {
      this.$emit("submit", this.form);
    }
  },
};
</script>
<style scoped lang="scss">
.table-header, .table-row {
  display: flex;
  justify-content: space-between;
  padding: 8px;
}

.table-header {
  font-weight: bold;
  background-color: #f5f7fa;
  border-bottom: 1px solid #EBEEF5;
}

.table-row {
  border-bottom: 1px solid #EBEEF5;
}

.table-header span, .table-row span {
  width: 25%;
  text-align: center;
}

.drag-handler {
  cursor: move; /* 改变鼠标手势 */
}
.headline {
  color: #4f597f;
  font-size: 14px;
  font-weight: 500;
  .el-icon-warning-outline {
    margin: 10px 0 0 16px;
  }
  .el-icon-arrow-down {
    background-color: #f3f4f9;
    border-radius: 1px;
    margin: 0 0 0 16px;
  }
}

.mission {
  border: 1px solid #ebf0fa;
  border-radius: 4px;
  display: flex;
  padding: 16px 8px;
  margin: 16px 0;
}
.mission_left {
  display: flex;
  flex-direction: column;
}
.min {
  display: flex;
  border: 1px solid transparent;
  border-radius: 4px;
  padding: 0 12px;
  position: relative;
}
.execute {
  align-items: center;
  color: #8e9eb1;
  display: flex;
  font-size: 12px;
  line-height: 20px;
  margin-right: 16px;
  min-width: 60px;
}
.wrapper {
  background-color: #f3f4f9;
  border-radius: 4px;
  display: flex;
  padding: 16px;
  position: relative;
}
.expression {
  width: 100%;
  .expression-top {
    color: #8e9eb1;
    font-size: 12px;
    height: 20px;
    line-height: 20px;
  }
  .expression-centre {
    width: 100%;
    align-items: flex-start;
    padding: 12px 0 6px;
    display: inline-flex;
    padding-right: 16px;
  }
}

::v-deep .time {
  display: flex;
  justify-content: space-between;
  width: 100%;
  .el-input__inner {
    height: 30px;
    line-height: 30px;
    border: none;
  }
  .el-input__suffix-inner {
    line-height: 30px;
    color: #000;
  }
}
.executiontime {
  font-size: 12px;
  color: #9c9c9c;
  display: flex;
  flex-direction: column;
  justify-content: center;
  line-height: 20px;
  padding-left: 16px;
  width: 200px;
  border-left: 1px solid #e1e6f0;
}
.expression-below {
  color: #8e9eb1;
  font-size: 12px;
  height: 20px;
  line-height: 20px;
}
.footer {
  display: flex;
  align-items: center;
  padding: 12px 12px 0 12px;
  margin-top: 12px;
  span {
    align-items: center;
    color: #8e9eb1;
    font-size: 12px;
    line-height: 20px;
    margin-right: 16px;
  }
}
.way {
  padding: 0 12px;
}
::v-deep .el-radio {
  margin-right: 20px;
}
::v-deep .el-radio__inner {
  width: 12px;
  height: 12px;
}
::v-deep .el-radio__label {
  font-size: 12px;
}
::v-deep .footer .avatar {
  display: flex;
  align-items: center;
}
.mission_right {
  padding-right: 50px;
}
.el-form-item {
  margin-bottom: 6px;
}
::v-deep .el-form-item__label {
  color: #8e9eb1;
  font-size: 12px;
  line-height: 36px;
}
.restrict {
  color: #8e9eb1;
  font-size: 12px;
  line-height: 36px;
  padding-left: 10px;
}
// 标题
.selected {
  display: flex;
  justify-content: space-between;
  padding-bottom: 8px;
}
.append-bt {
  border-radius: 4px;
  height: 32px;
}
.menu-list-item {
  display: flex;
  justify-content: space-between;
  width: 300px;
  padding: 16px;
  .num {
    display: inline-block;
  }
  .icon {
    display: none;
  }
  &:hover {
    background-color: #ebf1ff;
    .num {
      display: none;
    }
    .icon {
      display: inline-block;
    }
  }
  .menu-itme-left {
    display: flex;
    .menu-itme-text {
      display: flex;
      flex-direction: column;
      margin-left: 8px;
      .text-top {
        line-height: 14px;
        color: #343434;
      }
      .text-bottom {
        margin-top: 14px;
        color: #9c9c9c;
      }
    }
  }
}
.table {
  width: calc(100% - 300px);
  padding: 24px 24px 0;
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
  }
}
.icon--edit {
  background-color: #33bc5a;
  display: inline-block;
  width: 16px;
  height: 16px;
  text-align: center;
  line-height: 16px;
  color: #fff;
  border-radius: 2px;
  margin-right: 10px;
}
.icon__pencil {
  background-color: #fec47b;
  display: inline-block;
  width: 16px;
  height: 16px;
  text-align: center;
  line-height: 16px;
  color: #fff;
  border-radius: 2px;
  margin-right: 10px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

::v-deep .table-input {
  .el-input__inner {
    border: none;
  }
}
.table-input-text {
  &:hover {
    .icon {
      display: inline-block;
    }
  }
  .icon {
    display: none;
  }
}
.el-icon-success {
  width: 14px;
  height: 14px;
  color: rgb(51, 188, 90);
  margin-right: 10px;
}
.footer .avatar {
  display: flex;
  align-items: center;
}
::v-deep .table .el-table .cell {
  display: flex;
  align-items: center;
  .el-avatar--circle {
    margin-right: 10px;
  }
}
/* 修改 tab 标签的字体大小 */

::v-deep .el-tabs {
  .el-tabs__nav-wrap::after {
    display: none;
  }
  .el-tabs__header {
    margin: 0;
  }
  .el-tabs__item {
    font-size: 12px; /* 字体大小为 12px */
    font-weight: 500;
  }
}
.tab-line {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ebf0fa;
}
::v-deep .el-dialog {
  .el-dialog__body {
    padding: 10px;
  }
}
</style>
