<template>
    <div style="display: flex;flex-direction: column;height: 100%;">
        <div style="flex:1">
            <el-timeline v-loading='Loading'>
                <template v-for="(value, key) in followList">
                    <el-timeline-item :timestamp="key" placement="top" color="#1874FF">
                    </el-timeline-item>
                    <el-timeline-item placement="top" v-for="(item,index) in value">
                        <el-card v-if="!onlyShowFollow||(onlyShowFollow&&item.dataType!='log')">
                            <div class="follow_item flex" v-if="item.dataType!='log'">
                                <img :src="item.followUpMemberAvatar">
                                <div class="follow_content">
                                    <div><span class="text_black bold">{{item.createByName}}
                                            {{item.followUpTypeName}}</span><span>{{item.followUpTime}}</span></div>
                                    <div class="follow_desc">{{item.subject}}</div>
                                    <div><span class="text_black">来自{{ item.resourceTypeName
                                            }}：</span><span>{{ item.resourceName }}</span></div>
                                </div>
                                <div class="follow_btn">
                                    <!-- <el-button @click="followDel(item.id, '')" v-if="handleBtnRole('remove')">删除记录</el-button> -->
                                    <el-button @click="followDetail(item.id)" v-if="handleBtnRole('detail')">详情</el-button>
                                    <el-button type="primary"  @click="item.show=!item.show" v-if="handleBtnRole('commit')">评论({{item.comment?item.comment.length:0}})</el-button>
                                </div>
                            </div>
                            <div class="follow_item flex" v-if="item.dataType == 'log'">
                                <img :src="item.createByAvatar">
                                <div class="follow_content">
                                    <div><span class="text_black bold">{{ item.operator }}
                                            {{ item.followUpTypeName }}</span><span>{{ item.operationTime }}</span></div>
                                    <div class="follow_desc" v-if="item.operationType == 1">新增 {{ item.swaggerTitle }}
                                        {{ item.newValue }}</div>
                                    <div class="follow_desc" v-if="item.operationType == 2">{{ item.swaggerTitle }} 由
                                        {{ item.oldValue }} 变更为 {{ item.newValue }}</div>
                                    <div class="follow_desc" v-if="item.operationType == 3">删除 {{ item.swaggerTitle }}
                                        {{ item.newValue }}</div>
                                    <!-- <div><span class="text_black">来自客户：</span><span>{{item.customerName}}</span></div> -->
                                </div>
                            </div>
                            <div class="comment" v-if="item.dataType != 'log'&&item.show">
                                <div class="follow_item flex" v-for="oitem in item.comment" :key="oitem.id">
                                    <img :src="oitem.staffPhoto">
                                    <div class="follow_content">
                                        <div class="flex-center">
                                            <span class="text_black bold">{{ oitem.staffName }}</span>
                                            <span>{{ oitem.createTime }}</span>
                                            <el-icon class="del_icon" @click="delComment(oitem.id)">
                                                <Delete />
                                            </el-icon>
                                        </div>
                                        <div class="follow_desc">{{ oitem.content }}</div>
                                    </div>
                                </div>
                                <div style="margin-top: 18px;">
                                    <el-input v-model="item.commentText" style="width: 100%" placeholder="请输入评论内容"
                                        v-if="handleBtnRole('commit')">
                                        <template #append><el-button type="primary"
                                                @click="comment(item.id, item.commentText, index, key)">评论</el-button></template>
                                    </el-input>
                                </div>
                            </div>
                        </el-card>
                    </el-timeline-item>
                </template>

            </el-timeline>
            <div class="no_data" v-if="Object.keys(followList).length==0"><span>暂无数据</span></div>
        </div>

        <div>
            <pagination v-if="props.showAll" layout="total, sizes, prev, pager, next" v-model:total="total"
                v-model:page="params.pageIndex" v-model:limit="params.pageSize" @pagination="getData" />
        </div>
    </div>

    <!-- 跟进详情 -->
     <FollowDetail ref="detail"></FollowDetail>


</template>


<script setup lang="ts">
import { listFollow, getFollow, delFollow } from '@/api/customer/follow';
import { FollowForm,FollowVO } from '@/api/customer/follow/types';
import FollowDetail from '@/components/Follow/detail.vue'
import { addComment, listComment, deleteComment, listTypes, listOperationLog } from '@/api/public'
import { object } from 'vue-types';

