<template>
    <div class="hc-order-service">
        <div class="order-service-content">
            <el-scrollbar ref="scrollbarRef">
                <div class="content-box" v-loading="dataLoading" element-loading-text="获取数据中...">
                    <div class="comment-card-box" v-for="(item,index) in orderDataList" :key="item.id">
                        <div class="user-avatar-box">
                            <el-avatar :size="50" :src="item.avatar || avatarPng" />
                        </div>
                        <div class="card-content-box">
                            <div class="user-info-box">
                                <div class="text-lg">{{item['createUserName']||'用户名异常'}}</div>
                                <div class="text-gray">{{item['createTime']}}</div>
                            </div>
                            <div class="desc_para" v-html="item['opinionContent']"></div>
                            <div class="image_desc" v-if="item['returnFiles']?.length > 0">
                                <div class="hc-image-box" v-for="(items,indexs) in item['returnFiles']">
                                    <HcImg class="hc-image" :src="items" :srcs="item['returnFiles']" :index="indexs"/>
                                </div>
                            </div>
                            <div class="foot-tools-box">
                                <div class="icon-box" :class="item['commentsNumber'] >= 1 ? 'active' : ''" @click="commentExpanded(item)">
                                    <HcIcon name="question-answer" class="icon" :fill="item['commentsNumber'] >= 1"/>
                                    <span class="badge" v-if="item['commentsNumber'] >= 1">{{item['commentsNumber']}}</span>
                                </div>
                                <div class="icon-box" :class="item['currentUserGood'] ? 'active' : ''" :data-index="item['expandedName']" @click="likeClick(item)">
                                    <i class="hc-icon-i icon" :class="item['currentUserGood'] ? 'hcicon-praise_fill ': 'hcicon-praise'"></i>
                                    <span class="badge" v-if="item['goodNumber'] >= 1">{{item['goodNumber']}}</span>
                                </div>
                            </div>
                            <el-collapse class="hc-collapse-box" v-model="item['expandedName']" accordion>
                                <el-collapse-item title="" :name="`commentList-${item['id']}`">
                                    <div class="collapse-comment-box">
                                        <div class="comment-reply-content-box">
                                            <el-input autosize type="textarea" v-model="item['replyContent']" placeholder="我也说一句"/>
                                            <el-button type="primary" hc-btn @click="saveCommentClick(item)">评论</el-button>
                                        </div>
                                        <div class="user-comment-info-box" v-for="items in item['expandedCommentList']" :key="items.id">
                                            <el-avatar :size="50" :src="items.avatar || avatarPng" />
                                            <div class="user-comment-box">
                                                <div class="user-info-box">
                                                    <span class="user-name">{{items['userName']||'用户名异常'}}</span>
                                                    <span class="create-time">{{items['createTime']}}</span>
                                                </div>
                                                <div class="user-comment-content-box" v-html="items['replyContent']"></div>
                                            </div>
                                        </div>
                                    </div>
                                </el-collapse-item>
                            </el-collapse>
                        </div>
                        <div class="code-status-box" v-if="parseInt(item['isSolve']) === 1">
                            <img :src="Web515Png" class="widget" alt=""/>
                        </div>
                    </div>
                </div>
            </el-scrollbar>
            <div class="page-top-btn" @click="scrollToTop">
                <HcIcon name="arrow-up" class="icon"/>
            </div>
        </div>
        <!--我的工单服务-->
        <div class="order-service-data" :style="'width:' + leftWidth + 'px;'">
            <HcCard :scrollbar="false">
                <template #header>
                    <el-badge :value="2" class="item-badge">
                        <div class="font-bold text-lg">我的工单服务进度</div>
                    </el-badge>
                </template>
                <template #extra>
                    <el-tooltip effect="dark" content="发起新工单服务" placement="top">
                        <el-button type="primary" hc-btn class="hc-add-icon" @click="newOrderServiceClick">
                            <HcIcon name="add" style="margin-right: 0"/>
                        </el-button>
                    </el-tooltip>
                </template>
                <div class="mb-5">
                    <el-select v-model="nameSelectKey" block placeholder="工单名称" size="large" @change="nameSelectUpdate">
                        <el-option v-for="item in nameSelectData" :key="item.id" :label="item?.title" :value="item?.id"/>
                    </el-select>
                </div>
                <div class="time-line-box" :class="isCurrentBol?'time-height':''">
                    <el-scrollbar>
                        <el-timeline class="hc-time-line">
                            <template v-for="(item,index) in orderFlowList" :key="index">
                                <el-timeline-item :class="item['currentBol']?'success':item['current']?'primary':''" size="large">
                                    <div class="timeline-item-icon">
                                        <HcIcon name="check" class="check-icon" v-if="item['currentBol']"/>
                                        <span v-else>{{index + 1}}</span>
                                    </div>
                                    <div class="reply-name">{{item['replyName']}}</div>
                                    <div class="reply-content" v-html="item['replyContent']"></div>
                                </el-timeline-item>
                            </template>
                        </el-timeline>
                    </el-scrollbar>
                </div>
                <div class="evaluation-box" :class="isCurrentBol?'show':''">
                    <div class="text-lg font-bold">评价</div>
                    <div class="tip-box">请对工单处理评价，若是未解决问题，可进行投诉，平台核实情况，将对相关客服人员绩效考核，并且重新为您自动发起工单解决问题</div>
                    <div class="radio-group-box">
                        <el-radio-group class="radio-group" v-model="evaluationKey">
                            <div class="radio-item" v-for="item in evaluationData" :key="item.value">
                                <el-radio :label="item.value" size="large" class="size-xl">{{ item.label }}</el-radio>
                            </div>
                        </el-radio-group>
                    </div>
                    <div class="btn-box">
                        <el-button type="primary" hc-btn @click="disposeUserFeedback">
                            <HcIcon name="check_circle"/>
                            <span>提交</span>
                        </el-button>
                    </div>
                </div>
            </HcCard>
            <!--左右拖动-->
            <div class="horizontal-drag-line" @mousedown="onmousedown"/>
        </div>
        <!--提交工单-->
        <el-dialog v-model="showModal" title="发起新工单服务" width="720px" class="hc-modal-border" :before-close="handleModalClose">
            <div class="title">请选择您需要反馈的问题类型</div>
            <div class="hc-type-tabs my-5">
                <el-radio-group v-model="typeTabKey" size="large" @change="typeTabChange">
                    <el-radio-button v-for="item in typeTab" :label="item?.dictValue">{{item?.dictValue}}</el-radio-button>
                </el-radio-group>
            </div>
            <div class="modal-checkbox-box">
                <el-checkbox-group v-model="typeCheckBox[typeTabIndex]">
                    <div class="checkbox-item" v-for="item in typeTab[typeTabIndex]?.children" :key="item.id">
                        <el-checkbox :label="item['dictValue']">{{item['dictValue']}}</el-checkbox>
                    </div>
                </el-checkbox-group>
            </div>
            <div class="mt-5">
                <el-input v-model="opinionContent" :rows="3" type="textarea" placeholder="请输入你宝贵的建议，我们将会跟踪解决"/>
            </div>
            <div class="mt-3 upload-img" v-loading="spinShow">
                <div class="w-full">
                    <HcUploads :fileList="uploadFileList" :accept="uploadAccept" action="put-file" :limit="3" :size="30" :viewer="false"
                               @change="uploadChange" @progress="uploadsProgress" @del="removeUpload" @preview="handlePreview"/>
                </div>
                <el-image-viewer v-if="showViewer" :initial-index="initialIndex" :url-list="previewFileList" @close="previewModalClose"/>
            </div>
            <div class="mt-3">
                <el-alert title="请上传JPG、PNG格式的图片文件，最多上传 3 张图片，文件大小不超过30M" type="error" :closable="false"/>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="handleModalClose">取消</el-button>
                    <el-button type="primary" hc-btn :disabled="uploadsLoading" @click="saveClick">提交</el-button>
                </div>
            </template>
        </el-dialog>

        <!--提示框-->
        <el-dialog v-model="showTipModal" title="感谢" width="600px" class="hc-modal-border" :before-close="handleTipModalClose">
            <div class="tip-modal-icon-box">
                <HcIcon name="emotion" fill/>
            </div>
            <div class="tip-modal-text-box">感谢您的仗义直言，大恩不言谢，有事联系我们，我们随时都在</div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="tipModalClick">下次不用感谢了</el-button>
                    <el-button type="primary" hc-btn @click="handleTipModalClose">不客气</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {nextTick, onMounted, ref, watch} from "vue";
