<template>
  <div>
    <BasicTable @register="registerTable" :clickToRowSelect="false">
      <template #toolbar>
        <Authority value="api:yt:template:post">
          <a-button type="primary" @click="handleCreate"> 新增消息模板 </a-button>
        </Authority>
        <Authority value="api:yt:template:delete">
          <Popconfirm
            title="您确定要批量删除数据"
            ok-text="确定"
            cancel-text="取消"
            @confirm="handleDeleteOrBatchDelete(null)"
          >
            <a-button color="error" :disabled="hasBatchDelete"> 批量删除 </a-button>
          </Popconfirm>
        </Authority>
      </template>
      <template #config="{ record }">
        <a-button type="link" class="ml-2" @click="goConfig">
          {{ record.messageConfig?.configName }}
        </a-button>
      </template>
      <template #status="{ record }">
        <Switch
          :checked="record.status === 1"
          :loading="record.pendingStatus"
          checkedChildren="启用"
          unCheckedChildren="禁用"
          @change="(checked:boolean)=>statusChange(checked,record)"
        />
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '发送',
              auth: 'api:yt:template:sendEmail:post',
              icon: 'ant-design:send-outlined',
              onClick: handleModal.bind(null, record),
            },
            {
              label: '编辑',
              auth: 'api:yt:template:update',
              icon: 'clarity:note-edit-line',
              onClick: handleEdit.bind(null, record),
            },
            {
              label: '删除',
              auth: 'api:yt:template:delete',
              icon: 'ant-design:delete-outlined',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDeleteOrBatchDelete.bind(null, record),
              },
              ifShow: record.status == 0,
            },
          ]"
        />
      </template>
    </BasicTable>
    <SendSms @register="registerModal" />
    <SendEmail @register="registerMailModal" />
    <TemplateDrawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, nextTick } from 'vue';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { useDrawer } from '/@/components/Drawer';
  import TemplateDrawer from './TemplateDrawer.vue';
  import { columns, searchFormSchema } from './template.data';
  import { deleteMessageTemplate, messageTemplatePage } from '/@/api/message/template';
  import { useGo } from '/@/hooks/web/usePage';
  import { PageEnum } from '/@/enums/pageEnum';
  import { useModal } from '/@/components/Modal';
  import SendSms from '/@/views/message/template/SendSms.vue';
  import { MessageEnum } from '/@/enums/messageEnum';
  import SendEmail from '/@/views/message/template/SendEmail.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useBatchDelete } from '/@/hooks/web/useBatchDelete';
  import { Switch, Popconfirm } from 'ant-design-vue';
  import { setMessageTemplateStatus } from '/@/api/message/template';
  import { Authority } from '/@/components/Authority';

  export default defineComponent({
    name: 'MessageTemplateManagement',
    components: {
      SendSms,
      SendEmail,
      BasicTable,
      TemplateDrawer,
      TableAction,
      Switch,
      Authority,
      Popconfirm,
    },
    setup() {
      const [registerModal, { openModal: openModal }] = useModal();
      const [registerMailModal, { openModal: openMailModal }] = useModal();
      const go = useGo();
      function handleSuccess() {
        reload();
      }
      const [registerDrawer, { openDrawer }] = useDrawer();

      const [registerTable, { reload, setProps, setSelectedRowKeys }] = useTable({
        title: '消息模板列表',
        api: messageTemplatePage,
        columns,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
        },
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        showIndexColumn: false,
        actionColumn: {
          width: 200,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right',
        },
      });
      const { hasBatchDelete, handleDeleteOrBatchDelete, selectionOptions, resetSelectedRowKeys } =
        useBatchDelete(deleteMessageTemplate, handleSuccess, setProps);
      selectionOptions.rowSelection.getCheckboxProps = (record: Recordable) => {
        // Demo:status为1的选择框禁用
        if (record.status === 1) {
          return { disabled: true };
        } else {
          return { disabled: false };
        }
      };
      nextTick(() => {
        setProps(selectionOptions);
      });

      function handleCreate() {
        openDrawer(true, {
          isUpdate: false,
        });
      }

      function handleEdit(record: Recordable) {
        openDrawer(true, {
          record,
          isUpdate: true,
        });
      }

      function handleModal(record: Recordable) {
        let openSms = false;
        let openEmail = false;
        const messageType = Reflect.get(record, 'messageType');
        if (messageType === MessageEnum.IS_SMS) {
          openSms = true;
        } else if (messageType === MessageEnum.IS_EMAIL) {
          openEmail = true;
        }
        if (openSms) {
          openModal(openSms, {
            record,
          });
        }
        if (openEmail) {
          openMailModal(openEmail, {
            record,
          });
        }
      }

      function goConfig() {
        go(PageEnum.MESSAGE_CONFIG);
      }
      const statusChange = async (checked, record) => {
        setProps({
          loading: true,
        });
        setSelectedRowKeys([]);
        resetSelectedRowKeys();
        const newStatus = checked ? 1 : 0;
        const { createMessage } = useMessage();
        try {
          const { id, templatePurpose, messageType, tenantId } = record;
          await setMessageTemplateStatus({
            id,
            templatePurpose,
            messageType,
            tenantId,
            status: newStatus,
          });
          if (newStatus) {
            createMessage.success(`启用成功`);
          } else {
            createMessage.success('禁用成功');
          }
        } finally {
          setProps({
            loading: false,
          });
          reload();
        }
      };
      return {
        registerTable,
        registerDrawer,
        registerModal,
        registerMailModal,
        handleCreate,
        handleEdit,
        handleSuccess,
        handleModal,
        goConfig,
        handleDeleteOrBatchDelete,
        statusChange,
        hasBatchDelete,
      };
    },
  });
</script>
