<script setup lang="tsx">
import { message, Tag } from 'ant-design-vue';
import type { Key } from 'ant-design-vue/es/_util/type';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { SimpleScrollbar } from '~/packages/materials/src';
import { useI18n } from "vue-i18n";
import { SyncOutlined, SearchOutlined, ProfileOutlined, CloseOutlined, ExportOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { enableStatusOptions } from '@/constants/business';
import { saveAs } from 'file-saver';

import Modal from 'ant-design-vue/es/modal/Modal';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();



const { t } = useI18n();
const wrapperEl = shallowRef<HTMLElement | null>(null);
const { height: wrapperElHeight } = useElementSize(wrapperEl);

const jobId = route.query && (route.query.jobId as string);

/**对话框对象信息状态 */
let modalState: any = reactive({
  openByView: false,
  openByEdit: false,
  title: '任务',
  from: {
    jobId: undefined,
    jobName: '',
    invokeTarget: '',
    cronExpression: '',
    misfirePolicy: '3',
    concurrent: '0',
    jobGroup: 'DEFAULT',
    status: '0',
    saveLog: '0',
    targetParams: '',
    remark: '',
    jobMessage: ''
  },
  confirmLoading: false,
  openByCron: false,
  statusOpt: [
    { label: t('common.normal'), value: '0' },
    { label: t('common.disable'), value: '1' }
  ],
  jobGroup: [
    { label: t('common.default'), value: "DEFAULT" },
    { label: t('common.system'), value: "SYSTEM" }
  ],
  sysJobSaveLog: [
    { label: t('common.record'), value: "0" },
    { label: t('common.noRecord'), value: "1" }
  ]
});


const scrollConfig = computed(() => {
  return {
    y: wrapperElHeight.value - 72,
    x: 1000
  };
});

const { columns, data, loading, getData, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: doGetjobLogList,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    jobName: '',
    jobGroup: '',
    status: ''
  },
  rowKey: 'jobLogId',
  columns: () => [
    {
      dataIndex: 'jobLogId',
      title: t('page.manage.task.taskId'),
      align: 'center'
    },
    {
      key: 'jobName',
      dataIndex: 'jobName',
      title: t('page.manage.task.taskName'),
      align: 'center'
    },
    {
      key: 'jobGroup',
      dataIndex: 'jobGroup',
      title: t('page.manage.task.group'),
      align: 'center',
    },
    {
      key: 'invokeTarget',
      dataIndex: 'invokeTarget',
      title: t('page.manage.task.invoke'),
      align: 'center'
    },
    {
      key: 'status',
      dataIndex: 'status',
      align: 'center',
      customRender: ({ record }: any) => {
        if (record.status === null) {
          return null;
        }
        const tagMap: any = {
          '0': t('common.normal'),
          '1': t('common.abnormal'),
        };
        const tagColor: any = {
          '0': 'success',
          '1': 'error'
        };
        return <Tag color={tagColor[record.status]}>{tagMap[record.status]}</Tag>;
      },
      title: t('page.manage.log.operStatus'),
    },
    {
      key: 'jobMessage',
      title: t('page.manage.task.jobMessage'),
      dataIndex: 'jobMessage',
      align: 'center',
    },
    {
      title: t('page.manage.task.createTime'),
      dataIndex: 'createTime',
      align: 'center',
      width: 150,
      key: 'createTime',
    },
    {
      key: 'jobLogId',
      title: t('common.operate'),
      align: 'center',
      width: 200,
    }
  ]
});

const {
  operateType,
  checkedRowKeys,
  onDeleted
  // closeDrawer
} = useTableOperate(data, { getData, idKey: 'jobLogId' });



async function handleBatchDelete() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('page.manage.task.delLogTip', { num: checkedRowKeys.value.join(',') }),
    async onOk() {

      const { error } = await doDeleteJobLog(checkedRowKeys.value);
      if (!error) {
        onDeleted();
        // 取消勾选
        if (checkedRowKeys.value.length > 0) {
          checkedRowKeys.value = [];
        }
      }
    }
  })
}


function handleUserSelectChange(selectedRowKeys: Key[], selectedRows: any[]) {
  checkedRowKeys.value = selectedRowKeys as number[];
}

function fnTest() {
  if (jobId && jobId !== '0') {
    searchParams.value = Object.assign(searchParams, {
      status: undefined,
      pageNum: 1,
      pageSize: 10,
    });
  } else {
    searchParams.value = Object.assign(searchParams, {
      jobId: '',
      jobName: '',
      jobGroup: undefined,
      status: undefined,
      pageNum: 1,
      pageSize: 10,
    });
  }
  resetSearchParams();
}

async function fnRecordView(jobLogId: number) {
  operateType.value = 'view';
  if (modalState.confirmLoading) return;
  const hide = message.loading('Waiting...', 0);
  modalState.confirmLoading = true;
  doGetjobLogInfo(jobLogId).then(res => {
    modalState.confirmLoading = false;
    hide();
    if (!res.error) {
      modalState.from = Object.assign(modalState.from, res.data);
      modalState.openByView = true;
      modalState.title = t('page.manage.task.viewJob');
      console.log(modalState.openByView);
    }
  });
}