import {useAppStore} from "~src/store";
import orderServe from '~api/other/orderServe';
import avatarPng from '~src/assets/images/avatar.png';
import Web515Png from '~src/assets/images/Web515.png';
import {userConfigSave} from "~api/other";
import {isType, base64ToFile, getObjNullValue} from "vue-utils-plus"
import ossApi from "~api/oss";

//初始变量
const useAppState = useAppStore()
const { getArrValue, getObjValue } = isType()
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);
const isScreenShort = ref(useAppState.getScreenShort)
//是否弹出工单感谢, 0不弹出，1弹出
const opinionView = ref(useAppState.getOrderServiceTipModal)

//搜索和分页数据
const searchForm = ref({current: 1, size: 20})
const orderDataList = ref([])

// 工单名称
const nameSelectKey = ref(null)
const nameSelectData = ref([])

//监听
watch(() => [
    useAppState.getScreenShort
], ([ScreenShort]) => {
    isScreenShort.value = ScreenShort
    if( ScreenShort ) {
        let base64 = window.sessionStorage.getItem('screenShort-base64') || '';
        if (base64) uploadImgFile(base64)
    }
})

nextTick(() => {
    //截图数据
    if(isScreenShort.value) {
        let base64 = window.sessionStorage.getItem('screenShort-base64') || '';
        if (base64) uploadImgFile(base64)
    }
})

