<script setup lang="tsx">
import { NButton, NDropdown, NPopconfirm, NTag } from 'naive-ui';
import { useRouter } from 'vue-router';
import {ref, h} from 'vue';
import { useBoolean } from '@sa/hooks';
import {
  fetchBatchDeleteWorkflow,
  fetchDeleteWorkflowHistory,
  fetchGetWorkflowPageList,
  fetchUpdateWorkflowStatus, fetchWorkflowHistory
} from '@/service/api';
import index from "@/views/namespace/index.vue";

import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { triggerTypeRecord } from '@/constants/business';
import StatusSwitch from '@/components/common/status-switch.vue';
import { tagColor } from '@/utils/common';
import { useAuth } from '@/hooks/business/auth';
import { downloadFetch } from '@/utils/download';
import { useRouterPush } from '@/hooks/common/router';
import WorkflowSearch from './modules/workflow-search.vue';
import WorkflowTriggerModal from './modules/workflow-trigger-modal.vue';
// import { DeleteTwotone } from '@vicons'
import Delete24Regular from '@vicons/fluent/Delete24Regular'
import BookSearch20Regular from '@vicons/fluent/BookSearch20Regular'
const { hasAuth } = useAuth();

const router = useRouter();
const appStore = useAppStore();
const { routerPushByKey } = useRouterPush();

const triggerData = ref<Api.Workflow.Workflow | null>();
const { bool: triggerVisible, setTrue: openTriggerModal } = useBoolean(false);
const showModal =  ref(false);
const bodyStyle = ref({
    width: '900px'
  });