/**
 * 对话框弹出关闭执行函数
 * 进行表达规则校验
 */
function fnModalCancel() {
  modalState.openByEdit = false;
  modalState.openByView = false;
}






/**列表清空 */
function fnCleanList() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('page.manage.task.clearTip'),
    onOk() {
      const key = 'cleanJobLog';
      message.loading({ content: t('common.loading'), key });
      doCleanJobLog().then(res => {
        if (!res.error) {
          message.success({
            content: t('page.manage.task.clearOk'),
            key,
            duration: 2,
          });
          getData();
        }
      });
    },
  });
}


/**列表导出 */
function fnExportList() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('common.exportTip'),
    onOk() {
      const key = 'exportJobLog';
      message.loading({ content: t('common.loading'), key });
      exportJobLog().then(res => {
        console.log(res);
        if (!res.error) {
          message.success({
            content: t('common.exportOk'),
            key,
            duration: 2,
          });
          saveAs(res.data, `job_log_${Date.now()}.xlsx`);
        }
      });
    },
  });
}



/**关闭跳转 */
function fnClose(this: any) {
  router.back(); // 返回到上一个页面
}

onMounted(() => {
  // 指定任务id数据列表
  if (jobId && jobId !== '0') {
    doGetjobInfo(jobId).then(res => {
      if (!res.error) {
        console.log(res.data);
        searchParams.jobId = res.data.jobId;
        searchParams.jobName = res.data.jobName;
        searchParams.jobGroup = res.data.jobGroup;
        getData();
      }
    });
  } else {
    getData();
  }
})

</script>

