<template>
    <div class="main commentmain" style="background:transparent">
        <img src="../assets/bg.png" alt="" class="bg" >
        <div class="content">
            <div class="title">{{ !isResult?'互动讨论区':'留言' }}<img src="../assets/cai.png" alt="" srcset="" class="cai"></div>
            <div class="tips" v-if="!isResult">感谢您的参与，请在文中点击“完成”提交</div>
            <div class="bottom" v-if="!isResult">
                <div class="textbox">
                    <van-field :autosize="{ minHeight: 150 }" v-model="message" rows="2" autosize type="textarea"
                        maxlength="200" :placeholder="placeholder" show-word-limit />
                </div>
                <button class="button"  @click="handleSubmit">完成</button>
            </div>
            <div class="add" v-if="isResult" @click="showLiuyan=true">添加留言</div> 
            <div class="bottom" v-if="showLiuyan">
                <div class="textbox">
                    <van-field :autosize="{ minHeight: 150 }" v-model="message" rows="2" autosize type="textarea"
                        maxlength="200" placeholder="病例有疑问？方案有争议？欢迎在此留言、提问、探讨~ " show-word-limit />
                </div>
                <button class="button" :disabled="isLock" @click="handleAdd">完成</button>
            </div>
            <div class="conmmentbox">
                <div class="commentwrapercell">
                     <comment-list :childList="list" @freshLike="freshLike" :case_id="case_id" :project_id="project_id"  @freshSecComment="freshSecComment" @handleFreshList="handleFreshList"></comment-list>
                </div>

            </div>
             <div class="loadmore" v-if="list.length<total" @click="loadMore">——加载更多留言（{{total-list.length}}条）—— </div>
            


            

        </div>
        <c-dialog :message="dialog_message" ref="cdialog" @handledConfirm="handledConfirm" @handledCancel="handledCancel"></c-dialog>
    </div>
</template>

<script setup>
import { showToast } from "vant";
import { ref,getCurrentInstance } from "vue";
import dayjs from 'dayjs'
import api from '../api/user.js';
import { useRouter, useRoute } from 'vue-router';
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
let share_user_iden_temp=route.query.share_user_iden?route.query.share_user_iden:'';
const share_user_iden=ref(share_user_iden_temp);

const showLiuyan=ref(false);
const isResult=ref(route.path.includes('result')?true:false);
const  read_duration=ref(0);
const case_id = ref(route.query.case_id)
const isLock=ref(false);
const project_id=ref(null);
const message = ref("");
const cdialog=ref(null);
const list=ref([]);
const page=ref(1);
const total=ref(0);
const dialogType=ref(0); //1 未留言，不满3min 2未留言，已满3min 3已留言不满3min
const dialog_message=ref('');
const placeholder=ref('欢迎就本病例提出您的讨论话题、思考与诊疗分享，如病例疑难点、诊疗经验、用药心得等。');
const complete_read=ref(0);//完成阅读积分
const complete_read_time=ref(0);//完成阅读时间积分
const first_high_quality=ref(0);//首次高质量留言积分
const is_white_user=ref(0);
let origin=route.query.source?route.query.source:''
const source = ref(origin);
//const is_welfare=ref(0);
let answer=ref([])
const props=defineProps({
      countTime:{
        type:String,
        default:'0'
    },
    allAnswer:{
        type:Object,
        default:{}
    },
    is_welfare:{
        type:Number,
        default:0
    },
    start_time:{
        type:String,
        default:''
    }
});

const formatAnswer=(data)=>{
  
    answer.value=[];
    for(let i in data){
        data[i].forEach(item => {
            answer.value.push(item)
        })
    }
    console.log(answer.value)

}
const emit=defineEmits(['initPage']);
// watch(()=>props.allAnswer,(newVal)=>{
//     answer.value=[];
//     console.log(1111111)
//     console.log(props.allAnswer)
//     for(let i in newVal){
//         console.log(333)
//         console.log(newVal[i])

//         // newVal[i].forEach(item => {
//         //     answer.value.push(item)
//         // })
//     }
//     console.log(answer.value)

// },{
//     immediate:true,
//     deep:true

