<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="30%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #iconSelect>
        <Upload
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :customRequest="customUpload"
          :before-upload="beforeUpload"
        >
          <img v-if="tenantLogo" :src="tenantLogo" alt="avatar" />
          <div v-else>
            <LoadingOutlined v-if="loading" />
            <plus-outlined v-else />
            <div class="ant-upload-text">上传</div>
          </div>
        </Upload>
      </template>
      <template #videoPlatformIdSlot="{ model, field }">
        <a-select
          placeholder="请选择流媒体配置"
          v-model:value="model[field]"
          :options="streamConfigOptions.map((item) => ({ value: item.value, label: item.label }))"
        >
          <template #dropdownRender="{ menuNode: menu }">
            <v-nodes :vnodes="menu" />
            <a-divider style="margin: 4px 0" />
            <div @click="handleOpenStreamConfig" style="padding: 4px 8px; cursor: pointer">
              <plus-outlined />
              新增流媒体配置
            </div>
          </template>
        </a-select>
      </template>
    </BasicForm>
  </BasicDrawer>
  <SteramingDrawer @register="registerSteramingDrawer" @success="handleSuccess" />
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, nextTick, onMounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from './config.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { createOrEditCameraManage } from '/@/api/camera/cameraManager';
  import { message, Upload } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
  import { upload } from '/@/api/oss/ossFileUploader';
  import { FileItem } from '/@/components/Upload/src/typing';
  import { getStreamingMediaList } from '/@/api/camera/cameraManager';
  import SteramingDrawer from '../streaming/SteramingDrawer.vue';
  import { useDrawer } from '/@/components/Drawer';

  export default defineComponent({
    name: 'ContactDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      Upload,
      PlusOutlined,
      LoadingOutlined,
      SteramingDrawer,
      VNodes: (_, { attrs }) => {
        return attrs.vnodes;
      },
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const loading = ref(false);
      const streamConfigOptions: any = ref([]);
      const isUpdate = ref(true);
      const editId = ref('');
      const [registerForm, { validate, setFieldsValue, resetFields }] = useForm({
        labelWidth: 120,
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      onMounted(async () => {
        const res = await getStreamingMediaList({});
        streamConfigOptions.value = res.map((m) => {
          return {
            label: m.host,
            value: m.id,
          };
        });
      });
      const [registerSteramingDrawer, { openDrawer }] = useDrawer();

      const handleOpenStreamConfig = () => {
        openDrawer(true, {
          createFlag: true,
        });
      };
      async function handleSuccess() {
        const res = await getStreamingMediaList({});
        if (res) {
          streamConfigOptions.value = res.map((m) => {
            return { label: m.host, value: m.id };
          });
        } else {
          streamConfigOptions.value = [];
        }
      }
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        await resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          await nextTick();
          editId.value = data.record.id;
          tenantLogo.value = data.record?.avatar;
          await setFieldsValue(data.record);
        } else {
          tenantLogo.value = '';
          editId.value = '';
        }
      });

      const tenantLogo = ref('');

      async function customUpload({ file }) {
        if (beforeUpload(file)) {
          tenantLogo.value = '';
          loading.value = true;
          const formData = new FormData();
          formData.append('file', file);
          const response = await upload(formData);
          if (response.fileStaticUri) {
            tenantLogo.value = response.fileStaticUri;
            loading.value = false;
          }
        }
      }

      const beforeUpload = (file: FileItem) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          message.error('只能上传图片文件!');
        }
        const isLt2M = (file.size as number) / 1024 / 1024 < 5;
        if (!isLt2M) {
          message.error('图片大小不能超过5MB!');
        }
        return isJpgOrPng && isLt2M;
      };

      const getTitle = computed(() => (!unref(isUpdate) ? '新增视频配置' : '编辑视频配置'));

      async function handleSubmit() {
        setDrawerProps({ confirmLoading: true });
        try {
          const { createMessage } = useMessage();
          const values = await validate();
          if (!values) return;
          if (tenantLogo.value !== '') {
            values.avatar = tenantLogo.value;
          }
          if (editId.value !== '') {
            values.id = editId.value;
          } else {
            delete values.id;
          }
          let saveMessage = '添加成功';
          let updateMessage = '修改成功';
          await createOrEditCameraManage(values);
          closeDrawer();
          emit('success');
          createMessage.success(unref(isUpdate) ? updateMessage : saveMessage);
        } finally {
          setTimeout(() => {
            setDrawerProps({ confirmLoading: false });
          }, 300);
        }
      }

      return {
        getTitle,
        registerDrawer,
        registerForm,
        handleSubmit,
        customUpload,
        beforeUpload,
        tenantLogo,
        loading,
        streamConfigOptions,
        registerSteramingDrawer,
        handleOpenStreamConfig,
        handleSuccess,
      };
    },
  });
</script>
