<template>
  <ResizePageWrapper>
    <template #resizeLeft>
      <BasicTree
        search
        :title="t('模板类型')"
        :clickRowToExpand="true"
        :treeData="data.treeData"
        :fieldNames="{ key: 'id', title: 'name' }"
        :selectedKeys="[data.classifyId]"
        @select="handleSelect"
      />
    </template>

    <template #resizeRight>
      <BasicTable @register="registerTable" isMenuTable>
        <template #toolbar>
          <a-button type="primary" @click="handleCreate" v-auth="'messageTemplate:add'">{{
            t('新增')
          }}</a-button>
        </template>

        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                label: '编辑',
                auth: 'messageTemplate:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                auth: 'messageTemplate:delete',
                color: 'error',
                popConfirm: {
                  title: t('是否确认删除'),
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </BasicTable>
    </template>
    <FormModal @register="registerModal" @success="handleSuccess" />
  </ResizePageWrapper>
</template>
<script lang="ts" setup>
  import { onMounted, reactive, h } from 'vue';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { Tag } from 'ant-design-vue';
  import { ResizePageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getDicDetailList } from '/@/api/system/dic';
  import FormModal from './components/Form.vue';
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import { MessageTemplateCategory } from '/@/enums/messageTemplateEnum';
  import { deleteDesign, getPage } from '/@/api/system/generator/messageTemplate';
  import { useModal } from '/@/components/Modal';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { t } = useI18n();
  const configColumns: BasicColumn[] = [
    {
      title: t('编码'),
      dataIndex: 'code',
      align: 'center',
      resizable: true,
    },
    {
      title: t('名称'),
      dataIndex: 'name',
      align: 'center',
      resizable: true,
    },
    {
      title: t('模板类型'),
      dataIndex: 'templateTypeName',
      align: 'center',
      resizable: true,
    },
    {
      title: t('消息类型'),
      dataIndex: 'messageTypeName',
      align: 'center',
      resizable: true,
    },
    {
      title: t('状态'),
      dataIndex: 'enabledMark',
      componentType: 'input',
      customRender: ({ record }) => {
        const color = record.enabledMark ? 'blue' : 'red';
        const text = record.enabledMark ? t('已启用') : t('已禁用');
        return h(Tag, { color: color }, () => text);
      },
      sorter: true,
      align: 'center',
      resizable: true,
    },
    {
      title: t('备注'),
      dataIndex: 'remark',
      width: 120,
      align: 'center',
      resizable: true,
    },
  ];
  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: '',
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: t('请输入关键字'),
      },
    },
  ];
  const { notification } = useMessage();
  const { hasPermission } = usePermission();

  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload, clearSelectedRowKeys }] = useTable({
    title: t('消息模板列表'),
    api: getPage,
    rowKey: 'id',
    columns: configColumns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      showResetButton: false,
    },
    beforeFetch: (params) => {
      //发送请求默认新增  左边树结构所选机构id
      return { ...params, category: data.classifyId, isAuth: false };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    pagination: {
      pageSize: 18,
    },
    actionColumn: {
      width: 88,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    tableSetting: {
      size: false,
    },
    customRow: (record) => {
      return {
        ondblclick: () => {
          if (hasPermission('messageTemplate:edit')) {
            handleEdit(record);
          }
        },
      };
    },
  });

  let data: {
    treeData: Array<TreeItem>;
    classifyId: string;
    xml: string;
  } = reactive({
    treeData: [],
    classifyId: '1747131473466900481',
    xml: '',
  });

  onMounted(() => {
    getCategoryTree();
  });
  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
  }
  function handleSuccess() {
    reload();
  }
  async function handleEdit(record: Recordable) {
    openModal(true, {
      isUpdate: true,
      ...record,
    });
  }

  function handleDelete(record: Recordable) {
    deleteDesign([record.id]).then((_) => {
      notification.success({
        message: t('提示'),
        description: t('删除成功'),
      }); //提示消息
      reload();
    });
  }

  function handleSelect(selectIds: Array<string>) {
    clearSelectedRowKeys();
    data.classifyId = selectIds[0];
    reload();
  }

  async function getCategoryTree() {
    let res = (await getDicDetailList({
      itemId: MessageTemplateCategory.ID,
    })) as unknown as TreeItem[];
    data.treeData = res;
  }
</script>