// })
const handleFreshList=(data)=>{
      list.value=[];
      getList();
}
const getList = async (root_id='') => {
    const { code, data } = await api.getCommentList({
        case_id:case_id.value,
        project_id:project_id.value,
        page:page.value,
        page_size:10,
        root_id:root_id
    })
    if (code == 200) {
        list.value = list.value.concat(data.data);
        total.value=data.total;
    }

}

const handledConfirm=()=>{
    if(dialogType.value==1){
       emit('initPage');
    }else if(dialogType.value==2){
        
    }else if(dialogType.value==3){
        emit('initPage');
    }
}

const behaviorRecord=(step='',start_time='',end_time='')=>{
    api.behaviorRecord({
        case_id:case_id.value,
        step:step,
        start_time:start_time,
        end_time:end_time
    }).then(res=>{

    })
}
const changeDialog=(type)=>{
    let unit='积分';
    if(source.value){
        unit='e豆'
    };
   if(type==1){
       dialogType.value=1;
       dialog_message.value='阅读时长满足'+read_duration.value/60+'分钟可获得'+complete_read_time.value+unit+'、留言入选优质点评有机会获得'+first_high_quality.value+unit+'，是否继续学习？';
      cdialog.value.openDialog();
   }else if(type==2){
        dialogType.value=2;
       dialog_message.value='留言入选优质点评，有机会获得'+first_high_quality.value+unit+'，是否留言？'
       cdialog.value.openDialog();
   }else if(type==3){
      dialogType.value=3;
     dialog_message.value='阅读时长满足'+read_duration.value/60+'分钟可获得'+complete_read_time.value+unit+'，是否继续学习？'
     cdialog.value.openDialog();
   }else{
    dialogType.value=4;
   }
}

const loadMore=()=>{
    page.value++;
    getList();
}
const init= async(caseId,projectId)=>{
    list.value=[];
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
    case_id.value=caseId;
    project_id.value=projectId;
    if(!project_id.value){
        const { code, data } = await api.getCaseDetail(case_id.value);
        if(code==200){
            project_id.value=data.project_id;
        }
    }
    handleGetConfig();
    getList();
}
const freshLike=(data)=>{
   console.log(data);
   if(data.parentIndex<0){
    let cuurent= list.value[data.index]
    cuurent.like_num+=data.likeNum;
    if(data.likeNum>0){
        cuurent.is_like=true;
    }else{
        cuurent.is_like=false;
    }
   }else{
    let cuurent=list.value[data.parentIndex].case_comment[data.index];
    console.log(cuurent);
     cuurent.like_num+=data.likeNum;
    if(data.likeNum>0){
        cuurent.is_like=true;
    }else{
        cuurent.is_like=false;
    }
   }
}
const freshSecComment=(data)=>{
     console.log('freshSecComment')
     console.log(data);

    list.value[data.commentIndex].case_comment=list.value[data.commentIndex].case_comment.concat(data.commentData)


}

