<template>
  <div class="taskAdd">
    <header>
      <div class="top">
        <div class="left"></div>
        <div class="right"></div>
      </div>
      <div class="addbox">
        <baseNewForm
            ref="mainForm"
            :spanNumber="24"
            :formRow="formRow"
            :ruleForm="ruleForm"
            :isFunBtn="false"
            :lookFlag="lookFlag"
            :formRule="!lookFlag"
            @onSubmit="onSubmitHandle"
            @onChangeRadio="onChangeRadioHandle"
            @selectChange="selectChangeHandle"
        ></baseNewForm>
      </div>
    </header>
    <main>
      <div>
        <div class="title">
          <h1>执行策略</h1>
        </div>
        <baseNewForm
            :spanNumber="24"
            :formRow="mainFormRow"
            :ruleForm="mainRuleForm"
            :isFunBtn="false"
            :lookFlag="lookFlag"
        ></baseNewForm>
        <template v-if="mainRuleForm.now_execution == 'N'">
          <div class="timeEdit">
            <div class="title">
              <h1>编辑发生时间</h1>
            </div>
            <div class="timepick">
              <div class="Timebox">
                crontab完整表达式：{{
                  ruleForm.task_cron ? ruleForm.task_cron : "无"
                }}
              </div>
              <el-button round @click="showDialog" :disabled="lookFlag"
              >点击设置时间
              </el-button
              >
            </div>
          </div>
        </template>
      </div>
    </main>
    <footer>
      <div class="btn">
        <el-button
            type="primary"
            @click="commitForm"
            :loading="commitLoading"
            v-if="!lookFlag"
        >提交
        </el-button
        >
        <el-button @click="$router.back()">取消</el-button>
      </div>
    </footer>
    <el-dialog title="生成 cron" :visible.sync="showCron" width="70%">
      <FishCrontab
          class="crontab"
          @hide="showCron = false"
          @fill="crontabFill"
          :expression="expression"
          :fiveTimes="true"
      ></FishCrontab>
    </el-dialog>
  </div>
</template>

<script>
import FishCrontab from "fish-crontab";
import BaseLink from "./compoments/baseLink/index.vue";
import BaseNewForm from "./compoments/baseNewForm";
import baseTableForm from "./compoments/baseTableForm_v2.vue";
import {getApiModuleApi} from "@/api/apiChunks/index.js";

