<script lang="ts" setup>
import type { Job } from '#/api/monitor/job/model';

import { defineEmits, ref } from 'vue';

import { useVbenDrawer, useVbenForm, useVbenModal } from '@vben/common-ui';

import { AlarmClock } from '@element-plus/icons-vue';

import { addJob, jobDetail, updateJob } from '#/api/monitor/job/job';

import { drawerSchema } from './config-data';
import CronModal from './cron-modal.vue';

const emit = defineEmits<{ reload: [] }>();

// 定义表达式弹窗
const [Modal, modalApi] = useVbenModal({
  connectedComponent: CronModal,
});

// 定义侧拉里面的表单
const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  layout: 'horizontal',
  schema: drawerSchema(),
});
// 定义侧拉容器
const isUpdateRef = ref<boolean>(false);
const [Drawer, drawerApi] = useVbenDrawer({
  showConfirmButton: false,
  // 打开角色侧拉监听
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { jobId, isUpdate, isView } = drawerApi.getData();
      isUpdateRef.value = isUpdate;
      drawerApi.setState({ showConfirmButton: !isView });
      if (isUpdate || isView) {
        const jobResult = await jobDetail(jobId);
        await formApi.setValues(jobResult);
      }
    } catch (error) {
      console.error(error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },
  async onClosed() {
    // 重置表单
    await formApi.resetForm();
  },
  // 确认提交角色
  async onConfirm() {
    try {
      drawerApi.drawerLoading(true);
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const data = await formApi.getValues<Job>();
      isUpdateRef.value ? await updateJob(data) : await addJob(data);
      // 发射刷新列表
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },
});
// 创建表达式
async function generateCron() {
  const data = await formApi.getValues<Job>();
  modalApi.setData(data).open();
}
// 表达式回传的值
function cronCallBack(value: string) {
  formApi.setFieldValue('cronExpression', value);
}
</script>
<template>
  <Drawer title="编辑">
    <Form>
      <template #cronExpression="slotProps">
        <ElInput v-bind="slotProps">
          <template #append>
            <el-button :icon="AlarmClock" @click="generateCron">
              生成表达式
            </el-button>
          </template>
        </ElInput>
      </template>
    </Form>
    <Modal @cron-call-back="cronCallBack" />
  </Drawer>
</template>
