<template>
    <a-modal :width="950" title="设备异常反馈" :maskClosable="false" :closable="false" okText="提交" v-model:visible="visible"
        @ok="handleClickSubmit" @cancel="onClickClose">
        <a-form ref="formRef" :model="formModel" :colon="false" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-form-item label='异常描述' name="logs_info"
                :rules="[{ required: true, message: '异常描述不能为空', whitespace: true }]">
                <a-input style="width: 100%;" v-model:value="formModel.logs_info" placeholder="请输入异常描述" />
            </a-form-item>
            <a-form-item label='发生时间' name="happen_time" :rules="[{ required: true, message: '发生时间不能为空' }]">
                <a-date-picker style="width: 100%;" showTime v-model:value="formModel.happen_time"
                    placeholder="请选择发生时间" />
            </a-form-item>
            <a-form-item label='联系电话' name="contact_number">
                <a-input style="width: 100%;" v-model:value="formModel.contact_number" placeholder="请输入联系电话" />
            </a-form-item>
            <a-form-item label='联系邮箱' name="contact_email">
                <a-input style="width: 100%;" v-model:value="formModel.contact_email" placeholder="请输入联系邮箱" />
            </a-form-item>
            <a-form-item label='附件'>
                <a-upload :action="getUploadPath()" method="POST" :headers="getHeaders()"
                    :file-list="formModel.fileList" @change="handleChangeUpload">
                    <a-button style="position: relative;">
                        <div>
                            上传附件
                        </div>
                        <div style="width: 400px;color:#8a8a8a;font-size: 12px;position: absolute;top: 6px;right: -410px;cursor:auto;"
                            @click.stop>
                            支持上传：图片、文档、视频、RAR 及 ZIP 等文件（至多上传 3 个文件）
                        </div>
                    </a-button>
                </a-upload>
            </a-form-item>
        </a-form>
        <div class="log-list">
            <div class="log-list-item">
                <a-table :columns="airportLogColumns" :scroll="{ x: '100%', y: 300 }"
                    :data-source="state.airportLogList" :loading="state.listLoading" rowKey="boot_index"
                    :row-selection="airportLogState.rowSelection" :pagination="false">
                    <template #log="{ record }">
                        <div style="font-size: 12px;">
                            {{ getDateTime(record.start_time) }}
                            <span style="margin: 0 5px;">
                                -
                            </span>
                            {{ getDateTime(record.end_time) }}
                        </div>
                    </template>
                    <template #size="{ record }">
                        <div>
                            {{ getLogSize(record.size) }} G
                        </div>
                    </template>
                </a-table>
            </div>
            <div class="log-list-item">
                <a-table :columns="droneLogColumns" :scroll="{ x: '100%', y: 300 }" :data-source="state.droneLogList"
                    :loading="state.listLoading" rowKey="boot_index" :row-selection="droneLogState.rowSelection"
                    :pagination="false">
                    <template #log="{ record }">
                        <div style="font-size: 12px;">
                            {{ getDateTime(record.start_time) }}
                            <span style="margin: 0 5px;">
                                -
                            </span>
                            {{ getDateTime(record.end_time) }}
                        </div>
                    </template>
                    <template #size="{ record }">
                        <div>
                            {{ getLogSize(record.size) }} G
                        </div>
                    </template>
                </a-table>
            </div>
        </div>
    </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { getUploadPath, apis, CreateDeviceFeedbackApiParams } from '/@/api/custom';
import { getHeaders } from '/@/api/http/request';
import moment from 'moment';

interface Props {
    sn: string,
    visible: boolean,
    onClickSubmit: (sn: string, data: CreateDeviceFeedbackApiParams) => Promise<any>,
    onClickClose: () => void,
};

const props = withDefaults(defineProps<Props>(), {

});

const formRef = ref();

const formModel = reactive({
    logs_info: undefined,
    happen_time: undefined,
    contact_number: undefined,
    contact_email: undefined,
    fileList: [] as {
        uid: string,
        name: string,
        url: string,
    }[],
})

const labelCol = { span: 4 };

const wrapperCol = { span: 18 };

