<script setup>
import UploadButton from "../upload/UploadButton.vue";
import XImage from "../XImage/Index.vue";
import {reactive, useTemplateRef} from "vue";
import Api from "../../api";
import {Message} from "@arco-design/web-vue";
import useTableQuery from "../../hooks/useTableQuery.js";
import dayjs from "dayjs";
import {debounce, throttle} from "lodash";
import {useSystemStore} from "../../pinia/SystemStore/index.js";
import useUploadLength from "../../hooks/useUploadLength.js";
import UploadSlot from "../upload/UploadSlot.vue";

const SystemStore = useSystemStore();
const emits = defineEmits(['success']);
const ChatBoxRef = useTemplateRef('ChatBox');
const {task} = defineProps({
    task: {
        type: Object,
        default: {}
    }
});
let tempPage = 0;
const po = reactive({
    id: task.id,
});
const vo = reactive({
    info: null,
    rows: [],
    total: 0,
});
const form = reactive({
    content: null,
    images: [],
});

useUploadLength({
    array: form.images,
    length: 5,
});

const {loading, pagination, initFetchData, fetchData} = useTableQuery({
    parameter: po,
    api: SystemStore.isRoot ? Api.admin.getExchangeLogIntervention : Api.merchant.getExchangeLog,
    callback: (data) => {
        if (data.rows.length === 0) {
            if (pagination.current > 1) pagination.current--;
        } else {
            tempPage = pagination.current;
            vo.info = data.info;
            vo.total = data.total;
            vo.rows.push(...data.rows);
            vo.rows = Array.from(
                vo.rows.reduce((map, item) => {
                    map.set(item.id, item);
                    return map;
                }, new Map()).values()
            )
        }
    }
});

const send = debounce(async () => {
    const {msg} = await Api.merchant.addExchangeLog({
        id: task.id,
        ...form,
    });
    Message.success(msg);
    form.content = null;
    form.images.length = 0;
    pagination.current = tempPage;
    await fetchData()
}, 1000);

const handleScroll = ({target}) => {
    const {scrollTop, clientHeight, scrollHeight} = target;
    if (scrollTop + clientHeight >= scrollHeight - 10 && !loading.value) {
        throttle(() => {
            pagination.current++;
        }, 500)();
    }
}

const addIntervention = debounce(async (id) => {
    const {msg} = await Api.admin.addInterventionV2({...form, id: id});
    Message.success(msg);
    pagination.current = tempPage;
    await fetchData()
    emits('success')
}, 1000);

const intervention = debounce(async () => {
    const {msg} = await Api.merchant.interventionV2({...form, id: task.id});
    Message.success(msg);
    form.content = null;
    form.images.length = 0;
    pagination.current = tempPage;
    await fetchData();
    emits('success')
}, 1000)
</script>

