<template>
  <div class="wrap">
    <Card>
      <template #body>
        <div class="facility-box">
          <div class="state-right">
            <div class="iscollpInp">
              <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-form-item label="任务名称" prop="jobName">
                      <el-input
                        v-model="queryParams.jobName"
                        placeholder="请输入任务名称"
                        clearable
                        @keyup.enter="handleQuery"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="任务组名" prop="jobGroup">
                      <el-select v-model="queryParams.jobGroup" placeholder="请选择任务组名" clearable>
                        <el-option
                          v-for="dict in dict.type.sys_job_group"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="任务状态" prop="status">
                      <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
                        <el-option
                          v-for="dict in dict.type.sys_job_status"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <div class="search-buttons">
                      <el-button type="primary" @click="handleQuery">搜索</el-button>
                      <el-button @click="resetQuery">重置</el-button>
                    </div>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div class="table-container">
              <div class="spocebtn">
                <el-button type="primary" plain @click="handleAdd" v-hasPermi="['monitor:job:add']">新增</el-button>
                <el-button
                  type="danger"
                  plain
                  @click="handleDelete"
                  :disabled="multiple"
                  v-hasPermi="['monitor:job:remove']"
                >
                  删除
                </el-button>
                <el-button type="warning" plain @click="handleExport" v-hasPermi="['monitor:job:export']">
                  导出
                </el-button>
                <el-button type="info" plain @click="handleJobLog" v-hasPermi="['monitor:job:query']">日志</el-button>
              </div>
              <Table
                :columns="tableConfig.thead"
                :tableData="jobList"
                :showSelection="true"
                :showIndex="false"
                :total="total"
                :pageSizes="[10, 20, 30, 40]"
                :tableHeight="400"
                @selection-change="handleSelectionChange"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              >
                <template #jobGroup="{ row }">
                  <dict-tag :options="dict.type.sys_job_group" :value="row.jobGroup" />
                </template>
                <template #status="{ row }">
                  <el-switch
                    v-model="row.status"
                    active-value="0"
                    inactive-value="1"
                    @change="handleStatusChange(row)"
                  ></el-switch>
                </template>
                <template #operation="{ row }">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(row)"
                    v-hasPermi="['monitor:job:edit']"
                  >
                    修改
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(row)"
                    v-hasPermi="['monitor:job:remove']"
                  >
                    删除
                  </el-button>
                  <el-dropdown
                    size="mini"
                    @command="command => handleCommand(command, row)"
                    v-hasPermi="['monitor:job:changeStatus', 'monitor:job:query']"
                  >
                    <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item
                        command="handleRun"
                        icon="el-icon-caret-right"
                        v-hasPermi="['monitor:job:changeStatus']"
                      >
                        执行一次
                      </el-dropdown-item>
                      <el-dropdown-item command="handleView" icon="el-icon-view" v-hasPermi="['monitor:job:query']">
                        任务详细
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="handleJobLog"
                        icon="el-icon-s-operation"
                        v-hasPermi="['monitor:job:query']"
                      >
                        调度日志
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </Table>
            </div>
          </div>
        </div>
      </template>
    </Card>

    <!-- 添加或修改定时任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :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 dict.type.sys_job_group"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="invokeTarget">
              <span slot="label">
                调用方法
                <el-tooltip placement="top">
                  <div slot="content">
                    Bean调用示例：ryTask.ryParams('ry')
                    <br />
                    Class类调用示例：com.ruoyi.quartz.task.RyTask.ryParams('ry')
                    <br />
                    参数说明：支持字符串，布尔类型，长整型，浮点型，整型
                  </div>
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
              <el-input v-model="form.invokeTarget" placeholder="请输入调用目标字符串" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="cron表达式" prop="cronExpression">
              <el-input v-model="form.cronExpression" placeholder="请输入cron执行表达式">
                <template slot="append">
                  <el-button type="primary" @click="handleShowCron">
                    生成表达式
                    <i class="el-icon-time el-icon--right"></i>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.jobId !== undefined">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_job_status" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行策略" prop="misfirePolicy">
              <el-radio-group v-model="form.misfirePolicy" size="small">
                <el-radio-button label="1">立即执行</el-radio-button>
                <el-radio-button label="2">执行一次</el-radio-button>
                <el-radio-button label="3">放弃执行</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否并发" prop="concurrent">
              <el-radio-group v-model="form.concurrent" size="small">
                <el-radio-button label="0">允许</el-radio-button>
                <el-radio-button label="1">禁止</el-radio-button>
              </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="Cron表达式生成器" :visible.sync="openCron" append-to-body destroy-on-close class="scrollbar">
      <crontab @hide="openCron = false" @fill="crontabFill" :expression="expression"></crontab>
    </el-dialog>

    <!-- 任务日志详细 -->
    <el-dialog title="任务详细" :visible.sync="openView" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="120px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务编号：">{{ form.jobId }}</el-form-item>
            <el-form-item label="任务名称：">{{ form.jobName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组：">{{ jobGroupFormat(form) }}</el-form-item>
            <el-form-item label="创建时间：">{{ form.createTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="cron表达式：">{{ form.cronExpression }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次执行时间：">{{ parseTime(form.nextValidTime) }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调用目标方法：">{{ form.invokeTarget }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务状态：">
              <div v-if="form.status == 0">正常</div>
              <div v-else-if="form.status == 1">暂停</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否并发：">
              <div v-if="form.concurrent == 0">允许</div>
              <div v-else-if="form.concurrent == 1">禁止</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行策略：">
              <div v-if="form.misfirePolicy == 0">默认策略</div>
              <div v-else-if="form.misfirePolicy == 1">立即执行</div>
              <div v-else-if="form.misfirePolicy == 2">执行一次</div>
              <div v-else-if="form.misfirePolicy == 3">放弃执行</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { systemJobApi } from '@/utils/api.js'
import Crontab from '@/components/Crontab'
import Table from '@/components/CustomTable.vue'
import Card from '@/components/Card.vue'

const dict = ref({
  type: {
    sys_job_group: [],
    sys_job_status: [],
  },
})
const router = useRouter()
const { listJob, getJob, delJob, addJob, updateJob, runJob, changeJobStatus } = systemJobApi
// 数据定义
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const jobList = ref([])
const title = ref('')
const open = ref(false)
const openView = ref(false)
const openCron = ref(false)
const expression = ref('')

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  jobName: undefined,
  jobGroup: undefined,
  status: undefined,
})

const form = reactive({
  jobId: undefined,
  jobName: undefined,
  jobGroup: undefined,
  invokeTarget: undefined,
  cronExpression: undefined,
  misfirePolicy: 1,
  concurrent: 1,
  status: '0',
})

const rules = {
  jobName: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
  invokeTarget: [{ required: true, message: '调用目标字符串不能为空', trigger: 'blur' }],
  cronExpression: [{ required: true, message: 'cron执行表达式不能为空', trigger: 'blur' }],
}

const tableConfig = reactive({
  thead: [
    { prop: 'jobId', label: '任务编号', width: '100px' },
    { prop: 'jobName', label: '任务名称' },
    { prop: 'jobGroup', label: '任务组名' },
    { prop: 'invokeTarget', label: '调用目标字符串' },
    { prop: 'cronExpression', label: 'cron执行表达式' },
    { prop: 'status', label: '状态' },
    { prop: 'operation', label: '操作', width: '150px' },
  ],
})

const inp = reactive({
  input: '',
})

const treeDatas = reactive({
  treeData: [], // 这里需要根据实际情况填充树形数据
})

const selectTree = ref()

const filterNode = (value, data) => {
  if (!value) return true
  return data[defaultProps.label].indexOf(value) !== -1
}

watch(
  () => inp.input,
  newValue => {
    selectTree.value.filter(newValue)
  },
)

const defaultProps = {
  children: 'children',
  label: 'name',
}

const handleNodeClick = treeData => {
  // 处理树节点点击事件
}

const handleCheckChange = (data, checked, indeterminate) => {
  // 处理树节点选中状态变化
}

const handleSizeChange = val => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = val => {
  queryParams.pageNum = val
  getList()
}

// 方法定义
const getList = () => {
  loading.value = true
  listJob(queryParams).then(response => {
    jobList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

const jobGroupFormat = row => {
  return dict.value.sys_job_group.find(item => item.value === row.jobGroup)?.label || ''
}

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  // 重置表单的逻辑
  handleQuery()
}

const handleSelectionChange = selection => {
  ids.value = selection.map(item => item.jobId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

const handleCommand = (command, row) => {
  switch (command) {
    case 'handleRun':
      handleRun(row)
      break
    case 'handleView':
      handleView(row)
      break
    case 'handleJobLog':
      handleJobLog(row)
      break
  }
}

const handleStatusChange = row => {
  let text = row.status === '0' ? '启用' : '停用'
  ElMessageBox.confirm(`确认要"${text}""${row.jobName}"任务吗？`)
    .then(() => {
      return changeJobStatus(row.jobId, row.status)
    })
    .then(() => {
      ElMessage.success(text + '成功')
    })
    .catch(() => {
      row.status = row.status === '0' ? '1' : '0'
    })
}

const handleRun = row => {
  ElMessageBox.confirm(`确认要立即执行一次"${row.jobName}"任务吗？`)
    .then(() => {
      return runJob(row.jobId, row.jobGroup)
    })
    .then(() => {
      ElMessage.success('执行成功')
    })
    .catch(() => {})
}

const handleView = row => {
  getJob(row.jobId).then(response => {
    Object.assign(form, response.data)
    openView.value = true
  })
}

const handleShowCron = () => {
  expression.value = form.cronExpression
  openCron.value = true
}

const crontabFill = value => {
  form.cronExpression = value
}

const handleJobLog = row => {
  const jobId = row.jobId || 0
  router.push(`/monitor/job-log/index/${jobId}`)
}

const handleAdd = () => {
  Object.assign(form, {
    jobId: undefined,
    jobName: undefined,
    jobGroup: undefined,
    invokeTarget: undefined,
    cronExpression: undefined,
    misfirePolicy: 1,
    concurrent: 1,
    status: '0',
  })
  open.value = true
  title.value = '添加任务'
}

const handleUpdate = row => {
  const jobId = row.jobId || ids.value
  getJob(jobId).then(response => {
    Object.assign(form, response.data)
    open.value = true
    title.value = '修改任务'
  })
}

const submitForm = () => {
  // 表单提交逻辑
}

const handleDelete = row => {
  const jobIds = row.jobId || ids.value
  ElMessageBox.confirm(`是否确认删除定时任务编号为"${jobIds}"的数据项？`)
    .then(() => {
      return delJob(jobIds)
    })
    .then(() => {
      getList()
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

const handleExport = () => {
  // 导出逻辑
}

// 生命周期钩子
onMounted(() => {
  // getList()
  // 获取树形数据的方法，需要根据实际情况实现
  // getFacilityList()
})

// 计算属性
const disableSelection = computed(() => ({
  single: single.value,
  multiple: multiple.value,
}))
</script>

<style lang="scss" scoped>
.wrap {
  width: 100%;
  height: 100%;
}

.facility-box {
  display: flex;
  height: calc(100vh - 100px);
  overflow: hidden;
  flex: 1;
  .state-left {
    width: 20%;
    padding-right: 20px;
    overflow-y: auto;

    .treeinp {
      margin-bottom: 20px;
    }
  }

  .state-right {
    flex: 1;
    display: flex;
    flex-direction: column;
    border-left: 1px solid #ccc;
    padding-left: 20px;
    overflow-y: auto;

    .iscollpInp {
      margin-bottom: 20px;

      .el-form {
        width: 100%;

        .el-row {
          margin-bottom: 0;
        }

        .el-form-item {
          margin-bottom: 0;
        }
      }

      .search-buttons {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        height: 100%;

        .el-button {
          margin-left: 10px;
        }
      }
    }

    .table-container {
      flex: 1;
      display: flex;
      flex-direction: column;

      .spocebtn {
        margin-bottom: 10px;
      }
    }
  }
}
</style>