<template>
  <Modal
    :centered="true"

    :title="data.id ? '编辑' : '新增'"
    :open="true"
    width="700px"
    @cancel="handleCancel"
    :confirmLoading="loading"
    @ok="handleOk"
  >
    <div style="margin-top: 20px; padding: 0 20px">
      <Form class="form" layout="vertical" :model="formData" name="basic" autocomplete="off" ref="formRef">
        <FormItem
          label="名称"
          name="name"
          :rules="[
            { required: true, message: '请输入名称', trigger: 'blur' },
            { max: 64, message: '最多可输入64个字符' }
          ]"
        >
          <Input placeholder="请输入名称" v-model:value="formData.name" />
        </FormItem>
        <FormItem label="类型" name="type" :rules="[{ required: true, message: '请选择类型', trigger: 'blur' }]">
          <CardSelect :disabled="!!id" v-model:value="formData.type" :options="options" :column="2" @change="changeType" />
        </FormItem>
        <FormItem
          label="文件地址"
          :name="['configuration', 'location']"
          :rules="[
            {
              required: true,
              message: '请输入文件地址',
              trigger: 'blur'
            }
          ]"
        >
          <Input
            v-if="formData.type === 'local'"
            placeholder="请输入文件地址"
            v-model:value="formData.configuration.location"
          />
          <FileUpload v-else v-model:modelValue="formData.configuration.location" />
        </FormItem>
        <FormItem label="说明" name="description">
          <Textarea placeholder="请输入说明" v-model:value="formData.description" :maxlength="200" :rows="3" showCount />
        </FormItem>
      </Form>
    </div>
  </Modal>
</template>
<script lang="ts" setup>
import { getImage, onlyMessage } from "@jdlinker/utils";
import type { FormInstance, UploadChangeParam } from "ant-design-vue";
import FileUpload from "./FileUpload.vue";
import { save, update } from "../../../../api/link/protocol";
import { FormDataType } from "../type";
import { PermissionButton } from "@jdlinker/ui";
import { ref, watch } from "vue";
// @ts-ignore
import {
  Button as JButton,
  Form,
  FormItem,
  Modal,
  Textarea,
  Input
} from "linker-ui-components";
import CardSelect from '../../../../components/UI/CardSelect/CardSelect.vue';

const loading = ref(false);
  const fileLoading = ref(false);
  const formRef = ref<FormInstance>();
  const props = defineProps({
    data: {
      type: Object,
      default: () => {}
    }
  });

  const emit = defineEmits(['change']);
  // @ts-ignore
  const id = props.data.id;
  const options = [
    {
      label: 'Jar',
      value: 'jar',
      iconUrl: getImage('/jar.png')
    },
    {
      label: 'Local',
      value: 'local',
      iconUrl: getImage('/local.png')
    }
  ];

  const formData = ref<FormDataType>({
    type: 'jar',
    name: '',
    configuration: {
      location: ''
    },
    description: ''
  });
  const changeType = (value: Array<string>) => {
    formData.value.type = value[0];
    formData.value.configuration.location = '';
  };

  const onSubmit = async () => {
    const data: any = await formRef.value?.validate();
    loading.value = true;
    const response: any = !id ? await save(data).catch(() => {}) : await update({ ...props.data, ...data }).catch(() => {});
    if (response?.code === 200) {
      emit('change', response?.code === 200);
      if ((window as any).onTabSaveSuccess) {
        if (response.result?.id) {
          (window as any).onTabSaveSuccess(response);
          setTimeout(() => window.close(), 300);
        }
      }
    }
    loading.value = false;
  };

  const handleChange = (info: UploadChangeParam) => {
    fileLoading.value = true;
    if (info.file.status === 'done') {
      onlyMessage('上传成功！', 'success');
      formData.value.configuration.location = info.file.response?.result;
      fileLoading.value = false;
    }
  };

  const handleOk = () => {
    onSubmit();
  };
  const handleCancel = () => {
    emit('change', false);
  };

  // watch(
  //   () => formData.value.type,
  //   () => {
  //     formData.value.configuration.location = '';
  //   }
  // );
  watch(
    () => props.data,
    (value) => {
      // @ts-ignore
      if (value.id) {
        formData.value = value as FormDataType;
        // @ts-ignore
        if (!!value.type[0]?.value) {
          // @ts-ignore
          formData.value.type = value.type.map((i: any) => i.value);
        }
      }
    },
    { immediate: true, deep: true }
  );
</script>

<style lang="less" scoped>
  .form {
    .form-radio-button {
      width: 148px;
      height: 80px;
      padding: 0;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .form-upload-button {
      margin-top: 10px;
    }
    .form-submit {
      background-color: @primary-color !important;
    }
  }
</style>