export default {
  data() {
    return {
      commitLoading: false,
      timeCron: "",
      expression: "",
      showCron: false,
      lookFlag: false,
      activeIndex: "1",
      ruleForm: {
        plug: "1",
        task_cron: "",
      },
      formRow: [
        {
          elCol: [
            {
              type: "input",
              title: "任务编码",
              id: "task_code",
              row: 8,
              disabled: true,
            },
            {
              type: "input",
              title: "任务名称",
              id: "task_name",
              row: 8,
              required: true,
            },
            {
              type: "select",
              title: "任务分类",
              id: "task_classes",
              row: 8,
              required: true,
              options: [
                {
                  label: "测试",
                  id: 1,
                },
              ],
            },
          ],
        },
        {
          elCol: [
            {
              type: "input",
              title: "任务策略",
              id: "task_cron",
              row: 8,
              disabled: true,
              placeholder: "请选择时间策略",
            },
            {
              type: "select",
              title: "任务状态",
              id: "task_status",
              row: 8,
              required: true,
              options: [
                {id: "1", label: "开启"},
                {id: "2", label: "关闭"},
              ],
            },
            {
              type: "newSelect",
              title: "任务场景",
              id: "task_tag",
              row: 8,
              required: true,
              options: [],
              apiInfo: {
                tl: "apiReflectionService",
                as: "sys_api_reflectionService",
                dj: "queryPagedJson",
              },
              searchApiInfo: {
                tl: "apiReflectionService",
                as: "sys_api_reflectionService",
                dj: "queryOneById",
              },
              searchKey: "id",
              prop: {
                id: "id",
                label: "ref_name",
              },
            },
          ],
        },
        {
          elCol: [
            {
              type: "input",
              title: "任务描述",
              id: "fun_info",
              row: 12,
              required: true,
            },
          ],
        },
        {
          elCol: [
            {
              type: "textrea",
              title: "备注",
              id: "remark",
              row: 24,
            },
          ],
        },
        {
          elCol: [
            {
              type: "radio",
              title: "使用插件",
              id: "plug",
              row: 8,
              disabled: true,
              options: [
                {
                  label: "是",
                  id: "1",
                },
                {
                  label: "否",
                  id: "2",
                },
              ],
            },
            {
              refName: "plugId",
              type: "select",
              disabled: true,
              title: "插件列表",
              id: "plug_id",
              row: 8,
              show: true,
              options: [],
              apiBody: {
                pluginType: "1",
              },
              searchKey: "pluginId",
              prop: {
                label: "pluginLabel",
                id: "pluginId",
              },
            },
          ],
        },
      ],
      funData: [
        {
          type: "addattr",
          text: "添加属性",
          color: "blue",
        },
        {
          type: "dele",
          text: "删除",
          color: "blue",
        },
      ],
      mainFormRow: [
        {
          elCol: [
            {
              type: "radio",
              title: "",
              id: "now_execution",
              row: 8,
              options: [
                {label: "立即执行", id: "Y"},
                {label: "定时", id: "N"},
              ],
            },
          ],
        },
      ],
      mainRuleForm: {
        now_execution: "N",
      },
      tableInfo: [
        {
          id: "requestHeader",
          tableData: [
            {
              id: 3,
              parameterName: "1",
              children: [{id: 4}],
            },
          ],
          detailFields: [
            {
              type: "input",
              title: "参数名称",
              id: "parameterName",
              width: 250,
            },
            {
              type: "select",
              title: "参数类型",
              id: "parameterType",
            },
            {
              type: "select",
              title: "具体类型",
              id: "concreteType",
            },
            {
              type: "switch",
              title: "必选",
              id: "required",
              width: 80,
            },
            {
              type: "number",
              title: "长度",
              id: "length",
              width: 100,
            },
            {
              type: "input",
              title: "示例",
              id: "example",
            },
            {
              type: "input",
              title: "描述",
              id: "description",
            },
            {
              type: "number",
              title: "文档顺序",
              id: "sorts",
              width: 100,
            },
          ],
        },
        {
          id: "requestHeader",
          tableData: [
            {
              id: 3,
              parameterName: "2",
              children: [{id: 4}],
            },
          ],
          detailFields: [
            {
              type: "input",
              title: "参数名称",
              id: "parameterName",
              width: 250,
            },
            {
              type: "select",
              title: "参数类型",
              id: "parameterType",
            },
            {
              type: "select",
              title: "具体类型",
              id: "concreteType",
            },
            {
              type: "switch",
              title: "必选",
              id: "required",
              width: 80,
            },
            {
              type: "number",
              title: "长度",
              id: "length",
              width: 100,
            },
            {
              type: "input",
              title: "示例",
              id: "example",
            },
            {
              type: "input",
              title: "描述",
              id: "description",
            },
            {
              type: "number",
              title: "文档顺序",
              id: "sorts",
              width: 100,
            },
          ],
        },
        {
          id: "requestHeader",
          tableData: [
            {
              id: 3,
              parameterName: "3",
              children: [{id: 4}],
            },
          ],
          detailFields: [
            {
              type: "input",
              title: "参数名称",
              id: "parameterName",
              width: 250,
            },
            {
              type: "select",
              title: "参数类型",
              id: "parameterType",
            },
            {
              type: "select",
              title: "具体类型",
              id: "concreteType",
            },
            {
              type: "switch",
              title: "必选",
              id: "required",
              width: 80,
            },
            {
              type: "number",
              title: "长度",
              id: "length",
              width: 100,
            },
            {
              type: "input",
              title: "示例",
              id: "example",
            },
            {
              type: "input",
              title: "描述",
              id: "description",
            },
            {
              type: "number",
              title: "文档顺序",
              id: "sorts",
              width: 100,
            },
          ],
        },
        {
          id: "requestHeader",
          tableData: [
            {
              id: 3,
              parameterName: "4",
              children: [{id: 4}],
            },
          ],
          detailFields: [
            {
              type: "input",
              title: "参数名称",
              id: "parameterName",
              width: 250,
            },
            {
              type: "select",
              title: "参数类型",
              id: "parameterType",
            },
            {
              type: "select",
              title: "具体类型",
              id: "concreteType",
            },
            {
              type: "switch",
              title: "必选",
              id: "required",
              width: 80,
            },
            {
              type: "number",
              title: "长度",
              id: "length",
              width: 100,
            },
            {
              type: "input",
              title: "示例",
              id: "example",
            },
            {
              type: "input",
              title: "描述",
              id: "description",
            },
            {
              type: "number",
              title: "文档顺序",
              id: "sorts",
              width: 100,
            },
          ],
        },
      ],
      parameterTypeOptions: [
        {
          label: "基本类型",
          id: "fundamental",
        },
        {
          label: "复杂类型",
          id: "complex",
        },
        {
          label: "基本列表",
          id: "fundamentallist",
        },
        {
          label: "复杂列表",
          id: "complexlist",
        },
      ],
      concreteTypeOptions: {
        fundamental: [
          {
            label: "String",
            id: "String",
          },
          {
            label: "Int",
            id: "Int",
          },
          {
            label: "Long",
            id: "Long",
          },
          {
            label: "Float",
            id: "Float",
          },
          {
            label: "Double",
            id: "Double",
          },
          {
            label: "Boolean",
            id: "Boolean",
          },
        ],
        complex: [
          {
            label: "Object",
            id: "Object",
          },
          {
            label: "Map",
            id: "Map",
          },
        ],
        fundamentallist: [
          {
            label: "String",
            id: "String",
          },
          {
            label: "Int",
            id: "Int",
          },
          {
            label: "Long",
            id: "Long",
          },
          {
            label: "Float",
            id: "Float",
          },
          {
            label: "Double",
            id: "Double",
          },
          {
            label: "Boolean",
            id: "Boolean",
          },
        ],
        complexlist: [
          {
            label: "Object",
            id: "ObjectCom",
          },
        ],
        authport: [
          {
            label: "String",
            id: "String",
          },
          {
            label: "Int",
            id: "Int",
          },
          {
            label: "Long",
            id: "Long",
          },
          {
            label: "Float",
            id: "Float",
          },
          {
            label: "Double",
            id: "Double",
          },
          {
            label: "Boolean",
            id: "Boolean",
          },
        ],
      },
      timeForm: {
        timeNum: 1,
        timeunit: 1,
        happenMethod: 1,
        timeOnceData: "01-00-00",
        periodNum: 1,
        periotimeunit: 1,
        timeperiod: ["01-00-00", "02-00-00"],
        perpetual: true,
        takeDate: ["2023-07-06-00-00-00", "2023-08-04-00-00-00"],
      },
      itemunitOptions: [
        {
          id: 1,
          label: "天",
        },
        {
          id: 2,
          label: "时",
        },
      ],
    };
  },
  methods: {
    // 请求找到场景 初始化插件
    async selectChangeHandle(val, row) {
      if (val) {
        if (row.id == "task_tag") {
          const res = await getApiModuleApi(
              {
                tl: "apiReflectionService",
                as: "sys_api_reflectionService",
                dj: "queryOneById",
              },
              {
                id: val,
              }
          );
          console.log(res);
          if (res.status == 200) {
            this.$set(this.ruleForm, "plug", res.attribute.main.plug);
            this.formRow[4].elCol[1].show = this.ruleForm.plug == 1;
            this.$set(this.ruleForm, "plug_id", res.attribute.main.plug_id);
          }
        }
      }

      console.log(val, row);
    },
    // 初始化标识select
    async initSelectScene() {
      const res = await getApiModuleApi({
        tl: "apiReflectionService",
        as: "sys_api_reflectionService",
        dj: "queryPagedJson",
      });
    },
    // options
    async initSelectPlug() {
      const res = await getApiModuleApi(
          {
            tl: "pluginService",
            as: "plugins",
            dj: "queryPluginsByType",
          },
          {
            pluginType: "1",
          }
      );
      if (res.status == 200) {
        res.attribute.forEach((item) => {
          this.formRow[4].elCol[1].options.push({
            id: item.pluginId,
            label: item.pluginLabel,
          });
        });
      }
    },
    // 点击radio
    onChangeRadioHandle(val, index, indexRow, row) {
      console.log(val, index, indexRow, row);
      if (row.id == "plug") {
        if (val == 2) {
          if (this.ruleForm.plug_id) {
            this.ruleForm.plug_id = "";
          }
        }
        this.formRow[4].elCol[1].show = val == 1;
      }
    },
    // 查看任务
    async searchTaskHandle(id) {
      const res = await getApiModuleApi(
          {
            tl: "integrationTaskService",
            as: "integrationTask",
            dj: "queryIntegrationTaskById",
          },
          {
            id: this.$route.query.id
          }
      );
      if (res.status == 200) {
        this.ruleForm = res.attribute.main;
        this.formRow[4].elCol[1].show = this.ruleForm.plug == 1;
        this.mainRuleForm.now_execution =
            res.attribute.details[0]["now_execution"];
      }
    },
    // 点击提交
    commitForm() {
      this.$refs.mainForm.submitForm();
    },
    // 时间插件
    showDialog() {
      this.expression = this.ruleForm.task_cron; //传入的 cron 表达式，可以反解析到 UI 上
      this.showCron = true;
      this.$nextTick(() => {
        document
            .querySelector(".crontab tbody")
            .setAttribute("style", "vertical-align:none !important;");
      });
    },
    // 时间插件回调
    crontabFill(value) {
      //确定后回传的值
      this.ruleForm.task_cron = value;
    },
    handleChange() {
    },
    // 表单验证成功后
    async onSubmitHandle() {
      this.commitLoading = true;
      let obj = {...this.ruleForm, ...this.mainRuleForm};
      if (!this.$route.query.id) {
        const res = await getApiModuleApi(
            {
              tl: "integrationTaskService",
              as: "integrationTask",
              dj: "saveIntegrationTask",
            },
            obj
        );
        this.commitLoading = false;
        if (res.status == 200) {
          this.$message({
            type: "success",
            message: "保存成功！",
          });
          this.$router.back();
        }
      } else {
        obj["id"] = this.$route.query.id;
        const res = await getApiModuleApi(
            {
              tl: "integrationTaskService",
              as: "integrationTask",
              dj: "updateIntegrationTask",
            },
            obj
        );
        this.commitLoading = false;
        if (res.status == 200) {
          this.$message({
            type: "success",
            message: "修改成功！",
          });
          this.$router.back();
        }
      }
    },
    // 添加行
    addTableData(tabledata) {
      tabledata.push({id: Date.now()});
    },
    handleSelect(key, keyPath) {
      this.activeIndex = key;
    },
    tableButtonHandle() {
    },
    // 暂无用
    idWatch(arr, id) {
      arr.some((item, index) => {
        if (item.id === id) {
          arr.splice(index, 1);
          return true;
        } else if (item.children && item.children.length) {
          this.idWatch(item.children, id);
        } else {
          return false;
        }
      });
    },
    // 父下拉框改变处理（暂无用
    fatherSelectChangeHandle(row) {
      if (row[0].concreteType) {
        row[0].concreteType = "";
        if (row[0] && row[0].children) {
          this.$delete(row[0], "children");
        }
      }
    },
    // 子下拉框改变处理（暂无用
    sonSelectChangeHandle(val, row) {
      console.log(val, row);
      if (
          val != "Object" &&
          val != "ObjectCom" &&
          val != "Map" &&
          row[0].children
      ) {
        this.$delete(row[0], "children");
      }
    },
    // 表单操作按钮
    tableButtonHandle(row, item, data) {
      if (item.type === "dele") {
        this.$confirm("确认删除？")
            .then(() => {
              this.idWatch(data, row.id);
            })
            .catch(() => {
            });
      } else if (item.type === "addattr") {
        console.log(
            row.concreteType,
            row.concreteType != "Object",
            row.concreteType != "Map"
        );
        if (
            row.concreteType &&
            row.concreteType != "Object" &&
            row.concreteType != "Map" &&
            row.concreteType != "ObjectCom"
        ) {
          this.$notify({
            title: "添加失败",
            message: "具体类型为Object或Map时才能生成子集!",
            type: "error",
          });
          return;
        } else if (!row.children) {
          this.$set(row, "children", []);
          row.children.push({id: Date.now()});
        } else {
          row.children.push({id: Date.now()});
        }
        this.$notify({
          title: "添加成功",
          message: "添加成功！",
          type: "success",
        });
      }
    },
  },
  computed: {
    funWidth() {
      return this.funData.length * 70;
    },
  },
  components: {
    BaseNewForm,
    baseTableForm,
    BaseLink,
    FishCrontab,
  },
  mounted() {
    this.initSelectPlug();
    if (this.$route.query.id) {
      this.searchTaskHandle(this.$route.query.id);
    }
    if (this.$route.query.lookFlag) {
      this.lookFlag = true;
    }
  },
};
</script>