<template>
  <SimpleScrollbar>
    <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
      <!-- 搜索框 -->
      <ACard :title="$t('common.search')" :bordered="false" class="card-wrapper">
        <AForm :model="searchParams" :label-width="80">
          <ARow :gutter="[16, 16]" wrap>
            <ACol :lg="6" :md="12" :xs="24" v-if="jobId !== '0'">
              <AFormItem label="Name" name="jobName" class="m-0">
                <AInput v-model:value="searchParams.jobName" :disabled="jobId !== '0'" />
              </AFormItem>
            </ACol>

            <ACol :lg="6" :md="12" :xs="24">
              <AFormItem label="Group" name="jobGroup" class="m-0">
                <AInput v-model:value="searchParams.jobGroup" />
              </AFormItem>
            </ACol>


            <ACol :lg="6" :md="12" :xs="24">
              <AFormItem :label="$t('page.manage.user.status')" name="status" class="m-0">
                <ASelect v-model:value="searchParams.status" :placeholder="$t('page.manage.user.form.status')"
                  allow-clear>
                  <ASelectOption v-for="option in enableStatusOptions" :key="option.value" :value="option.value">
                    {{ $t(option.label) }}
                  </ASelectOption>
                </ASelect>
              </AFormItem>
            </ACol>


            <ACol :lg="6" :md="12" :xs="24">
              <AFormItem class="m-0">
                <div class="w-full flex-y-center justify-end gap-8px">
                  <a-space :size="8">
                    <a-button @click="fnTest">
                      <template #icon>
                        <SyncOutlined />
                      </template>
                      {{ $t('common.reset') }}
                    </a-button>
                    <AButton type="primary" ghost @click="getData">
                      <template #icon>
                        <SearchOutlined />
                      </template>
                      {{ $t('common.search') }}
                    </AButton>
                  </a-space>

                </div>
              </AFormItem>
            </ACol>
          </ARow>
        </AForm>
      </ACard>

      <ACard title="Task Log" :bordered="false" :body-style="{ flex: 1, overflow: 'hidden' }"
        class="flex-col-stretch sm:flex-1-hidden card-wrapper">
        <template #extra>
          <div class="flex flex-wrap justify-end gap-x-12px gap-y-8px lt-sm:(w-200px py-12px)">
            <slot name="prefix"></slot>
            <slot name="default">

              <a-button type="default" size="small" @click.prevent="fnClose()">
                <template #icon>
                  <CloseOutlined />
                </template>
                {{ t('common.close') }}
              </a-button>

              <APopconfirm :title="$t('common.confirmDelete')" :disabled="checkedRowKeys.length === 0"
                @confirm="handleBatchDelete">
                <AButton size="small" danger :disabled="checkedRowKeys.length <= 0">
                  <div class="flex-y-center gap-8px">
                    <icon-ic-round-delete class="text-icon" />
                    <span>{{ $t('common.batchDelete') }}</span>
                  </div>
                </AButton>
              </APopconfirm>

              <APopconfirm :title="$t('common.confirmClean')" :disabled="checkedRowKeys.length === 0"
                @confirm="handleBatchDelete">
                <a-button size="small" type="dashed" danger @click.prevent="fnCleanList()">
                  <template #icon>
                    <DeleteOutlined />
                  </template>
                  {{ t('common.clearText') }}
                </a-button>
              </APopconfirm>

              <AButton size="small" @click="getData">
                <div class="flex-y-center gap-8px">
                  <icon-mdi-refresh class="text-icon" />
                  <span>{{ $t('common.refresh') }}</span>
                </div>
              </AButton>
              <AButton size="small" type="primary" @click="fnExportList">
                <template #icon>
                  <ExportOutlined />
                </template>
                <span>{{ $t('common.export') }}</span>
              </AButton>
            </slot>

            <slot name="suffix"></slot>
          </div>
        </template>


        <ATable ref="wrapperEl" row-key="jobLogId" :columns="columns" :data-source="data" :loading="loading"
          :row-selection="{
            selectedRowKeys: checkedRowKeys,
            onChange: handleUserSelectChange,
          }" size="small" :pagination="mobilePagination" :scroll="scrollConfig" class="h-full">
          <template #bodyCell="{ column, record }">

            <template v-if="column.key === 'status'">
              <a-switch v-model:checked="record.status" disabled checked-value="0" un-checked-value="1" size="small" />
            </template>

            <template v-if="column.key === 'jobLogId'">
              <a-space :size="8" align="center">
                <a-tooltip>
                  <template #title>{{ t('common.view') }}</template>
                  <a-button type="link" @click.prevent="fnRecordView(record.jobLogId)">
                    <template #icon>
                      <ProfileOutlined />
                    </template>
                  </a-button>
                </a-tooltip>
              </a-space>
            </template>

          </template>
        </ATable>



        <!-- <taskOperateDrawer v-model:visible="drawerVisible" :dept-tree-data="deptTreeData" :operate-type="operateType"
          :row-data="editingData" @submitted="getData" /> -->


        <!-- 详情框 -->
        <a-modal :width="800" v-model:open="modalState.openByView" :title="modalState.title" @cancel="fnModalCancel">
          <a-form layout=" horizontal" :label-col="{ span: 6 }" :label-wrap="true">
            <a-row>
              <a-col :lg="12" :md="12" :xs="24">
                <a-form-item :label="$t('page.manage.task.taskId')" name="jobLogId">
                  {{ modalState.from.jobLogId }}
                </a-form-item>
              </a-col>
              <a-col :lg="12" :md="12" :xs="24">
                <a-form-item :label="t('page.manage.task.status')" name="status">
                  {{
                    [{
                      label: t('common.normal'),
                      value: '0',
                    }, {
                      label: t('common.abnormal'),
                      value: '1',
                    }].find(s => s.value === modalState.from.status)
                      ?.label
                  }}
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :lg="12" :md="12" :xs="24">
                <a-form-item :label="$t('page.manage.task.taskName')" name="jobName">
                  {{ modalState.from.jobName }}
                </a-form-item>
              </a-col>
              <a-col :lg="12" :md="12" :xs="24">
                <a-form-item :label="t('page.manage.task.group')" name="jobGroup">
                  <!-- <DictTag
                :options="dict.sysJobGroup"
                :value="modalState.from.jobGroup"
              /> -->
                  {{ modalState.from.jobGroup }}
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :lg="12" :md="12" :xs="24">
                <a-form-item :label="t('page.manage.task.invoke')" name="invokeTarget">
                  {{ modalState.from.invokeTarget }}
                </a-form-item>
              </a-col>
              <!-- <a-col :lg="12" :md="12" :xs="24">
                <a-form-item :label="t('page.manage.task.log')" name="saveLog">
                  <DictTag
                :options="dict.sysJobSaveLog"
                :value="modalState.from.saveLog"
              />
                </a-form-item>
              </a-col> -->
              <a-col :lg="12" :md="12" :xs="24">
                <a-form-item :label="t('page.manage.task.createTime')" name="createTime" :label-wrap="true">
                  {{ modalState.from.createTime }}
                </a-form-item>
              </a-col>
            </a-row>



            <a-form-item :label="t('page.manage.task.targetParams')" name="targetParams" :label-col="{ span: 3 }"
              :label-wrap="true">
              <a-textarea v-model:value="modalState.from.targetParams" :auto-size="{ minRows: 2, maxRows: 6 }"
                :disabled="true" />
            </a-form-item>

            <a-form-item :label="t('page.manage.task.jobMessage')" name="jobMessage" :label-col="{ span: 3 }"
              :label-wrap="true">
              <a-textarea v-model:value="modalState.from.jobMessage" :auto-size="{ minRows: 2, maxRows: 6 }"
                :disabled="true" />
            </a-form-item>
          </a-form>
          <template #footer>
            <a-button key="cancel" @click="fnModalCancel">
              {{ t('common.close') }}
            </a-button>
          </template>
        </a-modal>
      </ACard>


    </div>
  </SimpleScrollbar>
</template>

<style scoped></style>