onMounted(() => {
    //获取相关数据
    queryUserOpinionPage()
    queryCurrentUserOpinionList()
})

//获取列表数据
const dataLoading = ref(false)
const queryUserOpinionPage = async () => {
    dataLoading.value = true
    const { error, code, data } = await orderServe.queryUserOpinionPage(searchForm.value)
    dataLoading.value = false
    if (!error && code === 200) {
        orderDataList.value = getArrValue(data['records'])
    } else {
        orderDataList.value = []
    }
}

//获取工单服务下拉列表
const queryCurrentUserOpinionList = async () => {
    const { error, code, data } = await orderServe.queryCurrentUserOpinionList({
        projectId: projectId.value
    })
    if (!error && code === 200) {
        const res = getArrValue(data)
        nameSelectData.value = res
        if (res.length > 0) {
            nameSelectKey.value = res[0].id
            queryUserFlowOpinion()
        } else {
            nameSelectKey.value = null
        }
    } else {
        nameSelectData.value = []
        nameSelectKey.value = null
    }
}

//获取当前工单的最新流程
const isCurrentBol = ref(false)
const orderFlowList = ref([])
const queryUserFlowOpinion = async () => {
    let id = nameSelectKey.value || null;
    const { error, code, data } = await orderServe.queryUserFlowOpinion({userOpinionId: id})
    if (!error && code === 200) {
        const res = getArrValue(data)
        orderFlowList.value = res
        if (res.length > 0) {
            const {currentBol, evaluation} = res[res.length-1];
            isCurrentBol.value = !!(currentBol && parseInt(evaluation) === -1);
        }
    } else {
        orderFlowList.value = []
        isCurrentBol.value = false
    }
}

//我的工单被切换
const nameSelectUpdate = () => {
    //获取当前工单的最新流程
    queryUserFlowOpinion().then()
}

//评论
const expandedName = ref('')
const commentExpanded = (item) => {
    if (item['expandedName']) {
        item['expandedName'] = ''
    } else {
        item['expandedName'] = `commentList-${item.id}`
        queryCommentsList(item)
    }
}