<style scope lang='scss'>
::v-deep .el-table__header-wrapper {
  border-radius: 15px !important;
  background: #f7f7f7 !important;
}

.test {
  vertical-align: inherit !important;
}

.crontab > > > tbody {
  vertical-align: inherit !important;
}

.crontab > > > span {
  vertical-align: inherit !important;
}

.crontab > > > td {
  vertical-align: inherit !important;
}

.taskAdd {
  width: 100%;

  .addbox {
    background-color: #fff;
    padding: 20px 0;
    border-radius: 18px;
  }

  header {
    .top {
      background-color: #fff;
      display: flex;
      justify-content: space-between;

      .right {
        padding: 20px;
      }
    }
  }

  main {
    margin-top: 20px;
    border-radius: 20px;
    padding: 30px;
    width: 100%;
    background-color: #fff;

    .title {
      margin-bottom: 20px;
    }

    .timeEdit {
      margin-top: 20px;

      .timepick {
        display: flex;
        align-items: center;

        .Timebox {
          margin-right: 20px;
        }
      }
    }
  }

  footer {
    margin-top: 20px;
    border-radius: 20px;
    padding: 30px;
    width: 100%;
    background-color: #fff;
  }

  .add {
    margin-top: 30px;
    border: 1px dotted #ccc;
    text-align: center;
    height: 50px;
    line-height: 50px;
  }

  .link {
    width: 100%;
    margin-top: 20px;
  }

  .timeEdit {
    > .top {
      .box {
        display: flex;
        height: 50px;
        align-items: center;

        .left {
          width: 150px;
        }

        .right {
          margin-left: 20px;
        }
      }
    }
  }
}
</style>
