<!-- 编辑弹窗 -->
<template>
    <ele-modal
        form
        :width="960"
        v-model="visible"
        title="投诉状态及操作"
        @open="handleOpen"
    >
        <div class="flex w-full">
            <div style="flex: 1.5">
                <el-tag size="large">{{ getStatusText(form.status) }}</el-tag>

                <ele-text style="margin-top: 15px"
                    >1.请点击协商（留言）与对方协商。</ele-text
                >
                <ele-text>2.也可点击完结，投诉完结。</ele-text>
                <el-divider />
                <el-button @click="handleNegotiate">协商（留言）</el-button>
                <el-button type="danger" @click="handleComplete"
                    >完结</el-button
                >
                <el-divider />

                <div class="common-title">协商历史</div>
                <complain-item
                    v-for="(item, index) in disposeLogList"
                    :key="index"
                    :item="item"
                />
            </div>
            <div class="flex-1 complain-detail">
                <div class="common-title">投诉详情</div>
                <pro-form :items="formItems" :model="form" class="mt-6" />
            </div>
        </div>

        <template #footer>
            <el-button @click="handleCancel">关闭</el-button>
        </template>
    </ele-modal>

    <!-- 协商弹窗 -->
    <negotiate-dialog
        v-model:visible="negotiateVisible"
        :id="currentId"
        @submit="submitNegotiate"
    />
</template>

<script setup>
    import { ref, reactive, nextTick, getCurrentInstance } from 'vue';
    import ProForm from '@/components/ProForm/index.vue';
    import complainItem from '@/views/optimization/complain/components/complain-item.vue';
    import negotiateDialog from '@/views/optimization/complain/components/negotiate-dialog.vue';
    import { EleMessage } from 'ele-admin-plus/es';
    import { ElMessageBox } from 'element-plus';
    import { useDictData } from '@/utils/use-dict-data';

    const { proxy } = getCurrentInstance();
    const emit = defineEmits(['refresh']);

    // 获取投诉状态字典
    const [statusDicts] = useDictData(['complain_status']);

    // 获取状态文本
    const getStatusText = (status) => {
        return (
            statusDicts.value.find((d) => d.dictValue == status)?.dictLabel ||
            '协商中'
        );
    };

    /** 弹窗是否打开 */
    const visible = defineModel({ type: Boolean });

    /** 关闭弹窗 */
    const handleCancel = () => {
        visible.value = false;
    };

    // 当前投诉ID
    const currentId = ref(null);
    // 处理记录列表
    const disposeLogList = ref([]);

    /** 弹窗打开事件 */
    const handleOpen = (row) => {
        if (row && row.id) {
            currentId.value = row.id;
            visible.value = true;
            getComplaintDetail(row.id);
        } else {
            visible.value = true;
            nextTick(() => console.log('打开'));
        }
    };

    // 获取投诉详情
    const getComplaintDetail = (id) => {
        proxy.$http
            .get(`/order/orderComplaintsLog/getInfo/${id}`)
            .then((res) => {
                if (res.data.code === 200) {
                    const data = res.data.data || {};
                    // 映射API返回的数据到表单
                    form.id = data.id || '';
                    form.userName = data.userName || '-';
                    form.orderId = data.orderId || '';
                    form.reason = data.reason || '';
                    form.description = data.description || '';
                    form.createTime = data.createTime || '';
                    form.status = data.status || '';

                    // 处理协商历史
                    disposeLogList.value = data.disposeLogList || [];
                } else {
                    EleMessage.error(res.data.msg || '获取投诉详情失败');
                }
            })
            .catch((err) => {
                console.error('获取投诉详情失败', err);
                EleMessage.error('获取投诉详情失败');
            });
    };

    // 协商弹窗相关
    const negotiateVisible = ref(false);

    // 处理协商
    const handleNegotiate = () => {
        if (!currentId.value) {
            EleMessage.warning('请先选择投诉记录');
            return;
        }

        // 打开协商弹窗
        negotiateVisible.value = true;
    };

    // 提交协商
    const submitNegotiate = (formData) => {
        // 调用协商API
        proxy.$http
            .post('/order/orderComplaintsLog/dispose', formData)
            .then((res) => {
                if (res.data.code === 200) {
                    EleMessage.success('协商成功');
                    negotiateVisible.value = false;

                    // 刷新详情，更新协商历史
                    getComplaintDetail(currentId.value);
                } else {
                    EleMessage.error(res.data.msg || '协商失败');
                }
            })
            .catch((err) => {
                console.error('协商失败', err);
                EleMessage.error('协商失败');
            });
    };

    // 处理完结
    const handleComplete = () => {
        if (!currentId.value) {
            EleMessage.warning('请先选择投诉记录');
            return;
        }

        ElMessageBox.confirm('确认完结此投诉?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                // 调用完结API
                proxy.$http
                    .post(`/order/orderComplaintsLog/over/${currentId.value}`)
                    .then((res) => {
                        if (res.data.code === 200) {
                            EleMessage.success('投诉已完结');
                            emit('refresh'); // 通知父组件刷新列表
                            handleCancel(); // 关闭弹窗
                        } else {
                            EleMessage.error(res.data.msg || '操作失败');
                        }
                    })
                    .catch((err) => {
                        console.error('完结投诉失败', err);
                        EleMessage.error('完结投诉失败');
                    });
            })
            .catch(() => {
                // 用户取消操作
            });
    };

    const formItems = reactive([
        { type: 'text', label: '投诉编号:', prop: 'id' },
        { type: 'text', label: '投诉人:', prop: 'userName' },
        { type: 'text', label: '订单编号:', prop: 'orderId' },
        { type: 'text', label: '投诉原因:', prop: 'reason' },
        { type: 'text', label: '投诉说明:', prop: 'description' },
        { type: 'text', label: '投诉时间:', prop: 'createTime' }
    ]);

    const form = reactive({
        id: '',
        userName: '',
        orderId: '',
        reason: '',
        description: '',
        createTime: '',
        status: ''
    });

    defineExpose({
        handleOpen
    });
</script>
<style lang="scss">
    .complain-detail {
        border-left: 1px solid #e6e6e6;
        padding-left: 15px;
    }
</style>
