<script lang="ts" setup>
import { computed, h, reactive, ref, unref } from "vue";
import { NDataTable, useDialog } from "naive-ui";
import type { DataTableColumns, DataTableRowKey } from "naive-ui";
import Action from "../comp/Action.vue";
import { RejectModal } from "./index";
import type { RowData } from "@/config/final";
import { getFinalList } from "@/api/final";
import type { ApprovalParam } from "/#/api";
import { audit } from "@/api/task/task";

const emit = defineEmits<{
  (e: "commit", columns: any[]);
}>();

const show = ref(false);

function showModal() {
  show.value = true;
}

function closeModal() {
  show.value = false;
}

async function handleSumbit(e: MouseEvent) {
  e.preventDefault();
  closeModal();
}

defineExpose({
  showModal,
});

const columns: DataTableColumns<RowData> = [
  {
    type: "selection",
    fixed: "left",
    width: 50,
  },
  {
    title: "任务Id",
    key: "id",
    fixed: "left",
    width: 100,
  },
  {
    title: "任务名称",
    key: "fromtaskname",
    fixed: "left",
    width: 200,
  },
  {
    title: "审批节点",
    key: "approvalnode",
    width: 100,
  },
  {
    title: "审批状态",
    key: "states",
    width: 100,
  },
  {
    title: "图片相似度",
    key: "similarity",
    width: 100,
  },
  {
    title: "提报时间",
    key: "fromuptime",
    width: 200,
  },
  {
    title: "更新时间",
    key: "updatetime",
    width: 200,
  },
  {
    title: "操作",
    key: "actions",
    width: 200,
    fixed: "right",
    render(row) {
      return h(Action, {
        id: row.id,
        status: row.states,
        trigger: actionHandler,
      });
    },
  },
];

const rejectModalRef = ref(null);
const columnsRef = ref(columns);
const tableRef = ref<InstanceType<typeof NDataTable>>();
const rowKey = (row: RowData) => row.id;
const loading = ref(true);
const total = ref(0);
const pagination = reactive({
  page: 1,
  pageCount: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [
    {
      label: "10 每页",
      value: 10,
    },
    {
      label: "15 每页",
      value: 15,
    },
    {
      label: "30 每页",
      value: 30,
    },
    {
      label: "50 每页",
      value: 50,
    },
  ],
  showQuickJumper: true,
  prefix:()=>`共 ${total.value} 条数据`
});
const tableData = ref<Array<RowData>>([]);
const selectionIds = ref<DataTableRowKey[]>([]);

const deviceHeight = ref(600);

const maxHeight = computed(() => {
  return tableData.value.length ? `${unref(deviceHeight)}px` : "auto";
});

async function query(page: number, pageSize: number) {
  const result = await getFinalList({
    sortorder: "asc",
    pageSize: 10,
    currPage: 1,
    sortname: "",
  });
  const { data, pageCount,totalCount } = result;
  total.value = totalCount;
  tableData.value = data;
  pagination.page = page;
  pagination.pageCount = pageCount;
  loading.value = false;
}

async function handlePageChange(currentPage) {
  if (loading.value) return;
  pagination.page = currentPage;
  const { pageSize } = pagination;
  await query(currentPage, pageSize);
}
async function handlePageSizeChange(currentPageSize) {
  if (loading.value) return;

  const { page } = pagination;
  pagination.pageSize = currentPageSize;

  await query(page, currentPageSize);
}

function handleCheck(rowKeys: DataTableRowKey[]) {
  selectionIds.value = rowKeys;
}

function actionHandler(action: any) {
  const { key } = action;
  switch (key) {
    case "view":
      break;
    case "reset":
      resetHandler();
      break;
    case "approval":
      approvalHandler();
      break;
    case "reject":
      (rejectModalRef.value as any).showModal();
      break;
    default:
      break;
  }
}

const dialog = useDialog();

function resetHandler() {
  dialog.info({
    title: "确认提示",
    content: "确认重置当前选中的任务的审批吗?",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: async () => {
      // TODO：需要支持重置
      // const result = await resetApproval()
    },
    onNegativeClick: () => {},
  });
}

function approvalHandler() {
  dialog.info({
    title: "确认提示",
    content: "确认给该任务审批为【通过】吗?",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: () => {
      // TODO：调用批量审批接口
    },
    onNegativeClick: () => {},
  });
}

function rejectHandler(idOrDesc: string, isOther: boolean) {
  // TODO:实现批量拒绝
  // const param: ApprovalParam = {
  //   formid: '',
  //   taskId: '',
  //   approvd: false,
  //   taskComment: '',
  // }
  // if (isOther)
  //   param.taskComment = idOrDesc
  // else
  //   param.taskComment = idOrDesc
  // audit(param)
}

query(pagination.page, pagination.pageSize);
</script>

<template>
  <div>
    <n-modal v-model:show="show" transform-origin="center">
      <n-card
        class="cardstyle"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <div class="wrapper">
          <span class="wrapper-title">重复任务</span>
          <div class="wrapper-bar">
            <div class="wrapper-info">
              <span :style="{ 'margin-left': '18px' }">任务信息</span>
            </div>
          </div>
          <div class="wrapper-content">
            <NDataTable
              ref="tableRef"
              remote
              :columns="columnsRef"
              :scroll-x="1250"
              :max-height="maxHeight"
              :data="tableData"
              :loading="loading"
              :pagination="pagination"
              :row-key="rowKey"
              @update:page="handlePageChange"
              @update-page-size="handlePageSizeChange"
              @update:checked-row-keys="handleCheck"
            />
          </div>
        </div>
        <template #footer>
          <div class="wrapper-footer">
            <n-button type="info" @click="handleSumbit"> 确认 </n-button>
            <n-button secondary style="margin-left: 15px" @click="closeModal">
              取消
            </n-button>
          </div>
        </template>
      </n-card>
    </n-modal>
    <RejectModal ref="rejectModalRef" @commit="rejectHandler" />
  </div>
</template>

<style lang="less" scoped>
.wrapper {
  display: flex;
  flex-direction: column;

  &-title {
    font-weight: bold;
    font-size: 16px;
  }

  &-bar {
    background-color: #e8e8e8;
    width: 100%;
    margin-top: 20px;
  }

  &-content {
    flex: auto;
    background: #fff;
    margin-top: 20px;
  }

  &-footer {
    display: flex;
    justify-content: flex-end;
  }

  &-info {
    font-weight: bold;
    position: relative;

    &:before {
      background-color: #1980ff;
      content: "";
      width: 5px;
      border-radius: 2px;
      top: 0;
      bottom: 0;
      position: absolute;
    }
  }
}

.cardstyle {
  width: 820px;
  height: 800px;
  --n-padding-bottom: 20px;
  --n-padding-left: 24px;
}

::v-deep(.n-card.n-card--content-segmented > .n-card__content:not(:first-child)) {
  border: 0px;
}

::v-deep(.n-card > .n-card-header) {
  --n-padding-top: 0px;
  --n-padding-bottom: 12px;
}
</style>