const handleSubmit=()=>{
        let countS=props.countTime.split(':');
        let current=Number(countS[0])*60+Number(countS[1]);
        console.log('props.is_welfare:'+props.is_welfare)
        if(props.is_welfare==1 && is_white_user.value==1){
                if(message.value==='' && current<read_duration.value){
                changeDialog(1)
            }else if(message.value==='' && current>=read_duration.value){
                changeDialog(2)
            }else if(message.value && current<read_duration.value){
                changeDialog(3)
            }else{
                handleComplete()
            }
        }else{
            handleComplete()
        }
        
}
const handleAdd=async()=>{
    if(message.value==''){
        showToast('请输入内容');
        return false
    }
    isLock.value=true;
    const {code,data}=await api.addComment({
        case_id:case_id.value,
        project_id:project_id.value,
        content:message.value,
        level:1,
        root_id:'',
        parent_id:''
    })
    isLock.value=false;
    if(code==200){
        handleFreshList()
        message.value='';
        showLiuyan.value=false;
        showToast('留言成功')
    }
}
const handledCancel=()=>{
   
    handleComplete();
};
const handleComplete= async()=>{
    proxy.$loading.show();
    const {code,data}=await api.completeCase(case_id.value,{
        project_id:project_id.value,
        content:message.value,
        share_user_iden:share_user_iden.value,
        start_read:dayjs(props.start_time).format('YYYY-MM-DD HH:mm:ss'),
        end_read:dayjs().format('YYYY-MM-DD HH:mm:ss'),
        answer:answer.value
    })
     if(code==200){
        let last=localStorage.getItem('lastPage')
        behaviorRecord('完成',last,dayjs().format('YYYY-MM-DD HH:mm:ss'));
        if(source.value){
            router.push({
            path:'/result',
            query:{
                case_id:case_id.value,
                project_id:project_id.value,
                source:source.value
            }
         });
        }else{
            router.push({
            path:'/result',
            query:{
                case_id:case_id.value,
                project_id:project_id.value
            }
         });
        }
        
     }
     proxy.$loading.hide();
}
const handleGetConfig=async()=>{
    const {code,data}=await api.getConfig({
        project_id:project_id.value,
    });
    if(code==200){
        read_duration.value=data.read_duration;
        complete_read.value=data.complete_read;
        complete_read_time.value=data.complete_read_time;
        first_high_quality.value=data.first_high_quality;
        is_white_user.value=data.is_white_user;
        if(data.is_white_user==1){
            let txt='获取奖励';
            if(source.value){
                txt='获取e豆'
            }
            placeholder.value=`欢迎就本病例提出您的讨论话题、思考与诊疗分享，如病例疑难点、诊疗经验、用药心得等。(病例阅读时长≥${data.read_duration/60}分钟、留言入选精选留言均有机会${txt})`

        }else{
            placeholder.value=`欢迎就本病例提出您的讨论话题、思考与诊疗分享，如病例疑难点、诊疗经验、用药心得等。`
        }
       
        // if(data.read_duration==0){
        //     changeDialog(1)
        //  }
    }
}

//defineExpose({freshLike})

defineExpose({init,formatAnswer})

</script>

<style lang='scss' scoped>
.commentmain{
    :deep(.van-field__control::placeholder){
        color:#666;
    }
}

.main {
    width: 100%;
    position: relative;
    z-index:1;
    overflow: hidden;

    .add {
        margin: 25px auto;
        width: 250px;
        height: 40px;
        background: #43C9C3;
        border-radius: 23px;
        display: flex;
        font-size: 14px;
        color: #FFFFFF;
        justify-content: center;
        align-items: center;
    }

    .loadmore {
        margin-top: 15px;
        height: 50px;
        display: flex;
        font-size: 15px;
        color: #FFFFFF;
        justify-content: center;
        align-items: center;
        background: #0CAF98;
    }

    .conmmentbox {
        margin-top: 40px;
    }

    
    .expand {
        width: 240px;
        height: 19px;
        margin: 12px auto 12px;
        background: #43C9C3;
        border-radius: 4px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 10px;
        color: #FFFFFF;
    }

    .active {
        border-bottom: 1px solid #E5E5E5;
    }

    .textbox {
        border-radius: 5px;
        border: .5px solid #43C9C3;

        :deep() .van-cell {
            background: none;
        }

        :deep() .van-field__word-limit {
            color: #999999;
        }
    }

    .bg {
        width: 100%;
        position: absolute;
        z-index: -1;
    }

    .content {
        position: relative;
        margin: 20px 15px;
        min-height: 120px;
        margin-bottom: 20px;

        .count {
            :deep() .van-count-down {
                color: #fff;
            }

            right:0;
            top:-10px;
            z-index:9;
            display: flex;
            align-items: center;
            position: absolute;
            height: 31px;
            padding:0 8px;
            background: #43C9C3;
            border-radius: 8px;
        }

        .title {
            padding: 20px 0 10px;
            position: relative;
            font-weight: 600;
            font-size: 23px;
            color: #000000;
            .cai{
                width: 50px;
                height: 25px;
                bottom:4px;
                left:-4px;
                z-index:-1;
                position: absolute;
            }
        }

        .tips {
            font-weight: 400;
            font-size: 17px;
            color: #666666;
        }


    }

    

    .bottom {
        margin-top: 65px;
        width: 100%;
        overflow: hidden;



        .button {
            outline: none;
            width: 250px;
            height: 40px;
            margin: 34px auto 0;
            background: #43C9C3;
            border-radius: 20px;
            font-weight: 500;
            font-size: 17px;
            border: none;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #FFFFFF;
        }
    }

}
</style>