//获取评论列表
const queryCommentsList = async (item) => {
    const { error, code, data } = await orderServe.queryCommentsList({
        userOpinionId: item.id
    })
    if (!error && code === 200) {
        item['expandedCommentList'] = getArrValue(data)
    } else {
        item['expandedCommentList'] = []
    }
}

//提交评论
const saveCommentClick = async (item) => {
    if (!item['replyContent']) {
        window.$message?.warning('请先填写评论内容');
    } else {
        const { error, code } = await orderServe.saveUserComments({
            userOpinionId: item.id,
            replyContent: item['replyContent'],
            projectId: projectId.value,
            contractId: contractId.value,
        })
        if (!error && code === 200) {
            window.$message?.success('评论成功');
            item['replyContent'] = ''
            queryCommentsList(item)
        }
    }
}

//点赞
const likeClick = async (item) => {
    if (item['currentUserGood']) {
        const { error, code } = await orderServe.cancelGood({
            userOpinionId: item.id
        })
        if (!error && code === 200) {
            item['currentUserGood'] = false
            item['goodNumber'] --
        }
    } else {
        const { error, code } = await orderServe.addGoodNumber({
            userOpinionId: item.id,
            good: 1
        })
        if (!error && code === 200) {
            item['currentUserGood'] = true
            item['goodNumber'] ++
        }
    }
}

//弹框
const showModal = ref(false)

//类型tab数据
const typeTabKey = ref(null)
const typeTab = ref([]);

const typeTabIndex = ref(-1);
const typeCheckBox = ref([]);

const typeTabChange = (val) => {
    typeTabKey.value = val;
    typeTabIndex.value = typeTab.value.findIndex(item => item.dictValue === val);
}

//发起新工单服务
const newOrderServiceClick = () => {
    queryDictBizList()
    showModal.value = true
}

//关闭
const handleModalClose = () => {
    showModal.value = false
}

//获取字典信息
const queryDictBizList = async () => {
    const { error, code, data } = await orderServe.queryDictBizList()
    if (!error && code === 200) {
        const res = getArrValue(data)
        typeTab.value = res
        if (res.length > 0) {
            typeTabIndex.value = 0
            typeTabKey.value = res[0]?.dictValue
        }
    } else {
        typeTab.value = []
    }
}

//建议内容
const opinionContent = ref('')

//上传
const uploadAccept = "image/png,image/jpg,image/jpeg"
const uploadFileList = ref([])

//上传的文件结果
const uploadChange = ({ fileList}) => {
    uploadFileList.value = fileList
}

//上传进度
const uploadsLoading = ref(false)
const uploadsProgress = (val) => {
    uploadsLoading.value = val
}

//预览上传的文件
const showViewer = ref(false)
const initialIndex = ref(-1)
const previewFileList = ref([])
const handlePreview = ({ index, fileArr}) => {
    previewFileList.value = fileArr
    initialIndex.value = index
    showViewer.value = true
}

//预览关闭
const previewModalClose = () => {
    initialIndex.value = -1
    showViewer.value = false
}

//删除上传的文件
const removeUpload = async ({link}) => {
    const arrUrl = link.split(".com//");
    if (arrUrl.length > 0) {
        await ossApi.removeFile({fileName: arrUrl[1]},false)
    }
}


//上传截图文件
const spinShow = ref(false)
const uploadImgFile = async (base64) => {
    let fileOfBlob = base64ToFile(base64);
    let formData = new FormData();
    formData.append("file", fileOfBlob);
    //上传文件
    spinShow.value = true
    newOrderServiceClick()
    const { error, code, data } = await ossApi.putFile(formData, false)
    spinShow.value = false
    if (!error && code === 200) {
        let res = getObjValue(data)
        if (res?.link) {
            uploadFileList.value.push({
                url: res?.link,
                name: res?.name,
                response: {data: res}
            })
        }
        window.sessionStorage.removeItem('screenShort-base64');
        window.$message?.success('文件上传成功');
        spinShow.value = false
    } else {
        window.sessionStorage.removeItem('screenShort-base64');
        window.$message?.warning('文件上传失败');
    }
}

