<template>
    <div class="detail_area">
        <div class="detail_header flex-center">
            <div class="img-div">
                <div class="tooltip">创建</div>
                <img src="http://wework.qpic.cn/wwhead/duc2TvpEgST9hicuyypLEKAibNqE0Wz8cmngyyiaVaf1G7uXrPs1jp5ib8Ja4iaPFELS7OhqmSK1a1No/0" />
                <p class="bold">{{ detailData?.createByName }}</p>
                <p style="color: #666">{{ detailData?.createTime }}</p>
            </div>
            <div class="progress-div">
                <p>{{ (detailData?.orderStatus != 4 ? '已等待' : '') + detailData?.waitTimeStr }}</p>
                <el-progress :percentage="detailData?.orderStatus == 4 ? 100 : 50" :stroke-width="8" />
            </div>
            <div class="img-div">
                <div class="tooltip">完结</div>
                <img src="http://wework.qpic.cn/wwhead/duc2TvpEgST9hicuyypLEKAibNqE0Wz8cmngyyiaVaf1G7uXrPs1jp5ib8Ja4iaPFELS7OhqmSK1a1No/0" />
                <p class="bold">{{ detailData?.ownerByName }}</p>
                <p style="color: #666">{{ detailData?.orderStatusName }}</p>
            </div>
        </div>
        <div class="detail_main">
            <div class="main_nav flex-center">
                <p>{{ detailData?.title }}<span style="margin-left: 10px">{{ detailData?.orderStatusName }}</span></p>
                <div>
                    <template v-for="item in operateBtn" :key="item.value">
                        <el-button v-if="item.show" @click="openDialog(item.value)">{{item.label}}</el-button>
                    </template>
                </div>
            </div>
            <div class="nav_detail">
                <div class="nav_sec">
                    <div class="title flex">
                        <span class="bold">基本信息</span>
                    </div>
                    <div class="form_area flex">
                        <div class="form_item">
                            <div class="flex"><div class="label">工单编号：</div><div class="value">{{ detailData?.id }}</div></div>
                            <div class="flex"><div class="label">关联客户：</div><div class="value">{{ detailData?.customerName }}</div></div>
                            <div class="flex"><div class="label">发起人员：</div><div class="value">{{ detailData?.createByName }}</div></div>
                            <div class="flex"><div class="label">处理人员：</div><div class="value">{{ detailData?.ownerByName }}</div></div>
                            <div class="flex"><div class="label">当前状态：</div><div class="value">{{ detailData?.orderStatusName }}</div></div>
                        </div>
                        <div class="form_item">
                            <div class="flex"><div class="label">紧急程度：</div><div class="value">{{ detailData?.urgentStatusName }}</div></div>
                            <div class="flex"><div class="label">联系人：</div><div class="value">{{ detailData?.liaisonName }}</div></div>
                            <div class="flex"><div class="label">发起部门：</div><div class="value">{{ detailData?.createDepartmentName }}</div></div>
                            <div class="flex"><div class="label">处理部门：</div><div class="value">{{ detailData?.ownerDepartmentName }}</div></div>
                            <div class="flex"><div class="label">提交时间：</div><div class="value">{{ detailData?.createTime }}</div></div>
                        </div>
                    </div>
                </div>
                <div class="nav_sec">
                    <div class="title flex">
                        <span class="bold">工单详情</span>
                    </div>
                    <div class="detail-div flex-center">
                        <p>{{ detailData?.content }}</p>
                    </div>
                </div>
                <div class="nav_sec">
                    <div class="title flex">
                        <span class="bold">相关附件</span>
                    </div>
                    <Table :tableParams="tableParams" :rightBtn="[]" :isPagination="false" :isCheckbox="false">
                    </Table>
                </div>
                <div class="nav_sec">
                    <div class="title flex">
                        <span class="bold">查看记录</span>
                    </div>
                    <div class="check-div flex-center">
                        <div class="flex" style="flex: 1">
                            <div class="img-div" v-for="item in logData">
                                <img src="http://wework.qpic.cn/wwhead/duc2TvpEgST9hicuyypLEKAibNqE0Wz8cmngyyiaVaf1G7uXrPs1jp5ib8Ja4iaPFELS7OhqmSK1a1No/0" />
                                <p class="bold">{{ item.userName }}</p>
                                <p style="color: #666">{{ item.updateTime }}</p>
                            </div>
                        </div>
                        <div class="check-more flex-center" @click="openDialog('checkLog')">
                            <div class="icon">
                                <i-ep-ArrowRight size="10" color="#1874FF" />
                            </div>
                            <p class="text">更多</p>
                        </div>
                    </div>
                </div>
                <div class="nav_sec">
                    <div class="title flex">
                        <span class="bold">评论记录</span>
                    </div>
                    <div class="comment-div">
                        <div class="comment" v-for="item in commentData">
                            <div class="header">
                                <div class="flex-center">
                                    <img :src="item.staffPhoto" />
                                    <span class="bold">{{ item.staffName }}</span>
                                    <span style="color: #666">{{ item.createTime }}</span>
                                </div>
                                <i-ep-close style="cursor: pointer" @click="delComment(item.id)" />
                            </div>
                            <div class="content">
                                {{ item.content }}
                            </div>
                        </div>
                        <div class="comment-input flex">
                            <el-input v-model="commentText" placeholder="请输入评论内容"></el-input>
                            <el-button type="primary" @click="comment()">评论</el-button>
                        </div>
                    </div>
                </div>
                <div class="nav_sec">
                    <div class="title flex">
                        <span class="bold">工单动态</span>
                    </div>
                    <div>
                        <el-timeline>
                            <template v-for="(value, key) in dynamicData">
                                <el-timeline-item :timestamp="key" placement="top" color="#1874FF">
                                </el-timeline-item>
                                <el-timeline-item v-for="item in value">
                                    <el-card>
                                        <div class="follow_item flex">
                                            <img :src="item.avatar">
                                            <div class="follow_content">
                                                <div><span class="text_black bold">{{ item.userName }}</span><span>{{ item.createTime }}</span></div>
                                                <div class="follow_desc">
                                                    <template v-if="item.orderStatus == 2">
                                                        工单被撤销，{{ item.waitTimeStr }}，撤销原因：{{ item.remark }}
                                                    </template>
                                                    <template v-if="item.orderStatus == 3">
                                                        退回工单给发起人 {{ item.ownerByName }}，{{ item.waitTimeStr }}，备注原因：{{ item.remark }}
                                                    </template>
                                                    <template v-if="item.orderStatus == 4">
                                                        完结工单，{{ item.waitTimeStr }}，原因备注：{{ item.remark || '无' }}
                                                    </template>
                                                    <template v-if="item.orderStatus == 1">
                                                        工单转交给 {{ item.newUserName }} 处理
                                                    </template>
                                                </div>
                                                <div><span class="text_black">来自工单：</span><span>{{ item.title }}</span></div>
                                            </div>
                                        </div>
                                    </el-card>
                                </el-timeline-item>
                            </template>
                        </el-timeline>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <el-dialog title="查看记录" v-model="dialog.checkLog" width="850px">
        <Table :tableParams="logTableParams" :btnRole="[]" :rightBtn="[]" :isCheckbox="false">
        </Table>
    </el-dialog>

    <!-- 编辑工单 -->
    <AddOrder ref="editRef" @refresh="getDetailData" />

    <!-- 撤销工单 -->
    <el-dialog title="撤销工单" v-model="dialog.revoke" width="600px">
        <p style="margin-bottom: 10px">撤销工单，需要填写撤销原因</p>
        <el-input
            v-model="remark"
            type="textarea"
            :rows="4"
            placeholder="请填写撤销工单原因"
            :maxlength="300"
            resize="none"
            show-word-limit
        />
        <template #footer>
			<div class="dialog-footer">
				<el-button :loading="buttonLoading" type="primary" @click="submitForm('revoke', '撤销')">提交</el-button>
				<el-button @click="dialog.revoke = false">取 消</el-button>
			</div>
		</template>
    </el-dialog>

    <!-- 完结工单 -->
    <el-dialog title="完结工单" v-model="dialog.completion" width="600px">
        <el-form ref="completionRef" label-width="100px">
            <el-form-item label="备注信息：">
                <el-input
                    v-model="remark"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入备注信息"
                    :maxlength="300"
                    resize="none"
                    show-word-limit
                />
            </el-form-item>
            <el-form-item label="上传图片：">
                <el-upload action="#" list-type="picture-card" :auto-upload="false">
                    <el-icon><Plus /></el-icon>
                </el-upload>
                <p>支持格式：.jpg .png .gif，最多可上传9张图片</p>
            </el-form-item>
        </el-form>
        <template #footer>
			<div class="dialog-footer">
				<el-button :loading="buttonLoading" type="primary" @click="submitForm('completion', '完结')">提交</el-button>
				<el-button @click="dialog.completion = false">取 消</el-button>
			</div>
		</template>
    </el-dialog>

    <!-- 退回工单 -->
    <el-dialog title="退回工单" v-model="dialog.returnOrder" width="600px">
        <el-form ref="returnOrderRef" label-width="100px">
            <el-form-item label="退回到人员：">
                <el-input disabled :value="detailData?.createByName"></el-input>
            </el-form-item>
            <el-form-item label="退回原因：">
                <el-input
                    v-model="remark"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入退回原因"
                    :maxlength="300"
                    resize="none"
                    show-word-limit
                />
            </el-form-item>
        </el-form>
        <template #footer>
			<div class="dialog-footer">
				<el-button :loading="buttonLoading" type="primary" @click="submitForm('returnOrder', '退回')">提交</el-button>
				<el-button @click="dialog.returnOrder = false">取 消</el-button>
			</div>
		</template>
    </el-dialog>

    <!-- 转他人处理 -->
    <el-dialog title="转他人处理" v-model="dialog.transfer" width="600px">
        <el-form ref="transferRef" label-width="100px">
            <el-form-item label="选择人员：" class="select-item">
                <SelectUser v-model="transferOwnerBy"></SelectUser>
            </el-form-item>
            <el-form-item label="转交原因：">
                <el-input
                    v-model="remark"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入转交原因"
                    :maxlength="300"
                    resize="none"
                    show-word-limit
                />
            </el-form-item>
        </el-form>
        <template #footer>
			<div class="dialog-footer">
				<el-button :loading="buttonLoading" type="primary" @click="transferForm()">提交</el-button>
				<el-button @click="dialog.transfer = false">取 消</el-button>
			</div>
		</template>
    </el-dialog>