interface State {
    listLoading: boolean,
    airportLogList: {
        boot_index: number,
        start_time: number,
        end_time: number,
        size: number,
    }[],
    droneLogList: {
        boot_index: number,
        start_time: number,
        end_time: number,
        size: number,
    }[],
};

const state: State = reactive({
    listLoading: false,
    airportLogList: [],
    droneLogList: [],
});

const fetchList = async () => {
    state.listLoading = true;
    try {
        const res = await apis.fetchDeviceLogList(props.sn, { domain_list: '0,3' });
        const files = res.data.files;
        const airportLog = files.find((item: any) => item.module === '3');
        if (airportLog) {
            state.airportLogList = airportLog.list;
        }
        const droneLog = files.find((item: any) => item.module === '0');
        if (droneLog) {
            state.droneLogList = droneLog.list;
        }
    } catch (error) {
        console.error(error);
    } finally {
        state.listLoading = false;
    }
}

const getDateTime = (timestamp: number) => {
    const date = moment.unix(timestamp).format('YYYY-MM-DD HH:mm');
    return date;
}

const getLogSize = (size: number) => {
    // 将字节转换为GB
    const gbSize = size / (1024 * 1024 * 1024);
    // 保留一位小数
    return parseFloat(gbSize.toFixed(1));
};

onMounted(async () => {
    await fetchList();
})

const handleChangeUpload = (info: any) => {
    const list = info.fileList.slice(-3);
    const newFileList = list.map((file: any) => {
        const data = file.response?.data;
        return {
            uid: data?.id || file.uid,
            name: file.name,
            url: data?.url || file.url,
        }
    });
    formModel.fileList = newFileList;
    if (info.file.status === 'done') {// 上传成功
        const data = info.file.response;
        if (data.code === 0) {
            message.success('上传成功');
        } else {
            message.error(data.message);
        }
    }
};

const airportLogColumns = [
    {
        title: '机场日志',
        dataIndex: 'log',
        slots: { customRender: 'log' }
    },
    {
        title: '文件大小',
        dataIndex: 'size',
        width: 100,
        slots: { customRender: 'size' }
    }
]

const droneLogColumns = [
    {
        title: '飞行器日志',
        dataIndex: 'log',
        slots: { customRender: 'log' }
    },
    {
        title: '文件大小',
        dataIndex: 'size',
        width: 100,
        slots: { customRender: 'size' }
    }
]

const airportLogState = reactive({
    selectedRows: [] as any[],
    rowSelection: {
        columnWidth: 40,
        selectedRowKeys: [] as number[],
        onChange: (selectedRowKeys: number[], selectedRows: any[]) => {
            airportLogState.rowSelection.selectedRowKeys = selectedRowKeys;
            airportLogState.selectedRows = selectedRows;
        },
    }
})

const droneLogState = reactive({
    selectedRows: [] as any[],
    rowSelection: {
        columnWidth: 40,
        selectedRowKeys: [] as number[],
        onChange: (selectedRowKeys: number[], selectedRows: any[]) => {
            droneLogState.rowSelection.selectedRowKeys = selectedRowKeys;
            droneLogState.selectedRows = selectedRows;
        },
    }
})

// 点击提交
const handleClickSubmit = () => {
    formRef.value?.validateFields().then(async (values: any) => {
        const list = [];
        const airportLogSelectedList = airportLogState.selectedRows;
        const droneLogSelectedList = droneLogState.selectedRows;
        if (airportLogSelectedList.length) {
            list.push({ list: airportLogSelectedList, module: '3' });
        }
        if (droneLogSelectedList.length) {
            list.push({ list: droneLogSelectedList, module: '0' });
        }
        const data = {
            ...values,
            happen_time: moment(values.happenTime).valueOf(),
            oss_ids: formModel.fileList.length ? formModel.fileList.map(item => item.uid).join(',') : undefined,
            list: list.length ? list : undefined,
        }
        await props.onClickSubmit(props.sn, data);
    }).catch((error: any) => {
        console.error(error);
    });
}
</script>

<style lang="scss" scoped>
.log-list {
    display: flex;
    justify-content: space-between;

    &-item {
        width: 48.5%;
    }
}
</style>