<template>
  <BasicDrawer
    v-bind="$attrs"
    destroyOnClose
    @register="registerDrawer"
    :title="getTitle"
    :width="width"
    @ok="handleSubmit"
    :showFooter="true"
  >
    <BasicForm @register="registerForm" layout="vertical" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { dataSendFormSchema } from './data';

  import { smsTempDetail, smsSend } from '/@/api/sys/smsTempApi';
  const emit = defineEmits(['success', 'register']);

  const getTitle = computed(() => '发送短信');
  const width = '45%';
  const rowId = ref();
  const templateCode = ref();
  const templateItme = ref([]);
  const { createMessage } = useMessage();
  const [registerForm, { resetFields, validate, appendSchemaByField }] = useForm({
    labelWidth: 100,
    schemas: dataSendFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async data => {
    await resetFields();
    setDrawerProps({ confirmLoading: false });
    const result = await smsTempDetail(data.record.id);
    rowId.value = result.id;
    templateCode.value = result.code;
    if (result && result.templateParams && result.templateParams.length > 0) {
      templateItme.value = result.templateParams;
      result.templateParams.forEach(item => {
        appendSchemaByField(
          {
            label: item,
            field: item,
            required: true,
            component: 'Input',
          },
          null,
        );
      });
    }
  });
  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      values.templateCode = templateCode.value;
      values.templateParams = {};
      await templateItme.value.forEach(item => {
        values.templateParams[item] = values[item];
      });
      await smsSend(values);
      createMessage.success('短信发送成功！');
      closeDrawer();
      emit('success', {
        values: { ...values, id: rowId.value },
      });
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" scoped>
  ::v-deep(.ant-divider-plain.ant-divider-with-text) {
    font-size: 17px !important;
  }
</style>