</template>

<script setup lang="ts">
    import Table from '@/components/Table/index.vue'
    import { tableTypes } from '@/components/Table/types'
    import { getOrder, orderViewLog, orderAddLog, updateOrderStatus, distributionOrder } from '@/api/order';
    import { OrderVO } from '@/api/order/types';
    import AddOrder from '@/components/common/addOrder.vue';
    import { addComment, listComment, deleteComment, listTypes, listDynamic, listResource, delResource, resourceQuery, resourceVO } from '@/api/public'
    import auth from '@/plugins/auth'
    import useAppStore from '@/store/modules/app';
    const appStore = useAppStore();
    const toggleSideBar = () => {
        appStore.closeSideBar(false);
    }
    toggleSideBar()
    const router = useRouter();
    let queryData: { id?: string } = router.currentRoute.value.query

    // 获取工单详情数据
    const detailData = ref<OrderVO>()
    const getDetailData = () => {
        getOrder(queryData.id).then(res => {
            if(res.success) {
                detailData.value = res.result
            }
        })
    }

    // 获取评论数据
    const commentData = ref<listTypes[]>([])
    const getCommentData = () => {
        let params = {
            pageIndex: 1,
            pageSize: 999999,
            type: '100',
            recordId: queryData.id
        }
        listComment(params).then(res => {
            if(res.success) {
                commentData.value = res.result.records
            }
        })
    }

    // 获取工单动态数据
    const dynamicData = ref<any>({})
    const getDynamicData = () => {
        let params = {
            pageIndex: 1,
            pageSize: 999999,
            recordId: queryData.id,
            type: 100
        }
        listDynamic(params).then(res => {
            if(res.success) {
                res.result.records.map((item: { createTime: string }) => {
                    let time = item.createTime.slice(5, 10)
                    if(!dynamicData.value[time]) {
                        dynamicData.value[time] = [item]
                    }else{
                        dynamicData.value[time].push(item)
                    }
                })
            }
        })
    }

    const logData = ref<{ userName?: string; updateTime?: string }[]>([])
    if(queryData.id) {
        getDetailData()
        orderAddLog(queryData.id)
        orderViewLog({ pageIndex: 1, pageSize: 10, workOrderId: queryData.id }).then(res => {
            if(res.success) {
                logData.value = res.result.records
            }
        })
        getCommentData()
        getDynamicData()
    }

    const buttonLoading = ref(false)
    const remark = ref('')

     // 操作按钮弹窗
    let operateBtn = [
        { label: '撤销工单', value: 'revoke', show: auth.hasPermi('order:detail:cxgd') },
        { label: '完结工单', value: 'completion', show: auth.hasPermi('order:detail:wjgd') },
        { label: '退回工单', value: 'returnOrder', show: auth.hasPermi('order:detail:thgd') },
        { label: '转他人处理', value: 'transfer', show: auth.hasPermi('order:detail:ztrcl') },
        { label: '编辑工单', value: 'editClue', show: auth.hasPermi('order:detail:bjgd') }
    ]
    const dialog = reactive<any>({
        checkLog: false,
        revoke: false,
        completion: false,
        returnOrder: false,
        transfer: false,
        editClue: false
    })

    const editRef = ref()
    const transferOwnerBy = ref('')
    const openDialog = (val: string) => {
        remark.value = ''
        transferOwnerBy.value = ''
        switch(val) {
            case 'editClue': // 编辑工单
                editRef.value.open({ type: 'edit', id: queryData.id })
                break;
            default:
                dialog[val] = true
                break;
        }
    }

    // 相关附件
    const tableParams = reactive<tableTypes<resourceQuery, resourceVO>>({
        tableColumn: [
            { show: true, label: '上传时间', prop: 'createTime' },
            { show: true, label: '附件名称', prop: 'resourceName' },
            { show: true, label: '附件格式', prop: 'resourceFormat', render: ({ column }: { column: resourceVO }) => {
                return column.resourceName?.split(".")[1]
            } },
            { show: true, label: '文件大小', prop: 'resourceSize' },
            { show: true, label: '上传人员', prop: 'createByName' },
            { show: true, label: '备注信息', prop: 'resourceExt' },
            {
                show: true, label: '操作', width: 150, prop: 'operation', render: ({ column }: { column: resourceVO }) => {
                    return [
                        // h(ElButton, { link: true, type: 'primary', onClick: () => { } }, '预览'),
                        h('a', {
                            href: column.resourceUrl + '?response-content-type=application%2Fpdf',
                            download: column.resourceName,
                            target: "_blank",
                            style: { color: '#1874FF', 'vertical-align': 'middle', 'margin-right': '12px' }
                        }, '下载')
                    ]
                }
            },
        ],
        queryParams: {
            resourceType: '100',
            resourceTypeId: queryData.id
        },
        listFn: listResource,
        delFn: delResource,
        keyId: 'id',
    })

    // 更多查看记录
    const logTableParams = reactive<any>({
        tableColumn: [
            { show: true, label: '查看人员', prop: 'userName' },
            { show: true, label: '查看时间', prop: 'updateTime' },
            { show: true, label: '查看次数', prop: 'viewCount' },
            { show: true, label: '所属部门', prop: '' },
        ],
        queryParams: {
            workOrderId: queryData.id
        },
        listFn: orderViewLog,
    })

    // 变更状态
    const submitForm = (type: string, msg: string) => {
        if((type == 'revoke' || type == 'returnOrder') && !remark.value) {
            ElMessage.error(`请填写${ msg }工单原因`)
            return false
        }
        let params = {
            id: queryData.id,
            remark: remark.value,
            orderType: type == 'revoke' ? 1 : type == 'completion' ? 3 : 2
        }
        updateOrderStatus(params).then(res => {
            if(res.success) {
                ElMessage.success(msg + '成功')
                dialog[type] = false
                getDetailData()
            }
        })
    }

    //转他人处理
    const transferForm = () => {
        if(!remark.value) {
            ElMessage.error(`请填写转交原因`)
            return false
        }
        let params = {
            workOrderIds: queryData.id,
            remark: remark.value,
            ownerBy: transferOwnerBy.value
        }
        distributionOrder(params).then(res => {
            if(res.success) {
                ElMessage.success('转交成功')
                dialog.transfer = false
                getDetailData()
            }
        })
    }

    // 评论
    const commentText = ref('')
    const comment = () => {
        if(!commentText.value) {
            ElMessage.error(`请填写评论内容`)
            return false
        }
        let params = {
            type: '100',
            content: commentText.value,
            recordId: queryData.id
        }
        addComment(params).then(res => {
            if(res.success) {
                ElMessage.success('评论成功')
                commentText.value = ''
                getCommentData()
            }
        })
    }

    const delComment = (id: string) => {
        ElMessageBox.confirm(
            '是否确认删除当前评论？',
            '确认提示',
            { type: 'warning', confirmButtonText: '提交' }
        ).then(() => {
            deleteComment(id).then(res => {
                if(res.success) {
                    ElMessage.success('删除成功')
                    getCommentData()
                }else{
                    ElMessage.error('删除失败')
                }
            })
        }).catch(() => {})
    }
