<template>
  <Modal
    centered
    width="800px"

    visible
    :title="dialogTitle"
    :confirmLoading="loading"
    @ok="confirm"
    @cancel="emits('cancel')"
  >
    <Form ref="formRef" :model="form.data" layout="vertical">
      <Row :gutter="24">
        <Col :span="12">
          <FormItem
            name="name"
            label="名称"
            :rules="[
              { required: true, message: '请输入名称' },
              { max: 64, message: '最多可输入64个字符' }
            ]"
          >
            <Input v-model:value="form.data.name" placeholder="请输入名称" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem name="typeId" label="类型" :rules="[{ required: true, message: '请选择类型' }]">
            <JDictSelectTag
              placeholder="请选择类型"
              v-model:value="form.data.typeId"
              dictCode="data_source_type"
              allow-clear
              :disabled="!!form.data.id"
            />
            <!--            <j-select v-model:value="form.data.typeId" :options="form.typeOptions" placeholder="请选择类型" :disabled="!!form.data.id" />-->
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="24" v-if="form.data.typeId === 'rdb'">
        <Col :span="24">
          <FormItem
            :name="['shareConfig', 'url']"
            label="URL"
            :rules="[
              {
                required: true,
                message: '请输入URL',
                trigger: 'change'
              },
              { validator: checkUrl, trigger: 'blur' }
            ]"
          >
            <Input
              v-model:value="form.data.shareConfig.url"
              placeholder="请输入r2bdc或者jdbc连接地址，示例：r2dbc:mysql://127.0.0.1:3306/test"
            />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="24" v-if="form.data.typeId === 'rabbitmq'">
        <Col :span="24">
          <FormItem
            :name="['shareConfig', 'adminUrl']"
            label="管理地址"
            :rules="[{ required: true, message: '请输入管理地址' }, { validator: validateAdminUrl }]"
          >
            <Input
              v-model:value="form.data.shareConfig.adminUrl"
              placeholder="请输入管理地址，示例：http://localhost:15672"
            />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="24" v-if="form.data.typeId === 'rabbitmq'">
        <Col :span="24">
          <FormItem
            :name="['shareConfig', 'addresses']"
            label="链接地址"
            :rules="[{ required: true, message: '请输入链接地址' }, { validator: validateAddress }]"
          >
            <Input v-model:value="form.data.shareConfig.addresses" placeholder="请输入链接地址，示例：localhost:5672" />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="24" v-show="form.data.typeId">
        <Col :span="12">
          <FormItem
            :name="['shareConfig', 'username']"
            label="用户名"
            :rules="[
              { required: true, message: '请输入用户名' },
              {
                max: 64,
                message: '最多可输入64个字符'
              }
            ]"
          >
            <Input v-model:value="form.data.shareConfig.username" placeholder="请输入用户名" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem
            :name="['shareConfig', 'password']"
            label="密码"
            :rules="[
              { required: true, message: '请输入密码' },
              {
                max: 64,
                message: '最多可输入64个字符'
              }
            ]"
          >
            <InputPassword v-model:value="form.data.shareConfig.password" placeholder="请输入密码" />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="24" v-if="form.data.typeId === 'rabbitmq'">
        <Col :span="24">
          <FormItem
            :name="['shareConfig', 'virtualHost']"
            label="虚拟域"
            :rules="[
              { required: true, message: '请输入虚拟域' },
              {
                max: 64,
                message: '最多可输入64个字符'
              }
            ]"
          >
            <Input v-model:value="form.data.shareConfig.virtualHost" placeholder="请输入虚拟域" />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="24" v-if="form.data.typeId === 'rdb'">
        <Col :span="24">
          <FormItem
            :name="['shareConfig', 'schema']"
            label="schema"
            :rules="[
              { required: true, message: '请输入schema' },
              {
                max: 64,
                message: '最多可输入64个字符'
              }
            ]"
          >
            <Input v-model:value="form.data.shareConfig.schema" placeholder="请输入schema" />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="24">
        <Col :span="24">
          <FormItem name="description" label="说明">
            <Textarea v-model:value="form.data.description" placeholder="请输入说明" :rows="3" showCount :maxlength="200" />
          </FormItem>
        </Col>
      </Row>
    </Form>
  </Modal>
</template>

<script setup lang="ts">
  import { ref, computed, reactive, watch } from 'vue';
  import { saveOrUpdate } from '../service';
  import { FormInstance } from 'ant-design-vue';
  import { Rule } from 'ant-design-vue/lib/form';
  import type { optionItemType, sourceItemType } from '../typing';
  import { onlyMessage } from '@jdlinker/utils';
  import { JDictSelectTag } from '@jdlinker/ui';
  // @ts-ignore
  import { Modal, Form, Row, Col, FormItem, Textarea, Input, InputPassword } from 'linker-ui-components';

  const emits = defineEmits(['confirm', 'cancel']);
  const props = defineProps<{
    data: sourceItemType;
  }>();
  // 弹窗相关
  const dialogTitle = computed(() => (props.data.id ? '编辑' : '新增'));
  const loading = ref(false);

  const checkUrl = (_rule: Rule, value: string): Promise<any> => {
    if (!value) return Promise.resolve();
    const arr = value.split(':');
    if (arr?.[0] === 'jdbc' || arr?.[0] === 'r2dbc') {
      return Promise.resolve();
    } else {
      return Promise.reject('请输入正确的URL');
    }
  };

  /**
   * 管理地址校验
   */
  const validateAdminUrl = (_rule: Rule, value: string): Promise<any> => {
    return new Promise((resolve, reject) => {
      if (!value) {
        resolve('');
      } else {
        const arr = value.split('://');
        if (arr[0] === 'http' || arr[0] === 'https') {
          resolve('');
        } else {
          reject('请输入正确的管理地址');
        }
      }
    });
  };
  /**
   * 链接地址校验
   * @param _rule
   * @param value
   */
  const validateAddress = (_rule: Rule, value: string): Promise<any> => {
    return new Promise((resolve, reject) => {
      if (!value) {
        resolve('');
      } else {
        const reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
        if (reg.test(value)) {
          resolve('');
        } else {
          reject('请输入正确的链接地址');
        }
      }
    });
  };

  const formRef = ref<FormInstance>();
  const form = reactive({
    data: {
      ...props.data
    } as sourceItemType,
    typeOptions: [] as optionItemType[]
  });

  watch(
    () => props.data,
    (newValue) => {
      form.data = { ...newValue, shareConfig: { ...newValue?.shareConfig } };
    },
    {
      immediate: true,
      deep: true
    }
  );

  const confirm = () => {
    loading.value = true;
    formRef.value
      ?.validate()
      .then(async (_data: any) => {
        const resp = await saveOrUpdate({ ...props.data, ..._data });
        if (resp) {
          onlyMessage('操作成功');
          emits('confirm');
          formRef.value?.resetFields();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
</script>
