<template>
    <div>
        <div class="feedback" @click="openFeedback">
            <el-tooltip ref="tooltipRef" content="遇到问题？提交反馈" placement="left" :visible="errorTooltipVisible" manual>
                <i class="iconfont icon-bangzhufankuiwenhaoyiwen" @mouseenter="errorTooltipVisible = true"
                    @mouseleave="errorTooltipVisible = false"></i>
            </el-tooltip>
        </div>

        <!-- 操作弹窗 -->
        <Layer :layer="layer" @confirm="submit(ruleForm)" @close="layer.show = false">
            <el-form :model="formEdit" :rules="rules" ref="ruleForm" label-width="120px" style="margin-right:30px;">
                <el-form-item label="反馈标题" required prop="title">
                    <el-input v-model="formEdit.title" placeholder="请输入反馈标题" clearable />
                </el-form-item>
                <el-form-item label="反馈内容" required prop="content">
                    <el-input type="textarea" rows="13" v-model="formEdit.content" placeholder="请输入反馈内容" clearable />
                </el-form-item>
                <el-form-item label="反馈截图" prop="image">
                    <el-upload v-model:file-list="formEdit.imageList" action="#" list-type="picture-card"
                        :before-upload="beforeAvatarUpload" :http-request="onImageUpload" multiple
                        accept="image/jpg,image/jpeg,image/png,image/webp" :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
        </Layer>

        <!-- 图片预览弹窗 -->
        <el-dialog v-model="dialogVisible">
            <div class="img_show">
                <div class="icon" @click="prevImg" :class="{ disabled: currentPreviewIndex === 0 }">
                    <el-icon size="24">
                        <ArrowLeftBold />
                    </el-icon>
                </div>
                <el-image class="flex1" :src="dialogImageUrl" :z-index="99999" fit="fill" preview-teleported="true"
                    alt="Preview Image" />

                <div class="icon" @click="nextImg" :class="{ disabled: currentPreviewIndex === 0 }">
                    <el-icon size="24">
                        <ArrowRightBold />
                    </el-icon>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import Layer from "@/components/layer/index.vue";
import { useOssloader } from '@/hooks/useOssloader.js'
import { Plus, ArrowLeftBold, ArrowRightBold } from "@element-plus/icons-vue";
import { errorTooltipVisible, errorTitle, errorContent } from '@/hooks/useErrorTrigger'
import { workorderCreate } from '@/api/common.js'
import { ElMessage } from 'element-plus'

const { beforeAvatarUpload, uploadAllImages } = useOssloader()
const tooltipRef = ref(null)

// 弹窗
const layer = ref({
    show: false,
    title: "意见反馈",
    showButton: true,
    width: '52vw',
});

const ruleForm = ref(null);

const formEdit = ref({
    title: '',//工单标题
    content: '',//工单内容
    imageList: [],
    attachList: undefined,
})

const resetForm = () => {
    // 重置内容
    formEdit.value = {
        title: '',//工单标题
        content: '',//工单内容
        imageList: [],
        attachList: undefined,
    }
}

const openFeedback = () => {
    ruleForm.value?.resetFields()
    layer.value.show = !layer.value.show
}

const rules = reactive({
    title: [
        { required: true, message: "请输入反馈标题", trigger: "blur" },
    ],
    content: [
        { required: true, message: "请输入反馈内容", trigger: "blur" },
    ]
});

const submit = async (formEl) => {
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            // 提交内容
            if (formEdit.value.imageList.length > 0) {
                const attachList = await uploadAllImages(formEdit.value.imageList)
                formEdit.value.attachList = attachList
            }
            delete formEdit.value.imageList

            workorderCreate({ ...formEdit.value }).then(() => {
                ElMessage.success('提交成功')
                layer.value.show = false
            }).catch((err) => {
                ElMessage.error('提交失败，请重试！')
            })
        } else {
            console.log("error submit!", fields);
        }
    });
};

const handleRemove = (uploadFile, uploadFiles) => {
    // console.log(uploadFile, uploadFiles)
}

// 上传二维码图片
const onImageUpload = async (param) => {
    // console.log('param :===>>', param);
}

// 图片预览弹窗
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const currentPreviewIndex = ref(0)

const handlePictureCardPreview = (uploadFile) => {
    const index = formEdit.value.imageList.findIndex(item => item.uid === uploadFile.uid)

    if (index !== -1) {
        currentPreviewIndex.value = index
        dialogImageUrl.value = formEdit.value.imageList[index].url
        dialogVisible.value = true
    }
}

const prevImg = () => {
    if (formEdit.value.imageList.length === 0) return

    currentPreviewIndex.value =
        (currentPreviewIndex.value - 1 + formEdit.value.imageList.length) % formEdit.value.imageList.length

    dialogImageUrl.value = formEdit.value.imageList[currentPreviewIndex.value].url
}

const nextImg = () => {
    if (formEdit.value.imageList.length === 0) return

    currentPreviewIndex.value =
        (currentPreviewIndex.value + 1) % formEdit.value.imageList.length

    dialogImageUrl.value = formEdit.value.imageList[currentPreviewIndex.value].url
}

watch(() => layer.value.show, (newVal) => {
    console.log('newVal :===>>', newVal);
    if (newVal) {
         formEdit.value.title = errorTitle.value
         formEdit.value.content = errorContent.value
    } else {
        resetForm()
    }
}, { deep: true })


</script>

<style lang='scss' scoped>
.feedback {
    cursor: pointer;
    z-index: 9999;
    position: fixed;
    right: 1rem;
    bottom: 10rem;

    display: flex;
    align-items: center;
    justify-content: center;
    width: 42px;
    height: 42px;
    border-radius: 50%;
    background-color: var(--system-primary-color);
    box-shadow: 0 4px 5px rgba(0, 0, 0, 0.1), 0 0 6px rgba(0, 0, 0, 0.4);

    i {
        font-size: 42px;
        color: var(--system-primary-text-color);
    }
}

.img_show {
    display: flex;
    align-items: center;
    // 全局禁止选中
    user-select: none;
    -webkit-user-select: none;

    .icon {
        cursor: pointer;
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background-color: rgba($color: #000000, $alpha: .2);
        color: var(--system-primary-text-color);
    }

    .el-image {
        flex: 1;
        margin: 0 10px;
    }
}
</style>