import auth from "@/plugins/auth";
import { noticeEventStore } from '@/store/modules/noticeEvent'
import { set } from 'nprogress';
const userNoticeEventStore = noticeEventStore()
    const props = defineProps({
        // 查询参数，必传
        followParams: {
            type: Object,
            required: true
        },
        // 是否需要展示全部数据（客户详情页只需要展示四条）
        showAll: {
            type: Boolean,
            default: true
        },
        // 只看跟进
        onlyShowFollow: {
            type: Boolean,
            default: false
        },
        // 按钮权限，默认空数组，根据权限可传新增、导入、导出、编辑、删除按钮进来
        btnRole: {
            type: Array as () => { type: string, hasPermi: string }[] || [],
            default: () => { return [] }
        },
    })
    // 按钮权限判断
    const handleBtnRole = (type: string) => {
        let detailRole = props.btnRole.find(a => a.type == type)
        if(detailRole){
            return auth.hasPermi(detailRole.hasPermi)
        }
        return false
    }

    const onlyShowFollow = ref<boolean>(false)
    watch(() => props.onlyShowFollow, (newValue, oldValue) => {
        onlyShowFollow.value = newValue
    });
    watch(() => userNoticeEventStore.noticeFllow, (newValue, oldValue) => {
        getData()
    });

    const commentContent = ref<String>('')
    const detailDialog = ref<Boolean>(false)


    // 获取跟进记录
    const total = ref()
    const followList = ref<any>({})
    const commentIds = ref<string>('') //跟进记录评论id
    const beforeFollow = ref<any>([])
    const params = reactive<PageQuery>({
        pageIndex: 1,
        pageSize: 10
    })
    const Loading = ref(false)
    const getData = ()=>{
        Loading.value= true
        Object.assign(params, props.followParams)
        params.scopeMenuId = props.followParams.menuId
        listFollow(params).then((res) => {
            if(res.success) {
                let followList = res.result.records
                if(!props.showAll&&followList.length>4){
                    followList=followList.slice(0,4)
                }
                followList?followList.forEach(item=>item.comment=[]):followList=[]
                commentIds.value = followList.map(item=>item.id.toString()).join(',')
                beforeFollow.value = followList
                total.value = Number(res.result.total)
                getComment()
            }
        })
    }
    const logData = ref([])
    const getLogData = ()=>{
        let params = {
            pageIndex: 1,
            pageSize: 10,
            resourceTypeId: props.followParams.resourceTypeId,
            resourceType: props.followParams.resourceType,
        }
        listOperationLog(params).then(res => {
            if(res.success) {
                if(!props.showAll){
                    res.result.records=res.result.records.length>4?res.result.records.slice(0,4):res.result.records
                }
                res.result.records.forEach(item=>{item.dataType='log'})
                logData.value = res.result.records
                getData()
                // res.result.records.map((item: { createTime: string }) => {
                //     let time = item.createTime.slice(5, 10)
                //     if(!logData.value[time]) {
                //         logData.value[time] = [item]
                //     }else{
                //         logData.value[time].push(item)
                //     }
                // })
            }
        })
    }

    const followDetailData = ref<FollowVO>()
    const detail = ref()
    const followDetail = (id:any) =>{
        let params = {
            id,
            btnRole:props.btnRole
        }
        detail.value.open(params)
    }

    // 删除跟进记录
    const followDel = (id:any,type:any) =>{
        ElMessageBox.confirm(
            '是否确认删除当前跟进记录？',
            '确认提示',
            { type: 'warning', confirmButtonText: '提交' }
        ).then(() => {
            delFollow(id).then(res => {
                if (res.success) {
                    ElMessage.success('删除成功')
                    if(type=='detail'){
                        detailDialog.value=false
                    }
                    getData()
                }else{
                    ElMessage.error('删除失败')
                }
            })
        }).catch(() => {})

    }

    // 评论
    const comment = (id:any,text:string,index:number, key:number) => {
        if(!text) {
            ElMessage.error(`请填写评论内容`)
            return false
        }
        let params = {
            type: '90',
            content: text,
            recordId: id,
        }
        addComment(params).then(res => {
            if(res.success) {
                ElMessage.success('评论成功')
                followList.value[key][index].commentText = ''
                getComment()
            }
        })
    }

    // 获取评论
    const getComment = ()=>{
        let params = {
            pageIndex: 1,
            pageSize: 999999,
            type: '90',
            recordIds: commentIds.value
        }
        listComment(params).then(res => {
            if(res.success) {
                beforeFollow.value.forEach(ol=>{ol.comment=[]})
                res.result.records.forEach(element => {
                    beforeFollow.value.forEach(ol=>{
                        ol.dataType='follow'
                        ol.show=false
                        if(element.recordId==ol.id){
                            ol.comment.push(element)
                        }
                    })
                });
                getActive()
            }else{
                beforeFollow.value.forEach(ol=>{ol.comment=[]})
                getActive()
            }
        })
    }
    // 结合数据
    const getActive = ()=>{
        followList.value={}
        let concatdata = beforeFollow.value.concat(logData.value)
        concatdata.map((item: { createTime: string }) => {
            let time = item.createTime.slice(0, 10)
            if(!followList.value[time]) {
                followList.value[time] = [item]
            }else{
                followList.value[time].push(item)
            }
        })
        Loading.value= false
    }

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


    onMounted(() => {
        if(!props.showAll){
            getLogData()
        }else{
            getData()
        }

    })
    defineExpose({
        getData,
        followList
    })
</script>
<style lang="scss" scoped>
.comment{
    padding-left: 47px;
    .follow_item{
        margin: 12px 0 0;
    }
    .follow_content{
        .follow_desc{
            margin:8px 0 0;
        }
    }
}
.el-input-group__append button.el-button{
    background-color: #1874FF;
    color: #fff;
}

.del_icon{
    cursor: pointer;
    margin-left: 10px;
}
.no_data{
    color: #909399;
    display: flex;
    height: 100%;
    width: 100%;
    align-items: center;
    text-align: center;
    span{
        display: block;
        width: 100%;
    }
}
</style>