//提交工单反馈
const saveClick = async () => {
    //拼接问题类型
    let problemType = typeTabKey.value, index = typeTabIndex.value, problemVal = '';
    const checkBoxVal = typeCheckBox.value[index] || [];
    checkBoxVal.forEach(item => {problemVal += `-${item}`})
    let filesUrl = getUploadFileUrl()
    //判断数据
    if (!problemVal) {
        window.$message?.warning('请先选择问题类型');
    } else {
        //请求接口
        const { error, code } = await orderServe.saveUserOpinion({
            projectId: projectId.value,
            contractId: contractId.value,
            problemType: problemType + problemVal,
            opinionContent: opinionContent.value,
            returnFiles: filesUrl
        })
        if (!error && code === 200) {
            window.$message?.success('提交成功');
            showModal.value = false;
            //重置表单
            typeCheckBox.value[index] = []
            opinionContent.value = ''
            uploadFileList.value = []
            previewFileList.value = []
            //更新数据
            queryUserOpinionPage()
            queryCurrentUserOpinionList()
              window?.location?.reload()  //刷新页面
        }
    }
}

//获取文件URL
const getUploadFileUrl = () => {
    let fileArr = [], fileList = uploadFileList.value ?? [];
    fileList.forEach(item => {
        if (getObjNullValue(item?.response)) {
            fileArr.push(item?.response?.data?.link)
        } else {
            fileArr.push(item?.url)
        }
    })
    return fileArr
}

//评价
const showTipModal = ref(false)
const evaluationKey = ref('1')
const evaluationData = [
    {value: "1", label: "满意"},
    {value: "2", label: "不满意并再次提交解决"},
    {value: "3", label: "不满意且投诉"}
]
const disposeUserFeedback = async () => {
    let oldEndFlow = orderFlowList.value[3]?.id || ''
    const { error, code } = await orderServe.disposeUserFeedback({
        oldEndFlow: oldEndFlow,
        type: evaluationKey.value || '',
        userOpinionId: nameSelectKey.value || ''
    })
    if (!error && code === 200) {
        window.$message?.success('提交成功');
        showTipModal.value = parseInt(opinionView.value) === 1
        queryCurrentUserOpinionList()
    }
}

//提示框
const tipModalClick = async () => {
    await userConfigSave({opinionView: 0})
    showTipModal.value = false
    useAppState.setOrderServiceTipModal(0)
    opinionView.value = 0
}

const handleTipModalClose = () => {
    showTipModal.value = false
}

//滚动到顶部
const scrollbarRef = ref(null)
const scrollToTop = () => {
    scrollbarRef.value?.setScrollTop(0)
}

//左右拖动，改变树形结构宽度
const leftWidth = ref(500);
const onmousedown = () => {
    const clientWidth = document.body.clientWidth
    document.onmousemove = (ve) => {
        let diffVal = clientWidth - (ve.clientX + 24);
        if (diffVal >= 300 && diffVal <= 1000) {
            leftWidth.value = diffVal;
        }
    }
    document.onmouseup = () => {
        document.onmousemove = null;
        document.onmouseup = null;
    }
}
</script>

<style lang="scss" scoped>
@import "../../styles/other/order-service.scss";
</style>

<style lang="scss">
.item-badge .el-badge__content.is-fixed {
    top: 4px;
}
.comment-card-box .card-content-box .hc-collapse-box.el-collapse {
    border: 0;
    .el-collapse-item {
        &:last-child {
            margin-bottom: 0;
        }
        .el-collapse-item__header {
            display: none;
        }
        .el-collapse-item__wrap {
            background-color: initial;
            border-bottom: 0;
        }
    }
}
.comment-reply-content-box {
    .el-textarea {
        min-height: 40px;
        margin-right: 10px;
        .el-textarea__inner {
            min-height: 40px !important;
        }
    }
}
</style>
