<!--
  功能：功能描述
  作者：Aaron.Wu
  时间：2023年05月25日 17:00:26
  版本：v1.0
  修改记录：
  修改内容：
  修改人员：
  修改时间：
-->
<template>
  <!-- <QuillEditor theme="snow" /> -->
  <DynamicTable
    size="small"
    showIndex
    headerTitle="问题工单列表"
    titleTooltip=""
    :data-request="loadData"
    :columns="columns"
    row-key="id"
    @resize-column="handleResizeColumn"
    :row-selection="rowSelection"
    :scroll="{ x: '100vw' }"
  >
    <template v-if="isCheckRows" #title>
      <Alert class="w-full" type="info" show-icon>
        <template #message>
          已选 {{ isCheckRows }} 项
          <a-button type="link" @click="rowSelection.selectedRowKeys = []">取消选择</a-button>
        </template>
      </Alert>
    </template>
    <template #toolbar>
      <a-button type="primary" @click="openIssueModal({})">新增</a-button>
      <a-button
        type="danger"
        :disabled="!isCheckRows"
        @click="delRowConfirm(rowSelection.selectedRowKeys)"
      >
        <DeleteOutlined /> 删除
      </a-button>
    </template>
  </DynamicTable>
</template>

<script lang="tsx" setup>
  // import { QuillEditor } from '@vueup/vue-quill';
  import '@vueup/vue-quill/dist/vue-quill.snow.css';
  import { type TableListItem, baseColumns } from './columns';
  import { useTable, type OnChangeCallbackParams } from '@/components/core/dynamic-table';
  import {
    fetchIssuePageList,
    createIssue,
    updateIssue,
    deleteIssueById,
    deleteBatchIssueById,
  } from '@/api/issue';
  import { computed, ref } from 'vue';
  import { Modal, message, Alert } from 'ant-design-vue';

  import { useFormModal } from '@/hooks/useModal/index';
  import { issueSchemas } from './formSchemas';
  import { ExclamationCircleOutlined, DeleteOutlined } from '@ant-design/icons-vue';

  defineOptions({
    name: 'issue',
  });

  // const content = ref('');
  // const editorOptions = {
  //   theme: 'snow', // 设置主题
  //   modules: {
  //     toolbar: [
  //       [{ header: '1' }, { header: '2' }],
  //       ['bold', 'italic'],
  //       ['link'],
  //       ['blockquote', 'code-block'],
  //     ],
  //   },
  // };

  const [showModal] = useFormModal();

  const columns: any = [
    ...baseColumns,
    {
      title: '操作',
      width: 200,
      dataIndex: 'ACTION',
      hideInSearch: true,
      align: 'center',
      fixed: 'right',
      actions: ({ record }) => [
        {
          icon: 'searchoutlined',
          color: '#3b82f6',
          label: '查看',
          onClick: () => handleShow(record),
        },
        {
          icon: 'edit',
          color: '#3b82f6',
          size: '15',
          label: '修改',
          onClick: () => handleEdit(record),
        },
        {
          icon: 'delete',
          color: '#ec6f6f',
          label: '删除',
          popConfirm: {
            title: '确定要删除吗？',
            onConfirm: () => handleDelete(record.id),
          },
        },
      ],
    },
  ];
  /**
   * @description 打开问题工单弹窗
   */
  const openIssueModal = async (record: Partial<TableListItem> = {}, isReadOnly = false) => {
    const [formRef] = await showModal<any>({
      modalProps: {
        title: `${isReadOnly ? '查看' : record.id ? '编辑' : '新增'}问题工单`,
        width: 700,
        onFinish: async (values) => {
          console.log('新增/编辑问题工单', values);
          values.id = record.id;
          await (record.id ? updateIssue : createIssue)(values);
          message.success(`${record.id ? '编辑' : '新增'}成功`);
          dynamicTableInstance?.reload();
        },
        footer: isReadOnly ? null : undefined,
      },
      formProps: {
        labelWidth: 100,
        schemas: issueSchemas as any,
        autoSubmitOnEnter: true,
        disabled: isReadOnly,
      },
    });

    formRef?.setFieldsValue(record);
    // if (record?.id) {
    //   const { roles } = await getIssueInfo({ issueId: record.id });
    //   formRef?.setFieldsValue({ roles });
    // }
  };

  const handleEdit = (record: TableListItem) => {
    openIssueModal(record);
  };

  const handleShow = (record: TableListItem) => {
    openIssueModal(record, true);
  };

  const handleDelete = (id: string) => {
    delRowConfirm(id);
  };

  /**
   * @description 表格删除行
   */
  const delRowConfirm = async (id: string | string[]) => {
    Modal.confirm({
      title: '确定要删除所选的问题工单吗?',
      icon: <ExclamationCircleOutlined />,
      centered: true,
      onOk: async () => {
        if (Array.isArray(id)) {
          // 多个删除
          await deleteBatchIssueById(id).finally(dynamicTableInstance?.reload);
        } else {
          await deleteIssueById({ id }).finally(dynamicTableInstance?.reload);
        }
      },
    });
  };

  const [DynamicTable, dynamicTableInstance] = useTable();

  const rowSelection = ref<any>({
    selectedRowKeys: [] as string[],
    onChange: (selectedRowKeys: string[], selectedRows: TableListItem[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      rowSelection.value.selectedRowKeys = selectedRowKeys;
    },
  });

  // 是否勾选了表格行
  const isCheckRows = computed(() => rowSelection.value.selectedRowKeys.length);

  const loadData = async (
    params,
    onChangeParams?: OnChangeCallbackParams,
  ): Promise<API.TableListResult> => {
    console.log('params', params);
    console.log('onChangeParams', onChangeParams);
    // 手动设置搜索表单的搜索项
    // dynamicTableInstance?.getQueryFormRef()?.updateSchema?.([
    //   {
    //     field: 'price',
    //     componentProps: {
    //       options: [
    //         {
    //           label: '0-199',
    //           value: '0-199',
    //         },
    //         {
    //           label: '200-999',
    //           value: '200-999',
    //         },
    //       ],
    //     },
    //   },
    // ]);
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          list: [
            {
              id: '1',
              name: '1',
            },
          ],
          ...params,
        });
      }, 500);
    });
    const res = await fetchIssuePageList({
      ...params,
      current: params.page,
      size: params.limit,
    });
    console.log('res: ', res);
    rowSelection.value.selectedRowKeys = [];

    return {
      list: res.data.list,
      pagination: {
        total: Number(res.data.total),
        ...params,
      },
    };
  };
  const handleResizeColumn = (w, col) => {
    // console.log('w', w, col);
    col.width = w;
  };
</script>

<style lang="less" scoped>
  .action-divider {
    margin: 0 5px;
  }
</style>
