<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert type="info" show-icon>
          <template #message>
            <template v-if="checkedKeys.length > 0">
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <a-button type="link" @click="setSelectedRowKeys([])" size="small">清空</a-button>
              <Popconfirm
                v-if="hasPermission('AUTH_DATA_TASK_PROGRESS:DELETE')"
                class="ml-4"
                title="确定要全部删除吗？"
                ok-text="是"
                cancel-text="否"
                @confirm="handleBatchDelete"
              >
                <a href="#" class="text-red-500">删除</a>
              </Popconfirm>
            </template>
            <template v-else>
              <span>未选中任何项目</span>
            </template>
          </template>
        </Alert>
      </template>
      <template #toolbar>
        <a-button v-auth="'AUTH_DATA_TASK_PROGRESS:ADD'" type="primary" @click="handleCreate"> 新增</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <TableAction
            :actions="[
              {
                label: '编辑',
                icon: 'clarity:note-edit-line',
                onClick: handleEdit.bind(null, record),
                ifShow: hasPermission('AUTH_DATA_TASK_PROGRESS:EDIT'),
                divider:true
              },
              {
                label: '详情',
                icon: 'ant-design:eye-outlined',
                onClick: handleView.bind(null, record),
                divider:true
              },
            ]"
            :dropDownActions="[
              {
                label: '删除',
                icon: 'ant-design:delete-outlined',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  confirm: handleDelete.bind(null, record),
                  placement: 'topRight',
                },
                ifShow: hasPermission('AUTH_DATA_TASK_PROGRESS:DELETE'),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <TaskProgressDrawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { Alert,Popconfirm } from 'ant-design-vue';
  import { useGo } from '@/hooks/web/usePage';
  import { usePermission } from '@/hooks/web/usePermission';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { isObject } from '@/utils/is';
  import dayjs from 'dayjs';
  import * as TaskProgressApi from '@/api/data/taskProgressApi';
  import { useDrawer } from '@/components/Drawer';
  import TaskProgressDrawer from './drawer.vue';
  import { columns, searchFormSchema } from './schema';
  import { useMessage } from "@/hooks/web/useMessage";

  defineOptions({
    name: 'AUTH_DATA_TASK_PROGRESS'
  })

  const { createMessage } = useMessage();
  const { hasPermission } = usePermission();
  const go = useGo();

  const checkedKeys = ref<Array<string | number>>([]);
  const onSelectChange = (selectedRowKeys: (string | number)[]) => {
    checkedKeys.value = selectedRowKeys.filter(k => typeof k !== 'undefined');
  }

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, setSelectedRowKeys }] = useTable({
    title: '任务检测过程数据表',
    api: (params) => TaskProgressApi.search(handleParams(params)),
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      showAdvancedButton: false,
    },
    rowSelection: {
      type: 'checkbox',
      onChange: onSelectChange,
    },
    useSearchForm: true,
    showTableSetting: false,
    bordered: false,
    showIndexColumn: false,
    canResize: false,
    rowKey: (record: any) => record.id,
    actionColumn: {
      width: 170,
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
    },
  });

  const handleParams = (params) => {
    const { pageNum, pageSize, field = 'id', order = 'descend', ...rest } = params;
    const handledParams: any = { pageNum, pageSize, orderByClause: `${field} ${order === 'descend' ? 'desc' : 'asc'}` };
    Object.keys(rest).forEach((key) => {
      const schema = searchFormSchema.find((item) => item.field === key);
      const value = params[key];
      const paramKey = key;
      if (schema) {
        if (value !== undefined && value !== '') {
          if (schema.component === 'Input') {
            handledParams[paramKey] = `%${value.trim()}%`;
          } else if (['Select', 'ApiSelect', 'ApiTreeSelect'].includes(schema.component)) {
            handledParams[paramKey] = isObject(value) ? value.value : value;
          } else if (schema.component === 'RangePicker') {
            handledParams[`${paramKey}From`] = dayjs(value[0]).startOf('d').format('YYYY-MM-DD HH:mm:ss');
            handledParams[`${paramKey}To`] = dayjs(value[1]).endOf('d').format('YYYY-MM-DD HH:mm:ss');
          } else if (schema.component === 'DatePicker') {
            handledParams[paramKey] = dayjs(value).format((schema.componentProps as any).format || 'YYYY-MM-DD');
          } else {
            handledParams[paramKey] = value;
          }
        }
      } else {
        handledParams[paramKey] = value;
      }
    });
    return handledParams;
  };

  const handleCreate = () => {
    openDrawer(true, {
      isUpdate: false,
    });
  };

  const handleEdit = (record: Recordable) => {
    openDrawer(true, {
      record,
      isUpdate: true,
    });
  };

  const handleDelete = (record: Recordable) => {
    TaskProgressApi.remove(record.id).then((_) => {
      reload();
      setSelectedRowKeys([])
    });
  };

  const handleBatchDelete = () => {
    if (checkedKeys.value.length === 0) {
      createMessage.error('当前未选中任何项目！');
      return;
    }
    TaskProgressApi.batchRemove(checkedKeys.value).then((_) => {
      reload();
      setSelectedRowKeys([])
    });
  };

  const handleSuccess = () => {
    reload();
  };

  const handleView = (record) => {
    go('/data/task-progress/detail/' + record.id);
  };
</script>
<style lang="less" scoped></style>