const verData = ref();
const rowClassName = (row:any) => {
  console.log(row);
  return row.version === 0 ? 'current-version-row' : ''
}
const  pagination= ref(
  {
    pageSize: 5
  }
)
const verColumns = ref([
  {
    key: 'id',
    title: $t('common.index'),
    align: 'center',
    width: 120
  },
  {
    key: 'version',
    title: '版本',
    align: 'center',
    width: 120,
    // render: (row) => `v${row.version}`
    render(row:any,index:any) {
      return h('div', {
        class: index === 0 ? 'brush-mark' : '',
        style: { display: 'inline-block' }
      }, `v${row.version}`)
    }
  },
  {
    key: 'workflowName',
    title: '描述',
    align: 'center',
    width: 120
  },
  {
    key: 'createDt',
    title: '创建时间',
    align: 'center',
    width: 120
  },
  {
    key: 'operate',
    title: $t('common.operate'),
    align: 'center',
    fixed: 'right',
    width: 200,
    render: (row:any, { index:any }) => {
      console.log(index)
      return (
        <div class="flex-center gap-8px">
          <NButton text type="warning" ghost size="small" onClick={() => detail(row.id!)}>
            <n-icon size="26" color="#0e7a0d">
              <BookSearch20Regular />
            </n-icon>
          </NButton>

          <n-divider vertical />

          <div class="flex-center">
            <NPopconfirm onPositiveClick={() => handleDeleteVer(row.id,row.version)}  >
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton quaternary type="error" size="small"  disabled={!row || index === undefined}>
                    <n-icon size="26" color="#0e7a0d">
                      <Delete24Regular />
                    </n-icon>
                  </NButton>
                )
              }}
            </NPopconfirm>
          </div>
        </div>
      );
    }
  }

]);
const { columns, columnChecks, data, getData, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: fetchGetWorkflowPageList,
  apiParams: {
    page: 1,
    size: 10,
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
    workflowName: null,
    groupName: null,
    workflowStatus: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'id',
      title: $t('common.index'),
      align: 'center',
      width: 120
    },
    {
      key: 'workflowName',
      title: $t('page.workflow.workflowName'),
      align: 'left',
      minWidth: 120,
      render: row => {
        function showDetailDrawer() {
          detail(row.id!);
        }

        return (
          <n-button text tag="a" type="primary" onClick={showDetailDrawer} class="ws-normal">
            {row.workflowName}
          </n-button>
        );
      }
    },
    {
      key: 'groupName',
      title: $t('page.workflow.groupName'),
      align: 'left',
      minWidth: 120
    },
    {
      key: 'nextTriggerAt',
      title: $t('page.workflow.nextTriggerAt'),
      align: 'left',
      minWidth: 120
    },
    {
      key: 'workflowStatus',
      title: $t('page.workflow.workflowStatus'),
      align: 'left',
      minWidth: 120,
      render: row => {
        const fetchFn = async (workflowStatus: Api.Common.EnableStatusNumber, callback: (flag: boolean) => void) => {
          const { error } = await fetchUpdateWorkflowStatus(row.id!);
          if (!error) {
            row.workflowStatus = workflowStatus;
            window.$message?.success($t('common.updateSuccess'));
          }
          callback(!error);
        };

        return <StatusSwitch v-model:value={row.workflowStatus} onSubmitted={fetchFn} />;
      }
    },
    {
      key: 'triggerType',
      title: $t('page.workflow.triggerType'),
      align: 'left',
      minWidth: 120,
      render: row => {
        if (!row.triggerType) {
          return null;
        }

        const label = $t(triggerTypeRecord[row.triggerType!]);
        return <NTag type={tagColor(row.triggerType)}>{label}</NTag>;
      }
    },
    {
      key: 'triggerInterval',
      title: $t('page.workflow.triggerInterval'),
      align: 'left',
      minWidth: 120
    },
    {
      key: 'executorTimeout',
      title: $t('page.workflow.executorTimeout'),
      align: 'left',
      minWidth: 120
    },
    {
      key: 'updateDt',
      title: $t('page.workflow.updateDt'),
      align: 'left',
      minWidth: 120
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 200,
      render: row => {
        const options = [
          {
            label: $t('common.copy'),
            key: 'copy',
            click: () => copy(row.id!)
          },
          {
            type: 'divider',
            key: 'd2'
          },
          {
            label: $t('common.batchList'),
            key: 'batchList',
            click: () => goToBatch(row.id!)
          },
          {
            type: 'divider',
            key: 'd2'
          },
          {
            type: 'render',
            key: 'delete',
            render: () => (
              <div class="flex-center">
                <NPopconfirm onPositiveClick={() => handleDelete(row.id!)}>
                  {{
                    default: () => $t('common.confirmDelete'),
                    trigger: () => (
                      <NButton quaternary size="small">
                        {$t('common.delete')}
                      </NButton>
                    )
                  }}
                </NPopconfirm>
              </div>
            )
          },
          {
            type: 'divider',
            key: 'd2'
          },
          {
            // type:'render',
            label: '版本',
            key: 'version',
            click: () => showVer(row.id!)
          }
        ];

        const onSelect = (key: string) => {
          const fun = options.filter(o => o.key === key)[0].click;
          if (fun) fun();
        };

        return (
          <div class="flex-center gap-8px">
            <NButton text type="warning" ghost size="small" onClick={() => edit(row.id!)}>
              {$t('common.edit')}
            </NButton>

            <n-divider vertical />

            <NButton type="error" text ghost size="small" onClick={() => execute(row)}>
              {$t('common.execute')}
            </NButton>

            <n-divider vertical />

            <NDropdown trigger="click" show-arrow={false} options={options} size="small" on-select={onSelect}>
              {{
                default: () => (
                  <NButton text type="primary" ghost size="small">
                    更多
                  </NButton>
                )
              }}
            </NDropdown>
          </div>
        );
      }
    }
  ]
});

