<script lang="ts" setup>
  import { DeviceProfileRecord, OtaRecordDatum } from '/@/api/ota/model';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { Tabs, Space, Button } from 'ant-design-vue';
  import { useForm, BasicForm } from '/@/components/Form';
  import { formSchema } from '../config/packageDrawer.config';
  import { ref, unref } from 'vue';
  import { PackageField } from '../config/packageDetail.config';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    createOtaPackage,
    deleteOtaPackage,
    getDeviceProfileInfoById,
    getOtaPackageInfo,
  } from '/@/api/ota';
  import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  import { useDownload } from '../hook/useDownload';
  import { Authority } from '/@/components/Authority';
  import { OtaPermissionKey } from '../config/config';
  // import DeviceDetailDrawer from '/@/views/device/list/cpns/modal/DeviceDetailDrawer.vue';

  const emit = defineEmits(['register', 'update:list']);

  const loading = ref(false);

  const isUpdate = ref(false);

  const otaRecord = ref<OtaRecordDatum>({} as unknown as OtaRecordDatum);

  const deviceProfileInfo = ref<DeviceProfileRecord>({} as unknown as DeviceProfileRecord);

  const { createConfirm, createMessage } = useMessage();

  const [registerForm, { setFieldsValue, getFieldsValue, updateSchema }] = useForm({
    schemas: formSchema,
    showActionButtonGroup: false,
    disabled: true,
  });

  const [register, { closeDrawer, changeLoading }] = useDrawerInner(
    async (params: { id: string; isUpdate: boolean }) => {
      try {
        const { id, isUpdate: flag } = params;
        isUpdate.value = flag;
        const record = await getOtaPackageInfo(id);
        const deviceInfo = await getDeviceProfileInfoById(record.deviceProfileId.id);
        setFieldsValue({
          ...record,
          [PackageField.DESCRIPTION]: record.additionalInfo.description,
          [PackageField.DEVICE_PROFILE_INFO]: deviceInfo.name,
        });
        deviceProfileInfo.value = deviceInfo;
        otaRecord.value = record;
        if (unref(isUpdate)) {
          updateSchema({ field: PackageField.DESCRIPTION, dynamicDisabled: false });
        }
      } catch (error) {}
    }
  );

  // const [registerTBDrawer, TBDrawerMethod] = useDrawer();

  // const openDetailPage = () => {
  //   TBDrawerMethod.openDrawer({
  //     id: otaRecord.value.id.id,
  //     tbDeviceId: otaRecord.value.deviceProfileId.id,
  //   });
  // };

  const downloadPackage = async () => {
    await useDownload(unref(otaRecord));
  };

  const deletePackage = () => {
    createConfirm({
      iconType: 'warning',
      content: '是否确认删除操作？',
      onOk: async () => {
        try {
          await deleteOtaPackage(otaRecord.value.id.id);
          closeDrawer();
          emit('update:list');
          createMessage.success('删除成功');
        } catch (error) {}
      },
    });
  };

  const { clipboardRef, isSuccessRef } = useCopyToClipboard('');
  const copyPackageId = () => {
    clipboardRef.value = otaRecord.value.id.id;
    if (unref(isSuccessRef)) createMessage.success('复制成功');
  };

  const copyUrl = () => {
    if (!unref(otaRecord).url) {
      createMessage.warning('无直接URL');
      return;
    }
    clipboardRef.value = otaRecord.value.url;
    if (unref(isSuccessRef)) createMessage.success('复制成功');
  };

  const setLoading = (status: boolean) => {
    changeLoading(status);
    loading.value = status;
  };

  const handleSubmit = async () => {
    const value = getFieldsValue();
    try {
      setLoading(true);
      await createOtaPackage({
        ...unref(otaRecord),
        additionalInfo: { description: value[PackageField.DESCRIPTION] },
      } as any);
      createMessage.success('修改成功');
    } catch (error) {
    } finally {
      setLoading(false);
      closeDrawer();
    }
  };
</script>

<template>
  <BasicDrawer
    :title="otaRecord.title"
    width="40%"
    class="relative"
    @register="register"
    @ok="handleSubmit"
  >
    <Tabs>
      <Tabs.TabPane tab="详情" key="detail">
        <Space>
          <!-- <Button type="primary" @click="openDetailPage">打开详情页</Button> -->
          <Button type="primary" @click="downloadPackage" :disabled="!!otaRecord.url">
            下载包
          </Button>
          <Button type="primary" @click="deletePackage" danger>删除包</Button>
        </Space>
        <div class="mt-3">
          <Space>
            <Button type="primary" @click="copyPackageId">复制包ID</Button>
            <Button type="primary" @click="copyUrl">复制直接URL</Button>
          </Space>
        </div>
        <BasicForm @register="registerForm" />
      </Tabs.TabPane>
    </Tabs>
    <template #footer>
      <div
        class="absolute right-0 bottom-0 w-full border-t bg-light-50 border-t-gray-100 py-2 px-4 text-right"
      >
        <Button class="mr-2" @click="closeDrawer">取消</Button>
        <Authority :value="OtaPermissionKey.UPDATE">
          <Button v-if="isUpdate" type="primary" :loading="loading" @click="handleSubmit">
            保存
          </Button>
        </Authority>
      </div>
    </template>
    <!-- <DeviceDetailDrawer @register="registerTBDrawer" /> -->
  </BasicDrawer>
</template>
