<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="编辑配置" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import { updateDepartment } from '/@/api/system/dingding';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  const FormSchema: FormSchema[] = [
    {
      field: 'name',
      label: '名称',
      component: 'Input',
      colProps: { span: 24, style: { paddingTop: '16px' } },
      componentProps: {
        readonly: true,
      },
    },
    {
      field: 'name',
      label: '简称',
      component: 'Input',
      colProps: { span: 24 },
      componentProps: {
        readonly: true,
      },
    },
    {
      field: 'code',
      label: '编码',
      component: 'Input',
      colProps: { span: 24 },
      componentProps: {
        readonly: true,
      },
    },
    {
      field: 'dingAppKey',
      label: 'DingAppKey',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请填写应用的唯一标识key',
      },
    },
    {
      field: 'dingAppSecret',
      label: 'DingAppSecret',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请填写应用的密钥',
      },
    },
    {
      field: 'dingAgentId',
      label: 'DingAgentId',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请填写钉钉应用ID',
      },
    },
  ];

  const { notification } = useMessage();
  const record = ref();
  const emit = defineEmits(['success', 'register']);

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    schemas: FormSchema,
    showActionButtonGroup: false,
    layout: 'vertical',
    rowProps: {
      gutter: 32,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false, destroyOnClose: true, width: '35%' });
    record.value = data.record;
    setFieldsValue({
      ...record.value,
    });
  });

  const handleSubmit = async () => {
    try {
      const values = await validate();

      setModalProps({ confirmLoading: true });

      values.id = record.value.id;
      await updateDepartment(values);
      notification.success({
        message: '编辑',
        description: t('成功'),
      });

      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  };
</script>