const {
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

async function handleBatchDelete() {
  const { error } = await fetchBatchDeleteWorkflow(checkedRowKeys.value);
  if (error) return;
  onBatchDeleted();
}

async function handleDelete(id: string) {
  // request
  const { error } = await fetchBatchDeleteWorkflow([id!]);
  if (error) return;
  onDeleted();
}

async function handleDeleteVer(id: string,version:string){
  // request
  const { error } = await fetchDeleteWorkflowHistory(id,version);
  if (!error){
    const { data, error } = await fetchWorkflowHistory(id);
    verData.value = data
  } return;


}
function edit(id: string) {
  router.push({ path: '/workflow/form/edit', query: { id } });
}

function handleAdd() {
  router.push({ path: '/workflow/form/add' });
}

function detail(id: string) {
  router.push({ path: '/workflow/form/detail', query: { id } });
}

function copy(id: string) {
  router.push({ path: '/workflow/form/copy', query: { id } });
}

async function  showVer(id: string){
  console.log(id);
  showModal.value = true;
  console.log(showModal.value)
  const { data, error } = await fetchWorkflowHistory(id);
  if (!error) {
      verData.value = data
    console.log("verData"+verData.value)
  } else {

    window.$message?.error('获取工作流历史版本失败');
  }
  //请求数据
}

function dispVer(){
  // showModal.value = false;

}

async function execute(row: Api.Workflow.Workflow) {
  triggerData.value = row;
  openTriggerModal();
}

function body(): Api.Workflow.ExportWorkflow {
  return {
    workflowIds: checkedRowKeys.value,
    groupName: searchParams.groupName,
    workflowName: searchParams.workflowName,
    workflowStatus: searchParams.workflowStatus
  };
}

function handleExport() {
  downloadFetch('/workflow/export', body(), $t('page.workflow.title'));
}
function goToBatch(workflowId: string) {
  const findItem = data.value.find(item => item.id === workflowId)!;
  routerPushByKey('workflow_batch', { state: { workflowId, workflowName: findItem.workflowName } });
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <WorkflowSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getData" />
    <DeleteAlert />
    <NCard
      :title="$t('page.workflow.title')"
      :bordered="false"
      size="small"
      class="sm:flex-1-hidden card-wrapper"
      header-class="view-card-header"
    >
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          :show-delete="hasAuth('R_ADMIN')"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        >
          <template #addAfter>
            <FileUpload action="/workflow/import" accept="application/json" @refresh="getData" />
            <NPopconfirm @positive-click="handleExport">
              <template #trigger>
                <NButton size="small" ghost type="primary" :disabled="checkedRowKeys.length === 0 && hasAuth('R_USER')">
                  <template #icon>
                    <IconPajamasExport class="text-icon" />
                  </template>
                  {{ $t('common.export') }}
                </NButton>
              </template>
              <template #default>
                {{
                  checkedRowKeys.length === 0
                    ? $t('common.exportAll')
                    : $t('common.exportPar', { num: checkedRowKeys.length })
                }}
              </template>
            </NPopconfirm>
          </template>
        </TableHeaderOperation>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        :flex-height="!appStore.isMobile"
        :scroll-x="1300"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <n-modal
        v-model:show="showModal"
        class="custom-card"
        preset="card"
        title="版本信息"
        size="huge"
        :bordered="false"
        :style="bodyStyle"
      >
        <template #header-extra>
        </template>
          <n-data-table
            size="small"
            :columns="verColumns"
            :data="verData"
            :row-props:any="rowClassName"
            :pagination="pagination"
          />
        <template #footer>
<!--          <n-flex justify="end">-->
<!--            <n-button strong secondary round type="info" :on-click="dispVer()">-->
<!--              关闭-->
<!--            </n-button>-->
<!--          </n-flex>-->
        </template>
      </n-modal>
    </NCard>
    <WorkflowTriggerModal v-model:visible="triggerVisible" :row-data="triggerData" />
  </div>
</template>

<style scoped>
:deep(.brush-mark) {
  position: relative;
  z-index: 1;
  padding: 0 2px;
}

:deep(.brush-mark::after) {
  content: '';
  position: absolute;
  left: -27px;
  bottom: 2px;
  width: 80px ;
  height: 24px;
  background: linear-gradient(
    90deg,
    rgba(255, 165, 0, 0.2),
    rgba(255, 165, 0, 0.5) 50%,
    rgba(255, 165, 0, 0.2)
  );
  z-index: -1;
  transform: rotate(-1deg) skewX(-10deg);
  border-radius: 3px;
}

:deep(.current-version-row td) {
  background-color: #fff8e6;
  font-weight: 500;
}
</style>
