<template>
    <a-drawer width="70%" title="设备异常反馈记录" :visible="visible" @close="onClose">
        <div class="top">
            <a-button type="primary" @click="() => state.createModalVisible = true">
                新建异常反馈
            </a-button>
            <div>
                <a-form ref="formRef" layout="inline" :model="formModel" :colon="false">
                    <a-form-item name="rangeDate">
                        <a-range-picker style="width: 250px;" valueFormat="YYYY-MM-DD"
                            v-model:value="formModel.rangeDate" />
                    </a-form-item>
                    <a-form-item name="username">
                        <a-input style="width: 200px;" placeholder="反馈人" v-model:value="formModel.username" />
                    </a-form-item>
                    <a-form-item name="search_info">
                        <a-input style="width: 200px;" placeholder="设备SN、设备异常描述"
                            v-model:value="formModel.search_info" />
                    </a-form-item>
                    <a-form-item>
                        <a-button style="margin-right: 10px;" @click="handleClickSearch">
                            <template #icon>
                                <SearchOutlined />
                            </template>
                        </a-button>
                        <a-button @click="handleClickReset">
                            <template #icon>
                                <ReloadOutlined />
                            </template>
                        </a-button>
                    </a-form-item>
                </a-form>
            </div>
        </div>
        <div>
            <a-table :scroll="{ x: '100%', y: 500 }" rowKey="logs_id" :loading="state.listLoading" :columns="columns"
                :dataSource="state.list" :pagination="paginationConfig">
                <!-- 上传状态 -->
                <template #status="{ record }">
                    <div v-if="record.status === 1">
                        上传中
                    </div>
                    <div v-else-if="record.status === 2">
                        成功
                    </div>
                    <div v-else-if="record.status === 3">
                        取消
                    </div>
                    <div v-else-if="record.status === 4">
                        失败
                    </div>
                </template>
                <!-- 操作 -->
                <template #operation="{ record }">
                    <a-tooltip title="详情">
                        <FileSearchOutlined style="color: #2d8cf0" @click="handleClickDetail(record.logs_id)" />
                    </a-tooltip>
                </template>
            </a-table>
        </div>
    </a-drawer>
    <!-- 异常反馈-信息弹出层 -->
    <FeedbackCreateModal :sn="device.device_sn" :visible="state.createModalVisible"
        :onClickSubmit="createModalOnClickSubmit" :onClickClose="() => state.createModalVisible = false"
        v-if="state.createModalVisible" />
    <!-- 异常反馈-详情弹出层 -->
    <FeedbackDetailModal :currentId="state.currentId" :visible="state.detailModalVisible"
        :onClickClose="() => state.detailModalVisible = false" v-if="state.detailModalVisible" />
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { SearchOutlined, ReloadOutlined, FileSearchOutlined } from '@ant-design/icons-vue';
import FeedbackCreateModal from '../components/FeedbackCreateModal.vue';
import FeedbackDetailModal from '../components/FeedbackDetailModal.vue';
import { apis, CreateDeviceFeedbackApiParams } from '/@/api/custom';
import { Device } from '/@/types/device';
import moment from 'moment';

interface Props {
    visible: boolean,
    device: Device,
    onClose: () => void,
};

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

});

const formRef = ref();

const formModel = reactive({
    rangeDate: undefined,
    username: undefined,
    search_info: undefined,
})

type Query = Partial<{
    begin_time: number,
    end_time: number,
    username: number,
    search_info: string,
}>;

interface State {
    query?: Query,
    listLoading: boolean,
    list: any[],
    currentId: string,
    createModalVisible: boolean,
    detailModalVisible: boolean,
};

const state: State = reactive({
    query: undefined,
    listLoading: false,
    list: [],
    currentId: '',
    createModalVisible: false,
    detailModalVisible: false,
});

const paginationConfig = reactive({
    pageSizeOptions: ['20', '50', '100'],
    showQuickJumper: true,
    showSizeChanger: true,
    pageSize: 20,
    current: 1,
    total: 0,
    onChange: async (current: number) => {
        paginationConfig.current = current;
        await fetchList();
    },
    onShowSizeChange: async (current: number, pageSize: number) => {
        paginationConfig.pageSize = pageSize;
        await fetchList();
    }
})

const fetchList = async () => {
    state.listLoading = true;
    try {
        const res = await apis.fetchDeviceFeedbackRecordList(
            props.device.device_sn,
            {
                ...state.query,
                page: paginationConfig.current,
                page_size: paginationConfig.pageSize
            }
        );
        if (res.code === 0) {
            paginationConfig.total = res.data.pagination.total
            paginationConfig.current = res.data.pagination.page
            paginationConfig.pageSize = res.data.pagination.page_size
        }
        state.list = res.data.list;
    } catch (e) {
        console.error(e);
    } finally {
        state.listLoading = false;
    }
}

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

const columns = [
    {
        title: '反馈时间',
        dataIndex: 'create_time',
        width: 200,
        sorter: (a: any, b: any) => a.create_time.localeCompare(b.create_time),
    },
    {
        title: '反馈人',
        dataIndex: 'username',
        width: 150,
    },
    {
        title: '设备型号',
        dataIndex: 'device_name',
        width: 150,
    },
    {
        title: '设备SN',
        dataIndex: 'device_sn',
        width: 250,
        slots: { customRender: 'device_sn' }
    },
    {
        title: '设备名称',
        dataIndex: 'nick_name',
        width: 150,
        slots: { customRender: 'nick_name' },
    },
    {
        title: '设备异常描述',
        dataIndex: 'log_info',
        width: 150,
        ellipsis: true,
    },
    {
        title: '上传状态',
        dataIndex: 'status',
        slots: { customRender: 'status' },
        sorter: (a: any, b: any) => a.status.localeCompare(b.status),
        width: 150,
    },
    {
        title: '操作',
        dataIndex: 'operation',
        fixed: 'right',
        width: 80,
        slots: { customRender: 'operation' }
    },
]

// 点击查询
const handleClickSearch = async () => {
    const values = formRef.value?.getFieldsValue();
    const data = { ...values };
    delete data.rangeDate;
    if (values.rangeDate?.length === 2) {
        data.begin_time = moment(values.rangeDate[0]).valueOf();
        data.end_time = moment(values.rangeDate[1]).valueOf();
    }
    state.query = data;
    await fetchList();
}

// 点击重置
const handleClickReset = async () => {
    formRef.value?.resetFields();
    const values = formRef.value?.getFieldsValue();
    const data = { ...values };
    delete data.rangeDate;
    state.query = data;
    await fetchList();
}

const createModalOnClickSubmit = async (sn: string, data: CreateDeviceFeedbackApiParams) => {
    state.createModalVisible = false;
    try {
        const res = await apis.createDeviceFeedback(sn, data);
        if (res.code === 0) {
            await fetchList();
            message.success('提交成功');
        }
    } catch (error) {
        console.error(error);
    }
}

// 点击详情
const handleClickDetail = (id: string) => {
    state.currentId = id;
    state.detailModalVisible = true;
}
</script>

<style lang="scss" scoped>
.top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}
</style>