<template>
    <div
        v-if="
            (attachments.length > 0 && readOnlyFlag == true) ||
            readOnlyFlag == false
        "
        class="mt-3 sm:col-span-2"
    >
        <dt class="text-sm font-medium text-gray-500">
            <p v-if="readOnlyFlag" class="font-medium">첨부된 파일</p>
            <a
                v-else
                href="javascript:void(0)"
                class="font-medium text-blue-600 hover:text-blue-500"
                @click="addFiles()"
            >
                파일 첨부
            </a>
        </dt>
        <dd class="mt-1 text-sm text-gray-900">
            <ul
                role="list"
                class="border border-gray-200 rounded-md divide-y divide-gray-200"
            >
                <li
                    v-for="attachment in attachments"
                    :key="attachment.name"
                    class="pl-3 pr-4 py-3 flex items-center justify-between text-sm"
                >
                    <div class="w-0 flex-1 flex items-center">
                        <PaperClipIcon
                            class="flex-shrink-0 h-5 w-5 text-gray-400"
                            aria-hidden="true"
                        />
                        <span class="ml-2 flex-1 w-0 truncate">
                            {{ attachment.name }} {{ ', ' }}
                            {{ _utils.formatBytes(attachment.size, 2) }}
                        </span>
                    </div>

                    <div v-if="readOnlyFlag" class="ml-4 flex-shrink-0">
                        <a
                            :href="
                                _crossCtl.config['API_BASE_URL'].replace(
                                    '/api/',
                                    ''
                                ) + attachment.localUrl
                            "
                            :download="attachment.name"
                            target="_blank"
                            class="font-medium text-blue-600 hover:text-blue-500"
                        >
                            다운로드
                        </a>
                    </div>
                    <div v-else class="ml-4 flex-shrink-0">
                        <a
                            href="javascript:void(0)"
                            class="font-medium text-red-600 hover:text-red-500"
                            @click="rmvFile(attachment)"
                        >
                            삭제
                        </a>
                    </div>
                </li>
            </ul>
        </dd>
    </div>
</template>

<script setup lang="ts">
import { stringLiteral } from '@babel/types';
import { PaperClipIcon } from '@heroicons/vue/24/solid';
const props = defineProps({
    attachments: {
        type: Array<{ name: ''; localUrl: ''; size: 0; type: 'text/html' }>,
        default: [],
    },
    readOnlyFlag: { type: Boolean, required: true },
    updateAttachments: {
        type: Function,
        required: false,
        default: () => {
            void 0;
        },
    },
    boardId: { type: String, required: false, default: null },
    secureEnabled: { type: Boolean, required: false, default: false },
});

// console.log('huk props = ', props);

const currentDomain = ref('');

if (process.client) {
    currentDomain.value = _utils.getDomain(window.location.href);

    console.log('currentDomain.value=', currentDomain.value);
} else {
    console.log('server?');
}

function addFiles() {
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('multiple', 'multiple');

    input.click();

    // Listen upload local image and save to server
    input.onchange = () => {
        if (input.files.length > 0) {
            console.log('we got file(s) : ', input.files);
            uploadFiles(input.files);
        }
    };
}

async function uploadFiles(files) {
    const formData = new FormData();

    for (let i = 0; i < files.length; i++) {
        formData.append('upload-file', files[i], files[i].name);
    }

    formData.append('target', 'just');
    if (props.boardId != null) {
        formData.append('attachedTo', props.boardId);
    }
    formData.append('secureEnabled', props.secureEnabled.toString());

    console.log('formData=', formData);

    const responseJson = await _crossCtl.doUpload('just', formData);

    console.log('responseJson=', responseJson);

    if (responseJson['responseCode'] == 200) {
        props.updateAttachments([
            ...props.attachments,
            ...responseJson['files'],
        ]);
    } else {
        alert('upload error : ' + responseJson['responseMessage']);
    }
}

function rmvFile(target) {
    const tmpAry = [];
    for (let i = 0; i < props.attachments.length; i++) {
        if (props.attachments[i] != target) {
            tmpAry.push(props.attachments[i]);
        }
    }
    props.updateAttachments(tmpAry);
}
</script>
