<template>
    <div class="morning-week-page">
        <el-form :model="form" :rules="rules" label-width="80px" ref="form" class="form-wrap">
            <section class="section flex">
                <el-form-item label="报告类型" prop="type" style="width:50%">
                    <el-select :disabled="$route.query.isEdit" v-model="form.type" @change="typeChange" placeholder="请选择报告类型" style="width:80%">
                        <el-option label="周报" :value="'week'"></el-option>
                        <el-option label="晨报" :value="'day'"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="报告标题" prop="title" style="width:50%">
                    <el-input placeholder="请填写报告标题" v-model="form.title" style="width:80%"></el-input>
                </el-form-item>
                <el-form-item label="发布时间" prop="time" style="width:50%">
                    <el-date-picker
                        v-model="form.time"
                        type="date"
                        placeholder="选择日期"
                        style="width:80%"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="作者" prop="auth" style="width:50%">
                    <el-input placeholder="请填写作者" v-model="form.auth" style="width:80%"></el-input>
                </el-form-item>
                <div v-if="!$route.query.isEdit">
                    <el-button type="primary" plain @click="$router.go(-1)">取消</el-button>
                    <el-button type="primary" @click="handleSave">保存</el-button>
                </div>
            </section>
            <section class="section" v-if="$route.query.isEdit">
                <div style="font-size:16px;margin-bottom:20px">章节列表</div>
                <div class="list-box">
                    <div class="list-item" v-for="(item,index) in list" :key="item.ReportChapterId">
                        <div class="item-image-box">
                            <img :src="item.TypeEditImg" alt="" @click="goEditChapterReport(item)">
                            <p>{{item.TypeName}}</p>
                        </div>
                        <div style="border-bottom:1px solid #ededed;padding-bottom:5px;margin-bottom:5px">{{item.TypeName}}</div>
                        <div class="bot">
                            <p>
                                <span :style="{color:item.PublishState==2&&'#67C23A'}">{{item.PublishState==1?'未发布':'已发布'}}</span>
                                <span style="float:right;color:#4099ef;cursor: pointer;" @click.stop="handleShowEditTag(item)">{{item.Trend||'添加标签'}}</span>
                            </p>
                            <p style="margin-top:5px">
                                <span :style="{color:item.VideoUrl&&item.VideoKind==1?'#67C23A':''}" v-if="form.type=='week'">{{item.VideoUrl&&item.VideoKind==1?'已传录音':'未传录音'}}</span>
                                <el-popover
                                    placement="bottom"
                                    trigger="click"
                                >   
                                    <img style="width:150px" :src="item.QRCodeImg" alt="">
                                    <span 
                                        slot="reference" 
                                        style="float:right;color:#4099ef;cursor: pointer;" 
                                        v-if="item.PublishState==2" 
                                        @click="handleGetWechatImg(item,index)"
                                    >微信分享</span>
                                </el-popover>
                            </p>
                            <p style="margin-top:5px"><span>{{item.ModifyTime}}</span></p>
                        </div>
                    </div>
                </div>
                <div>
                    <el-button type="primary" style="width:120px" @click="handleEditDayWeekReport">保存</el-button>
                    <el-button type="primary" style="width:120px" @click="handlePublishValid">发布</el-button>
                </div>
            </section>
        </el-form>

      <!-- 章节标签 -->
      <el-dialog
        :visible.sync="editTag.show"
		:modal-append-to-body='false'
		width="400px"
        title="设置标签"
        v-dialogDrag
      >
        <div class="edit-tag-wrap">
            <span>{{editTag.type}}</span>
            <el-select
                v-model="editTag.text"
                filterable
                allow-create
                default-first-option
                placeholder="输入或者选择">
                <el-option
                    v-for="item in TagOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
            </el-select>
            <div style="margin:30px 0;text-align:center">
                <el-button type="primary" plain @click="editTag.show=false">取消</el-button>
                <el-button type="primary" @click="handleEditTrendTag">确定</el-button>
            </div>
        </div>
      </el-dialog>
    </div>
