<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"
          @onSelect="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="true">
          <div class="timeEdit">
            <div class="title">
              <h1>编辑发生时间</h1>
            </div>
            <div class="timepick">
              <div class="Timebox">
                crontab完整表达式：{{
                  ruleForm.taskCron ? ruleForm.taskCron : '无'
                }}
              </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'
import { authApi } from '@/api/apis/auth'

export default {
  data() {
    return {
      commitLoading: false,
      timeCron: '',
      expression: '',
      showCron: false,
      lookFlag: false,
      activeIndex: '1',
      ruleForm: {
        plug: '1',
        taskCron: ''
      },
      formRow: [
        {
          elCol: [
            {
              type: 'input',
              title: '任务编码',
              id: 'taskCode',
              row: 8,
              disabled: true
            },
            {
              type: 'input',
              title: '任务名称',
              id: 'taskName',
              row: 8,
              required: true,
              disabled: false
            },
            {
              type: 'input',
              title: '任务策略',
              id: 'taskCron',
              row: 8,
              disabled: true,
              placeholder: '请选择时间策略'
            }
          ]
        },
        {
          elCol: [
            {
              type: 'select',
              title: '任务状态',
              id: 'taskStatus',
              row: 8,
              required: true,
              options: [
                { id: '1', label: '启用' },
                { id: '2', label: '停用' }
              ]
            },
            {
              refName: 'plugId',
              type: 'select',
              disabled: false,
              title: '应用列表',
              id: 'taskApp',
              required: true,
              row: 8,
              show: true,
              options: [],
              apiBody: {
                pluginType: '1'
              },
              searchKey: 'pluginId',
              prop: {
                label: 'pluginLabel',
                id: 'pluginId'
              }
            },
            {
              refName: 'plugId',
              type: 'select',
              disabled: false,
              title: '插件列表',
              id: 'taskPlugin',
              required: true,
              row: 8,
              show: true,
              options: [],
              apiBody: {
                pluginType: '1'
              },
              searchKey: 'pluginId',
              prop: {
                label: 'pluginLabel',
                id: 'pluginId'
              }
            }

          ]
        },
        {
          elCol: [
            {
              type: 'input',
              title: '任务描述',
              id: 'funInfo',
              row: 12,
              required: true
            }
          ]
        },
        {
          elCol: [
            {
              type: 'textrea',
              title: '备注',
              id: 'remark',
              row: 24
            }
          ]
        }
      ],
      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, index, indexRow, row) {
      if (row.title === '应用列表') {
        this.formRow[1].elCol[2].options = []
        this.$set(this.ruleForm, 'taskPlugin', '')
        if (val) {
          const res = await authApi('sysApplicationPluginService', '', 'queryEntity', '', {
            appId: val
          })
          if (res.status === '200') {
            res.attribute.forEach((item) => {
              this.formRow[1].elCol[2].options.push({
                id: item.id,
                label: item.pluginName
              })
            })
          }
          console.log(res, '123')
        }
      }
      console.log(val, row)
    },
    // 初始化标识select
    async initSelectScene() {
      const res = await getApiModuleApi({
        tl: 'apiReflectionService',
        as: 'sys_api_reflectionService',
        dj: 'queryPagedJson'
      })
    },
    // 应用列表初始化
    async initSelectPlug() {
      const res = await getApiModuleApi(
        {
          tl: 'sysApplicationService',
          as: '',
          dj: 'queryEntity'
        },
        {}
      )
      if (res.status == 200) {
        res.attribute.forEach((item) => {
          this.formRow[1].elCol[1].options.push({
            id: item.id,
            label: item.name
          })
        })
      }
    },
    // 点击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: '',
          dj: 'getEntity'
        },
        {
          id: this.$route.query.id
        }
      )
      if (res.status == 200) {
        this.ruleForm = res.attribute
        console.log(res)
        this.formRow[0].elCol[1].disabled = false
        const res2 = await authApi('sysApplicationPluginService', '', 'queryEntity', '', {
          appId: res.attribute.taskApp
        })
        if (res2.status === '200') {
          res2.attribute.forEach((item) => {
            this.formRow[1].elCol[2].options.push({
              id: item.id,
              label: item.pluginName
            })
          })
        }
      }
    },
    // 点击提交
    commitForm() {
      this.$refs.mainForm.submitForm()
    },
    // 时间插件
    showDialog() {
      this.expression = this.ruleForm.taskCron //传入的 cron 表达式，可以反解析到 UI 上
      this.showCron = true
      this.$nextTick(() => {
        document
          .querySelector('.crontab tbody')
          .setAttribute('style', 'vertical-align:none !important;')
      })
    },
    // 时间插件回调
    crontabFill(value) {
      //确定后回传的值
      this.ruleForm.taskCron = value
    },
    handleChange() {
    },
    // 表单验证成功后
    async onSubmitHandle() {
      if (!this.ruleForm.taskCron) {
        this.$vmNews('请编辑发生时间选择任务策略')
        return
      }
      this.commitLoading = true
      let obj = { ...this.ruleForm }
      if (!this.$route.query.id) {
        const res = await getApiModuleApi(
          {
            tl: 'integrationTaskService',
            as: '',
            dj: 'saveEntity'
          },
          obj
        )
        this.commitLoading = false
        if (res.status == 200) {
          this.$message({
            type: 'success',
            message: res.msg
          })
          this.$router.back()
          //面包屑删除
          this.$store.dispatch('tagsView/delView', this.$route)
        }
      } else {
        obj['id'] = this.$route.query.id
        const res = await getApiModuleApi(
          {
            tl: 'integrationTaskService',
            as: '',
            dj: 'updateEntity'
          },
          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%;
  overflow: auto;

  .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>