<template>
    <div
        @scroll="handleScroll"
        :class="['size-full flex flex-col gap-[30px] overflow-auto', !SystemStore.isRoot ? 'max-h-[600px]' : 'max-h-[800px]']">
        <template v-for="v in vo.rows">
            <div v-if="v.pattern !== 2" :class="['flex gap-[18px]', v.right === 0 ? 'chat-right' : 'chat-left']">
                <a-image :src="v.people.avatar" class="rounded-[50%] overflow-hidden" width="64px"
                         height="64px"></a-image>
                <div class="content-box flex flex-col">
                    <div class="text-[#86909C] text-[12px]">{{ dayjs(v.createtime).format('MM月DD日 HH:mm') }}</div>
                    <div class="bg-white p-[16px] max-w-[330px]">
                        <div v-html="v.content"></div>
                        <div class="flex flex-wrap gap-[12px] mt-[12px]" v-if="v.image_arr.length > 0">
                            <x-image
                                class="flex-shrink-0"
                                v-for="(v, index) in v.image_arr"
                                :hide-delete="true"
                                :key="index"
                                width="50px"
                                height="50px"
                                :src="v">
                            </x-image>
                        </div>
                    </div>
                    <div
                        :class="[v.status===0?'text_warn':'',v.status===1?'text_success':'',v.status===-1?'text_error':'', 'text_info']">
                        {{ v.status_text }}
                    </div>
                    <div class="msg-state text-[14px] text-[#1D2129] mt-[4px]">
                        已读
                    </div>
                </div>
            </div>
            <div v-else class="flex justify-center">
                <a-card class="w-[528px]" :title="`${ v.type === 1 ? '达人' : '商家'}发起了平台介入`"
                        :header-style="{textAlign: 'center'}">
                    <div class="font-bold text-[#1D2129] mb-[6px]">{{ v.type === 1 ? '达人' : '商家' }}申诉理由:</div>
                    <div class="px-[16px] py-[12px] bg-[#F7F8FA]">
                        <div>
                            {{ v.content }}
                        </div>
                        <div class="grid grid-cols-5 gap-[12px] mt-[4px]">
                            <x-image hideDelete v-for="v in v.image_arr" :src="v"></x-image>
                        </div>
                    </div>
                    <div
                        v-if="v.is_handle === 1 || SystemStore.isRoot"
                        class="font-bold text-[#1D2129] mt-[20px] mb-[6px]">平台处理结果:
                    </div>
                    <div id="ROOT" class="flex flex-col justify-center items-center"
                         v-if="SystemStore.isRoot && v.is_handle !== 1">
                        <a-textarea v-model:model-value="form.content" class="w-full h-[140px]"
                                    placeholder="输入平台介入结果"></a-textarea>
                        <div class="flex flex-wrap gap-[16px] mt-[10px] mr-auto">
                            <x-image
                                v-for="(v, index) in form.images"
                                @delete="form.images.splice(index,1)"
                                :key="index"
                                width="32px"
                                height="32px"
                                :src="v">
                            </x-image>
                            <upload-slot @success="(e) => form.images.push(e)">
                                <div
                                    class="size-[32px] bg-[#F2F3F5] flex justify-center items-center flex-col rounded-[8px] cursor-pointer">
                                    <icon-plus/>
                                </div>
                            </upload-slot>
                        </div>
                        <a-button type="primary" class="mt-[10px]" @click="addIntervention(v.id)">平台介入</a-button>
                    </div>
                    <div v-else
                         v-show="v.is_handle === 1 || SystemStore.isRoot"
                         class="px-[16px] py-[12px] bg-[#F7F8FA]">
                        <div>
                            {{ v.reply_conyent }}
                        </div>
                        <div class="grid grid-cols-5 gap-[12px] mt-[4px]">
                            <x-image hideDelete v-for="v in v.reply_image_arr" :src="v"></x-image>
                        </div>
                    </div>
                </a-card>
            </div>
        </template>
    </div>

    <div
        v-if="!SystemStore.isRoot"
        class="bg-white rounded-[2px] w-[calc(100%-40px)] h-[144px] absolute left-0 bottom-[20px] mx-[20px] py-[8px]">
        <a-textarea
            v-model:model-value="form.content"
            class="w-full h-full"
            placeholder="提示：商家可主动发起一次自定义私信，若达人没有回复，则不能继续发送。仅当达人回复后，商家可发送3次私信。">
        </a-textarea>
        <a-button type="primary" class="absolute right-[12px] bottom-[12px] z-[2]" @click="send">
            <template #icon>
                <icon-send/>
            </template>
            发送
        </a-button>
        <a-button class="absolute right-[110px] bottom-[12px] z-[2]" @click="intervention">
            <template #icon>
                <icon-robot/>
            </template>
            申请平台介入
        </a-button>

        <div class="flex gap-[12px] absolute bottom-[12px] left-[12px] rounded-[6px] z-[2]">
            <x-image
                class="flex-shrink-0"
                v-for="(v, index) in form.images"
                :key="index"
                width="32px"
                height="32px"
                :src="v">
            </x-image>
            <upload-button :api="Api.system.uploadFile2" @success="e => form.images.push(e)">
                <template v-slot:upload-button>
                    <div
                        class="size-[32px] bg-[#F2F3F5] flex justify-center items-center flex-col rounded-[8px] cursor-pointer">
                        <icon-image/>
                    </div>
                </template>
            </upload-button>
        </div>
    </div>
</template>

<style lang="scss">
#ROOT {
    textarea {
        background-color: #F7F8FA;
    }
}
</style>

<style scoped lang="scss">
.chat-right {
    @apply flex-row-reverse;
    .content-box {
        @apply items-end;
    }
}

.msg-state {
    @apply flex items-center gap-[8px];
    &::before {
        content: '';
        @apply block size-[14px] rounded-[50%];
    }
}

.read {
    &::before {
        @apply bg-[rgb(var(--arcoblue-6))];
    }
}

.unRead {
    &::before {
        @apply bg-[rgb(var(--orange-6))];
    }
}

.chat-left {

}

.text_info {
    font-size: 12px;
    margin-top: 10px;
}

.text_success {
    color: rgba(0, 180, 42, 1);
}

.text_warn {
    color: rgba(255, 125, 0, 1);
}

.text_error {
    color: rgba(245, 63, 63, 1);
}
</style>