</template>
<script>
import moment from 'moment'
import {
    dayWeekChapterList,
    addDayWeekReport,
    chapterTrendTagList,
    editChapterTrendTag,
    editDayWeekReport,
    publishDayOrWeekReport,
    messagePushPost,
    chapterQRCodeImg,
    reportMessageSend,
    weekReportValidAudio
} from '@/api/api.js'
export default {
    beforeRouteEnter(to, from, next) {
        if(to.query.type){
            to.matched[1].name=`编辑${to.query.type=='day'?'晨报':'周报'}`
        }else{
            to.matched[1].name='编辑晨报/周报'
        }
        next()
    },
    data () {
        return {
            form:{
                type:'',
                title:'',
                time:'',
                auth:''
            },
            rules:{
                type:[{required:true,message:'请选择报告类型',trigger:'change'}],
                title:[{required:true,message:'请填写报告标题',trigger:'blur'}],
                time:[{required:true,message:'请选择日期',trigger:'change'}]
            },
            list:[],
            reportId:this.$route.query.reportid||'',
            isEdit:this.$route.query.isEdit,
            editTag:{
                show:false,
                ReportChapterId:0,
                text:'',
                type:''//编辑的章节名称
            },//编辑标签
            TagOptions:[]
        }
    },
    created () {
        if(this.reportId){
            this.getChapterList(this.reportId)
            const data=JSON.parse(sessionStorage.getItem('dayWeek'))
            this.form.type=data.ChapterType
            this.form.title=data.Title
            this.form.time=moment(data.CreateTime).format('YYYY-MM-DD')
            this.form.auth=data.Author
        }  
    },
    methods:{
        typeChange(){
            this.form.title=`【弘则FICC${this.form.type=='day'?'晨报':'周报'}】`
            this.form.time=moment().format('YYYY-MM-DD')
            this.form.auth='弘则研究'
        },
        
        //保存
        handleSave(){
            this.$refs.form.validate((valid)=>{
                if(valid){
                    addDayWeekReport({
                        Title:this.form.title,
                        ReportType:this.form.type,
                        CreateTime:this.form.time,
                        Author:this.form.auth
                    }).then(res=>{
                        if(res.Ret===200){
                            this.reportId=res.Data.ReportId
                            this.getChapterList(res.Data.ReportId)
                            const formData={
                                ChapterType:this.form.type,
                                Title:this.form.title,
                                CreateTime:this.form.time,
                                Author:this.form.auth
                            }
                            sessionStorage.setItem('dayWeek',JSON.stringify(formData))
                            this.$router.replace({
                                query:{
                                    reportid:res.Data.ReportId,
                                    isEdit:true,
                                    type:this.form.type
                                }
                            })
                        }
                    })
                }
            })
        },

        // 获取章节列表
        async getChapterList(reportId){
            const res=await dayWeekChapterList({ReportId:reportId})
            if(res.Ret===200){
                this.list=res.Data
                this.getChapterTrendTagList()
            }
        },

        //获取章节标签数据（仅在获取章节列表成功后获取一次）
        async getChapterTrendTagList(){
            const res=await chapterTrendTagList()
            if(res.Ret===200){
                let arr=res.Data||[]
                this.TagOptions=arr.map(item=>{
                    return {value:item.KeyWord,label:item.KeyWord}
                })
            }
        },

        // 点击修改标签
        handleShowEditTag(item){
            this.editTag={
                show:true,
                ReportChapterId:item.ReportChapterId,
                text:item.Trend,
                type:item.TypeName
            }
        },

        //确定修改标签
        async handleEditTrendTag(){
            const res=await editChapterTrendTag({
                ReportChapterId:Number(this.editTag.ReportChapterId),
                Trend:this.editTag.text
            })
            if(res.Ret===200){
                this.$message.success('修改成功')
                this.editTag.show=false
                this.getChapterList(this.reportId)
            }
        },

        //修改晨报周报
        async handleEditDayWeekReport(){
            this.$refs.form.validate((valid)=>{
                if(valid){
                    editDayWeekReport({
                        ReportId:Number(this.reportId),
                        Title:this.form.title,
                        ReportType:this.form.type,
                        CreateTime:this.form.time,
                        Author:this.form.auth
                    }).then(res=>{
                        if(res.Ret===200){
                            this.$message.success('保存成功')
                        }
                    })
                }
            })
        },

        //前往编辑章节详情
        goEditChapterReport(item){
            this.$router.push({
                path:'/editchapterreport',
                query:{
                    id:item.ReportChapterId,
                    type:item.ReportType,
                    typename:item.TypeName
                }
            })
        },

        //周报校验音频是否都上传了
        async handlePublishValid(){
            if(this.form.type==='week'){
                const validRes=await weekReportValidAudio({ReportId:Number(this.reportId)})
                if(validRes.Ret===200){
                    if(validRes.Data){
                        this.$confirm(`报告未上传录音：${validRes.Data.join('、')}，确定发布吗？`, '发布提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(()=>{
                            this.handlePublishReport()
                        }).catch(()=>{})
                    }else{
                        this.handlePublishReport()
                    }
                    
                }
                return
            }else{
                this.handlePublishReport()
            }
        },

        //发布报告 晨报提示是否推送客群
        async handlePublishReport(){
            const res=await publishDayOrWeekReport({
                ReportId:Number(this.reportId)
            })
            if(res.Ret===200){
                if(this.form.type=='day'){
                    if(res.Data){
                        this.$alert(res.Data, '发布提示', {
                            confirmButtonText: '确定',
                            callback: action => {
                                this.$confirm('发布后，是否推送模板消息和客户群？', '发布提示', {
                                    confirmButtonText: '推送',
                                    cancelButtonText: '不推送',
                                    type: 'warning'
                                }).then(async ()=>{
                                    const pushRes=await reportMessageSend({ReportId:this.reportId})
                                    if(pushRes.Ret===200){
                                        this.$message.success('推送成功')
                                        setTimeout(() => {
                                            this.$router.go(-1)
                                        }, 1500);
                                    }
                                }).catch(()=>{
                                    this.$message.success('发布成功')
                                    setTimeout(() => {
                                        this.$router.go(-1)
                                    }, 1500);
                                })
                            }
                        });
                    }else{
                        this.$confirm('发布后，是否推送模板消息和客户群？', '发布提示', {
                            confirmButtonText: '推送',
                            cancelButtonText: '不推送',
                            type: 'warning'
                        }).then(async ()=>{
                            const pushRes=await reportMessageSend({ReportId:this.reportId})
                            if(pushRes.Ret===200){
                                this.$message.success('推送成功')
                                setTimeout(() => {
                                    this.$router.go(-1)
                                }, 1500);
                            }
                        }).catch(()=>{
                            this.$message.success('发布成功')
                            setTimeout(() => {
                                this.$router.go(-1)
                            }, 1500);
                        })
                    }

                    


                }else{
                    this.$message.success('发布成功')
                    setTimeout(() => {
                        this.$router.go(-1)
                    }, 1500);
                }
            }

        },

        //获取章节太阳码
        async handleGetWechatImg(item,index){
            // 如果存在则不请求
            if(item.QRCodeImg) return
            const res=await chapterQRCodeImg({
                CodeScene:JSON.stringify({chapterId:item.ReportChapterId.toString()}),
                CodePage:'pages-report/chapterDetail'
            })
            if(res.Ret===200){
                this.$set(this.list,index,{...item,QRCodeImg:res.Data})
            }
        }

    }
}
</script>

<style lang="scss" scoped>
// .el-row{
//     flex-wrap: wrap;
// }
.morning-week-page{
    .section{
        background: #FFFFFF;
        border-radius: 4px;
        border: 1px solid #ECECEC;
        padding: 20px 30px;
        margin-bottom: 30px;
    }
    .flex{
        display: flex;
        flex-wrap: wrap;
    }
    .list-box{
    display: flex;
    // align-items: center;
    flex-wrap: wrap;
    // justify-content: space-between;
    margin-left: -20px;
        .list-item{
            margin-left: 20px;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 20px;
            border: 1px solid #ECECEC;
            width: 160px;
            // flex: 1;
            .item-image-box{
                position: relative;
                width: 160px;
                height: 160px;
                margin: 0 auto;
                img{
                    width: 100%;
                    display: block;
                    height: 160px;
                    background-color: gray;
                }
                p{
                    // white-space: nowrap;
                    word-break: break-all;
                    font-size: 20px;
                    color: white;
                    font-weight: bolder;
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translateX(-50%) translateY(-50%);
                    cursor:default;
                    pointer-events: none;
                    min-width: 100%;
                    text-align: center;
                }
            }
        }
    }
}
</style>