</script>

<style lang="scss" scoped>
    .detail-div{
        min-height: 48px;
        border: 1px solid #DCDEE2;
        padding-left: 20px;
    }
    .check-div{
        column-gap: 24px;
        border: 1px solid #DCDEE2;
        padding: 16px 20px;
        .check-more{
            flex-direction: column;
            cursor: pointer;
            .icon{
                border: 1px solid #1874FF;
                border-radius: 50%;
                width: 18px;
                height: 18px;
            }
            .text{
                color: #1874FF;
                margin-top: 5px;
            }
        }
    }
    .nav_sec{
        :deep(.el-table){
            margin: 0;
        }
    }
    .img-div{
        display: flex;
        flex-direction: column;
        align-items: center;
        min-width: 130px;
        img{
            width: 68px;
            height: 68px;
            border-radius: 50%;
        }
        .bold{
            margin: 5px 0;
        }
        .tooltip{
            width: 50px;
            background: #1874FF;
            text-align: center;
            color: #FFF;
            border-radius: 2px;
            font-size: 12px;
            position: relative;
            margin-bottom: 10px;
            &::after{
                content: '';
                position: absolute;
                border-top: 5px solid #1874FF;
                border-bottom: 5px solid transparent;
                border-left: 5px solid transparent;
                border-right: 5px solid transparent;
                bottom: -10px;
                left: 20px;
            }
        }
    }
    .progress-div{
        flex: 1;
        text-align: center;
        .el-progress{
            margin: 10px 0 45px;
            :deep(.el-progress__text){
                display: none;
            }
        }
    }
    .comment-div{
        .comment{
            box-shadow: 0px 0px 6px 0px rgba(0,0,0,0.1);
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 16px;
            .header{
                display: flex;
                justify-content: space-between;
                img{
                    width: 36px;
                    height: 36px;
                    border-radius: 50%;
                }
                .bold{
                    margin: 0 10px;
                }
            }
            .content{
                padding-left: 45px;
                color: #666;
            }
        }
    }
    .select-item{
        :deep(.el-row){
            width: 100%;
        }
    }
</style>
