<template>
    <div class="edit-smart-report-page">
        <!-- 顶部操作栏 -->
        <div class="top-action-wrap">
            <div class="title">{{reportInfo&&reportInfo.Title}}</div>
            <ul class="action-list">
                <li class="action-item" @click="showReportBaseInfo=true">
                    <img src="~@/assets/img/smartReport/icon01.png" alt="">
                    <span>基础信息</span>
                </li>
                <li class="action-item" @click="handleRefreshAllChart">
                    <img src="~@/assets/img/smartReport/icon02.png" alt="">
                    <span>图表刷新 </span>
                </li>
                <li class="action-item" @click="handlePreviewReport">
                    <img src="~@/assets/img/smartReport/icon03.png" alt="">
                    <span>预览</span>
                </li>
                <li class="action-item" @click="handleSaveContent">
                    <img src="~@/assets/img/smartReport/icon01.png" alt="">
                    <span>存草稿</span>
                </li>
                <li class="action-item" @click="handlePublishOpt('dsfb')">
                    <img src="~@/assets/img/smartReport/icon01.png" alt="">
                    <span>定时发布</span>
                </li>
                <li class="action-item" @click="handlePublishOpt('fb')">
                    <img src="~@/assets/img/smartReport/icon01.png" alt="">
                    <span>发布</span>
                </li>
            </ul>
        </div>
        <div class="main-wrap">
            <div class="report-action-wrap">
                <ul class="top-type-list">
                    <li class="item" v-for="item in topTypeList" :key="item.name" @click="handleShowRight(item)">
                        <img class="icon" :src="item.icon" alt="">
                        <span>{{item.name}}</span>
                    </li>
                </ul>
                <!-- 公共组件 -->
                <draggable
                    :list="compList"
                    :group="{ name: 'component', pull: 'clone', put: false }"
                    class="report-comp-wrap"
                    animation="300"
                    :sort="false"
                    tag="ul"
                >
                    <li class="comp-item" :comp-data="JSON.stringify(comp)" v-for="comp in compList" :key="comp.id">
                        <img :src="comp.icon">
                    </li>
                </draggable>

                <div class="report-content-box">
                    <draggable
                        :list="conList"
                        :group="{ name: 'component', pull: true, put: true }"
                        class="report-html-wrap"
                        animation="300"
                        tag="div"
                        handle=".drag-btn_p"
                        @add="handleParentAdd"
                        @remove="handleParentRemove"
                        :move="handleParentMove"
                    >
                        <div 
                            :class="['report-drag-item-wrap',activeId===item.id?'blue-bg':'']" 
                            v-for="item,index in conList" 
                            :key="item.id"
                            :comp-type="item.compType"
                            @click="handleChoose(item,index)"
                            :style="item.style"
                        >
                            <!-- 缩放的盒子 -->
                            <div class="resize-drag-box" @mousedown.stop="handleResizeP($event,index)"></div>
                            <div class="opt-btn-box" style="display: none;">
                                <div class="drag-btn drag-btn_p"></div>
                                <div class="del-btn" @click.stop="handleDelItem(index,-1)"></div>
                            </div>
                            <div 
                                v-if="item.child&&!item.child.length"
                                class="report-drag-item-wrap_content"
                                :data-id="item.id"
                            >
                                <component :is="getComponentName(item)" :compData="item"/>
                            </div>
                            <draggable
                                :list="item.child"
                                :group="{ name: 'component', pull: true, put: item.child&&item.child.length<3?true:false }"
                                animation="300"
                                tag="div"
                                class="report-drag-item-wrap_child-wrap"
                                @add="handleChildAdd($event,item,index)"
                                @remove="handleChildRemove($event,item.child)"
                                handle=".drag-btn_c"
                                style="display: flex;gap: 20px;align-items: flex-start;"
                            >
                                <div 
                                    :class="['report-drag-item-wrap_child_content',activeId===child.id?'blue-bg':'']" 
                                    v-for="child,cindex in item.child" 
                                    :key="child.id"
                                    :comp-type="child.compType"
                                    :data-id="child.id"
                                    @click.stop="handleChoose(child,index,cindex)"
                                    style="flex:1"
                                    :style="child.style"
                                >
                                    <div class="opt-btn-box2" style="display: none;">
                                        <div class="drag-btn drag-btn_c"></div>
                                        <div class="del-btn" @click.stop="handleDelItem(index,cindex)"></div>
                                    </div>
                                    <!-- 拖动按钮 -->
                                    <div class="resize-drag-box_lb" @mousedown.stop="handleResizeC($event,index,cindex,'lb')"></div>
                                    <div class="resize-drag-box_rb" @mousedown.stop="handleResizeC($event,index,cindex,'rb')"></div>
                                    <component :is="getComponentName(child)" :compData="child"/>
                                </div>
                            </draggable>
                        </div>
                    </draggable>
                </div>
            </div>

            <div class="right-action-wrap" v-show="showRight">
                <div class="close-icon" @click="handleCloseRight">
                    <img src="~@/assets/img/smartReport/icon14.png" alt="">
                </div>
                <div style="overflow-x:auto">
                    <div style="min-width:600px">
                <TextEdit 
                    v-if="rightType==='text'"
                    :key="activeId"
                    :content="activeContent" 
                    @textChange="handleTextChange" 
                />
                <ImgEdit 
                    v-if="rightType==='img'"
                    :key="activeId"
                    :content="activeContent" 
                    @imgChange="handleTextChange" 
                />
                <!-- 图库插入 -->
                <ETAChart 
                    v-if="rightType==='etaChart'"
                    @handleImportMyChart="handleImportMyChart"
                />
                <!-- ETA表格 -->
                <ETASheet v-if="rightType==='etaSheet'"/>
                <!-- 统计分析 -->
                <StatisticAnalysis v-if="rightType==='statisticAnalysis'"/>
                <!-- 商品价格曲线 -->
                <ETAPriceChart v-if="rightType==='etaPriceChart'"/>
                <!-- 沙盘图 -->
                <ETASandBox v-if="rightType==='etaSandBox'"/>
                <!-- 语义分析 -->
                <SemanticAnalysis v-if="rightType==='semanticAnalysis'"/>
                    </div>
                </div>
            </div>
        </div>

        <!-- 报告基础信息 -->
        <BaseInfo  v-model="showReportBaseInfo" :id="$route.query.id" @save="handleReportEdit" />

        <!-- 定时发布弹窗 -->
		<el-dialog 
			v-dialogDrag 
			:append-to-body="true" 
			:visible.sync="showDSFB" 
			width="500px" 
			title="定时发布"
		>
			<div>
				<div>
					<span>发送时间</span>
					<el-date-picker
						v-model="taskTime"
						type="datetime"
						placeholder="选择日期时间"
						value-format="yyyy-MM-dd HH:mm"
						:picker-options="timePickerOpt"
					/>
				</div>
				<p style="margin:15px 0">设置成功之后，研报将定时进行发送。</p>
				<div style="text-align:right;margin:20px 0">
					<el-button type="primary" plain @click="showDSFB=false">取消</el-button>
					<el-button type="primary" @click="handleSetReportPrepublish">确定</el-button>
				</div>
			</div>
		</el-dialog>

    </div>
</template>

<script>
import draggable from 'vuedraggable'
import TextComp from './components/TextComp.vue'
import ChartComp from './components/ChartComp.vue'
import ImgComp from './components/ImgComp.vue'
import SheetComp from './components/SheetComp.vue'
import _ from 'lodash'
import TextEdit from './components/TextEdit.vue'
import ImgEdit from './components/ImgEdit.vue'
import ETAChart from './components/ETAChart.vue'
import ETASheet from './components/ETASheet.vue'
import { getPublicSettingsApi } from '@/api/modules/oldApi';
import { dataBaseInterface } from "@/api/api.js";
import {apiSmartReport}  from '@/api/modules/smartReport'
import BaseInfo from './components/BaseInfo.vue'
import StatisticAnalysis from './components/StatisticAnalysis.vue'
import ETAPriceChart from './components/ETAPriceChart.vue'
import ETASandBox from './components/ETASandBox.vue'
import SemanticAnalysis from './components/SemanticAnalysis.vue'
import { getUrlParams } from '@/utils/common'
export default {
    name:"smartReportEdit",
    components: {
        draggable,
        BaseInfo,
        TextComp,
        ChartComp,
        ImgComp,
        SheetComp,
        TextEdit,
        ImgEdit,
        ETAChart,
        ETASheet,
        StatisticAnalysis,
        ETAPriceChart,
        ETASandBox,
        SemanticAnalysis
    },
    watch:{
        'taskTime'(){
            this.taskTime=this.$moment(this.taskTime).format('YYYY-MM-DD HH:mm')+':00'
			const date = this.$moment(this.taskTime).startOf('day').format('x');
	        const nowDate = this.$moment().startOf('day').format('x');
	        // 如果选择的是今天 则需要禁用已经过去的时间节点
	        if (date <= nowDate) {
	            // 默认选择的最新时间 是当前时间的两分钟后 （留出2分钟的富裕时间）
	            this.timePickerOpt.selectableRange = (
	                `${this.$moment().add(2,'m').format('HH:mm:ss')} - 23:59:59`
	            );
	        }else {
				// 如果是以后的日期，则不需要禁用时间节点
	            this.timePickerOpt.selectableRange = '00:00:00 - 23:59:59';
	        }
		},
        conList:{
            handler(n,o){
                console.log('内容改变');
                this.contentChange=true
            },
            deep:true
        }
    },
    data() {
        return {
            reportInfo:null,
            showReportBaseInfo:false,

            topTypeList:[
                {
                    name:'图库',
                    type:'etaChart',
                    icon:require('@/assets/img/smartReport/icon04.png')
                },
                {
                    name:'ETA表格',
                    type:'etaSheet',
                    icon:require('@/assets/img/smartReport/icon05.png')
                },
                {
                    name:'统计分析',
                    type:'statisticAnalysis',
                    icon:require('@/assets/img/smartReport/icon06.png')
                },
                {
                    name:'商品价格曲线',
                    type:'etaPriceChart',
                    icon:require('@/assets/img/smartReport/icon07.png')
                },
                {
                    name:'沙盘图',
                    type:'etaSandBox',
                    icon:require('@/assets/img/smartReport/icon08.png')
                },
                {
                    name:'语义分析',
                    type:'semanticAnalysis',
                    icon:require('@/assets/img/smartReport/icon09.png')
                }
            ],
            compList:[
                {   
                    compId:1,
                    compType:'text',
                    icon:require('@/assets/img/smartReport/icon10.png')
                },
                {
                    compId:2,
                    compType:'img',
                    icon:require('@/assets/img/smartReport/icon11.png')
                },
                // {
                //     compId:3,
                //     compType:'chart',
                // },
                // {
                //     compId:4,
                //     compType:'sheet',
                // }
                
            ],
            conList:[],
            activeId:'',
            activeContent:'',
            activePindex:'',
            activeCindex:'',
            showRight:false,
            rightType:'',

            timer:null,//自动保存定时器

            showDSFB:false,//显示定时发布弹窗
			taskTime:'',//定时发布的时间
			timePickerOpt:{
				disabledDate(e){
					return e.getTime()< new Date().getTime()-24 * 60 * 60 * 1000
				},
				selectableRange:'00:00:00 - 23:59:59',
                format:'HH:mm'
			},

            contentChange:false,//内容是否发生变化

            isDragResize:false,//是否正在拖动缩放
        }
    },
    methods: {
        // 大盒子的高度缩放
        handleResizeP(e,index){
            this.isDragResize=true
            e.preventDefault()
            const targetBox=e.target.parentNode
            const targetBoxHeight=targetBox.offsetHeight
            const startY=e.clientY
            document.onmousemove=(mouseEl)=>{
                mouseEl.preventDefault()
                const h=mouseEl.clientY-startY+targetBoxHeight
                targetBox.style.minHeight=`${h<50?50:h}px`
            }
            document.onmouseup=(el)=>{
                console.log(targetBox.style.cssText);
                this.$set(this.conList[index],'style',targetBox.style.cssText)
                el.preventDefault()
                document.onmousemove=null
                setTimeout(() => {
                    this.isDragResize=false
                }, 50);
                
            }
        },
        // 内部元素的缩放
        handleResizeC(e,index,cindex,type){
            this.isDragResize=true
            e.preventDefault()
            const parentBox=e.target.parentNode.parentNode
            const parentBoxWidth=parentBox.offsetWidth
            console.log(e);
            const targetBox=e.target.parentNode
            const targetBoxHeight=targetBox.offsetHeight
            const targetBoxWidth=targetBox.offsetWidth
            const startY=e.clientY
            const startX=e.clientX
            const initW=targetBoxWidth //拖动前要拖动盒子所占的宽度

            let computerW=0//存放其他兄弟节点要改变的宽度的值

            document.onmousemove=(mouseEl)=>{
                mouseEl.preventDefault()
                const h=mouseEl.clientY-startY+targetBoxHeight
                // 计算宽度
                const w=type==='rb'?mouseEl.clientX-startX+targetBoxWidth:startX-mouseEl.clientX+targetBoxWidth
                const resW= (w/parentBoxWidth)*100//计算出的百分比结果值
                targetBox.style.width=resW+'%'
                targetBox.style.flex='none'

                // 处理兄弟盒子的宽度
                const changeW=w-initW //宽度变化值
                computerW=changeW
                if(parentBox.childNodes.length===3){
                    computerW=changeW/2
                }
                // console.log('改变的宽度',computerW);

                targetBox.style.height=`${h<50?50:h}px`
            }   
            document.onmouseup=(el)=>{
                if(document.onmousemove){
                    parentBox.childNodes.forEach(item=>{
                        if(item!==targetBox){
                            const temw=item.offsetWidth-computerW
                            item.style.width=((temw/parentBoxWidth)*100)+'%'
                        }
                    })
                    // 存储修改的值
                    parentBox.childNodes.forEach((item,idx)=>{
                        this.$set(this.conList[index].child[idx],'style',item.style.cssText)
                    })
                }
                el.preventDefault()
                document.onmousemove=null
                setTimeout(() => {
                    this.isDragResize=false
                    document.onmouseup=null
                }, 50);
            }
        },

        // 跳转预览
        handlePreviewReport(){
            const htmlStr=$('.report-html-wrap').html()
            sessionStorage.setItem('smartReportContent', htmlStr);
			let { href } = this.$router.resolve({ 
                path: '/smartReportDetail',
                query:{
                    id:this.$route.query.id,
                    type:'preview'
                }
            });
			window.open(href, '_blank');
        },

        // 批量插入myETA数据
        handleImportMyChart(list){
            const LINK_CHART_URL = this.$setting.dynamicOutLinks.ChartViewUrl+'/chartshow';
            // console.log(list);
            let arr=[]
            // 分成三个一组
            for (let index = 0; index < list.length; index+=3) {
                const temarr=list.slice(index,index+3)
                let resArr={child:[]}
                if(temarr.length===1){//落单了
                    resArr={
                        compId:3,
                        compType:'chart',
                        content:`${LINK_CHART_URL}?code=${temarr[0].UniqueCode}`,
                        id:this.getCompId(`chart${temarr[0].UniqueCode}_`),
                        child:[]
                    }
                }else{
                    temarr.forEach(e => {
                        resArr.child.push({
                            compId:3,
                            compType:'chart',
                            content:`${LINK_CHART_URL}?code=${e.UniqueCode}`,
                            id:this.getCompId(`chart${e.UniqueCode}_`),
                            child:[]
                        })
                    });
                }
                arr.push(resArr)
            }
            // console.log(arr);
            this.conList=[...this.conList,...arr]
            
        },

        // 设置sheet iframe 样式
        setSheetIframeStyle(e){
            const { height, code } = e.data;
            // console.log(e.data);
            let iframeDom = document.getElementsByClassName(`iframe${code}`);
            // console.log(iframeDom);
            iframeDom.forEach((ele) => {
                ele.height = `${height + 45}px`;
            });
        },

        handleParentAdd(e){
            console.log('container-onAdd操作------------------->');

            const {item,newDraggableIndex}=e

            const hasid=item.getAttribute('data-id')
            console.log(hasid);

            this.conList.forEach(item=>{
                if(item.id==hasid&&item.style){
                    const styleArr=item.style.split(';').filter(s=>s&&(s.indexOf('width')===-1&&s.indexOf('flex')===-1)).join(';')
                    item.style=styleArr
                }
            })
            if(hasid) return

            // 要添加的元素数据
            const compData=JSON.parse(item.getAttribute('comp-data'))
            // console.log(compData);
            // 非注册组件返回
            // if(!comp){
            //     this.conList.splice(newDraggableIndex,1)
            //     return
            // }
            const tempCompData={
                compId:compData.compId,
                compType:compData.compType,
                id:this.getCompId(compData.compType),
                content:compData.content||'',
                child:[]
            }
            // console.log(tempCompData);
            this.conList.splice(newDraggableIndex,1,tempCompData)
            // this.activeId=tempCompData.id
        },

        handleChildAdd(e,parent,parentIndex){
            console.log('child-onAdd操作------------------->');
            // console.log(parent);
            const {item,newDraggableIndex}=e

            const compData=JSON.parse(item.getAttribute('comp-data'))

            console.log(compData,newDraggableIndex);

            const index=parentIndex
            // if(index>-1){
                let obj=_.cloneDeep(this.conList[index]) 

                console.log(obj);

                if(obj.child&&obj.child.length===1&&obj.id){
                    if(compData){
                        obj={
                            child:[
                                {
                                    compId:obj.compId,
                                    compType:obj.compType,
                                    id:obj.id,
                                    content:obj.content,
                                    child:[]
                                },
                                {
                                    compId:compData.compId,
                                    compType:compData.compType,
                                    content:compData.content||'',
                                    id:this.getCompId(compData.compType),
                                    child:[]
                                }
                            ]
                        }
                    }else{//是内容区域拖动排序的
                        const temItem=_.cloneDeep(obj.child[0])
                        if(temItem.child.length>0){//如果拖动的盒子里面有子元素则不能进入
                            obj={
                                ...obj,
                                child:[]
                            }
                            setTimeout(() => {
                                this.conList.splice(index,0,temItem)
                            }, 50);
                        }else{
                            obj={
                                child:[
                                    {
                                        compId:obj.compId,
                                        compType:obj.compType,
                                        id:obj.id,
                                        content:obj.content,
                                        child:[]
                                    },
                                    {
                                        ...temItem
                                    }
                                ]
                            }
                        }
                    }
                    
                }else{
                    if(compData){//如果是从内容区域拖入的没有compData
                        obj.child.splice(newDraggableIndex,1,{
                            compId:compData.compId,
                            compType:compData.compType,
                            content:compData.content||'',
                            id:this.getCompId(compData.compType),
                            child:[]
                        })
                    }
                    
                }
                console.log(obj);

                this.conList.splice(index,1,obj)
            // }
        },

        handleParentMove(e){
            // console.log(e.draggedContext);
            // console.log(e.relatedContext);
            // // console.log(e.relatedContext.compType);
            // console.log(e.draggedContext.element.child.length>0&&!e.relatedContext.compType);
            // if(e.draggedContext.element.child.length>0&&(!e.relatedContext.compType||e.relatedContext.element.compType)) return false
        },

        // 移除事件 
        handleChildRemove(e,arr){
            console.log('child-remove操作------------------->');
            // 如果都移除了则删除这个
            // this.conList=this.conList.filter(_item=>!(_item.child&&_item.child.length===0&&!_item.id))

            // 如果当前移出的这个child还有两个的话则重置他们的宽度
            arr.forEach(item=>{
                if(item.style){
                    const styleArr=item.style.split(';').filter(s=>s&&(s.indexOf('width')===-1&&s.indexOf('flex')===-1)).join(';')
                    item.style=styleArr
                }
            })


            // 如果child只剩一个了则移出来
            this.conList=this.conList.map(_item=>{
                if(_item.child&&_item.child.length===1){
                    const obj=_item.child[0]
                    if(obj.style){
                        const styleArr=obj.style.split(';').filter(s=>s&&(s.indexOf('width')===-1&&s.indexOf('flex')===-1)).join(';')
                        obj.style=styleArr
                    }
                    return obj
                }else{
                    return _item
                }
            })
        },

        handleParentRemove(e){
            console.log('container-remove操作------------------->');
        },

        // 点击删除某个
        handleDelItem(pindex,cindex){
            if(cindex===-1){
                this.conList.splice(pindex,1)
            }else{//删除子盒子
                this.conList[pindex].child.splice(cindex,1)
                if(this.conList[pindex].child.length===1){//只剩一个子盒子了则变成一个大盒子
                    this.conList[pindex]=this.conList[pindex].child[0]
                    this.conList[pindex].style='flex:1'
                }
            }
        },

        // 富文本编辑组件/图片组件数据变化
        handleTextChange(e){
            console.log(e);
            this.activeContent=e
            if(this.activeCindex>=0&&this.activeCindex!==''){
                if(this.conList[this.activePindex].child[this.activeCindex].content){
                    this.conList[this.activePindex].child[this.activeCindex].content=e
                }else{
                    this.$set(this.conList[this.activePindex].child[this.activeCindex],'content',e)
                }
            }else{
                if(this.conList[this.activePindex].content){
                    this.conList[this.activePindex].content=e
                }else{
                    this.$set(this.conList[this.activePindex],'content',e)
                }
            }
        },

        // 当前再编辑哪个
        handleChoose(item,index,cindex){
            //{item:数据,index:父序号,cindex:子序号}
            if(!item.id||this.isDragResize||!['text','img'].includes(item.compType)) return
            this.activeId=item.id
            this.showRight=true
            this.rightType=item.compType
            this.activeContent=item.content||''
            this.activePindex=index
            this.activeCindex=cindex>=0?cindex:''
        },

        //点击顶部插入图或者图表等类型
        handleShowRight(item){
            this.rightType=item.type
            this.activeId=''
            this.activeContent=''
            this.activePindex=''
            this.activeCindex=''
            this.showRight=true 
        },

        // 关闭右侧
        handleCloseRight(){
            this.activeId=''
            this.activeContent=''
            this.activePindex=''
            this.activeCindex=''
            this.showRight=false
            this.rightType=''
        },

        getComponentName(item){
            const temMap=new Map([
                ['text',TextComp],
                ['chart',ChartComp],
                ['img',ImgComp],
                ['sheet',SheetComp]
            ])
            return temMap.get(item.compType)
        },
        // 生产随机id
        getCompId(type){
            return type+new Date().getTime()
        },

        // 编辑保存报告
        handleReportEdit(e){
            const params={
                SmartReportId:Number(this.$route.query.id)||0,
                ...e,
                Content:$('.report-html-wrap').html(),
                ContentStruct:JSON.stringify(this.conList)
            }
            console.log(params);
            apiSmartReport.reportEdit({...params}).then(res=>{
                if(res.Ret===200){
                    this.$message.success('保存成功')
                    this.reportInfo.Title=params.Title
                    this.showReportBaseInfo=false
                }
            })
        },

        /* 获取动态配置 外部动态链接 */
        async getPublicSettings() {
            const res =  await getPublicSettingsApi();
            if(res.Ret !== 200) return
            
            this.$store.commit('SET_DYNAMIC_LINK',res.Data)
        },

        // 获取报告详情
        getReportDetail(){
            const id=this.$route.query.id||0
            if(!id) return
            apiSmartReport.reportDetail({
                SmartReportId:Number(id)
            }).then(res=>{
                if(res.Ret===200){
                    this.reportInfo=res.Data
                    this.conList=res.Data.ContentStruct?JSON.parse(res.Data.ContentStruct):[]
                    this.$nextTick(()=>{
                        this.contentChange=false
                    })
                }
            })
        },

        // 刷新所有图表
        handleRefreshAllChart: _.debounce ( async function() {
            let code_arr = [];
            $('iframe').each((k,i) => {
                try {
                    let href = $(i).attr('src');
                    code_arr.push(getUrlParams(href,'code'));
                } catch (err) {
                }
            });

            if(!code_arr.length) return this.$message.warning('请插入图表');

            const loading = this.$loading({
                lock: true,
                text: '刷新中..',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.02)'
            });

            const { Ret } = await dataBaseInterface.reportRefresh({
                ChartInfoCode: code_arr
            })
        
            loading.close();
            
            if(Ret === 200) {
                $('iframe').each((k,i) => {
                    $(i).attr('src',$(i).attr('src'))
                });
                this.$message.success('刷新成功');
            }

        },1000),
        
        // 自动/存草稿保存内容
        handleSaveContent({isAutoSave}){
            return new Promise((resolve,reject)=>{
                const id=this.$route.query.id||0
                if(!id) return
                apiSmartReport.saveReportContent({
                    SmartReportId:Number(id),
                    Content:$('.report-html-wrap').html(),
                    ContentStruct:JSON.stringify(this.conList),
                    NoChange:this.contentChange?2:1,
                }).then(res=>{
                    if(res.Ret===200){
                        resolve(true)
                        if(!isAutoSave){
                            this.$message.success('保存成功')
                        }
                    }
                    if(res.Msg==='报告已发布, 不允许编辑'){
                        this.$router.replace({ path: '/smartReportList' });
                    }
                })
            })
        },

        // 点击定时发布/发布
        async handlePublishOpt(type){
            // 存一次草稿
            const saveRes=await this.handleSaveContent({isAutoSave:true})
            if(!saveRes) return
            if(type==='dsfb'){
                this.showDSFB=true
                return
            }
            // 发布
            if(this.reportInfo.MsgIsSend==1){//该报告已经推送过模板消息
                this.reportPublish({sendMsg:false})
            }else{
                const isPost = this.permissionBtn.checkPermissionBtn(this.permissionBtn.smartReportManageBtn.reportManage_sendMsg)
                this.$confirm(
                    isPost?'发布后，是否推送模板消息？':'是否立即发布报告？', 
                    '发布提示', 
                    {
                        confirmButtonText: isPost?'推送':'发布',
                        cancelButtonText: isPost?'不推送':'取消',
                        type: 'warning',
                        distinguishCancelAndClose:true,
                    
                        beforeClose:(action, instance,done)=>{
                            if(action==='close') {
                                //右上角
                                // this.isPublishloading = false;
                            } else if(action==='cancel') {
                                //cancelButton
                                if(isPost){
                                    this.reportPublish({sendMsg:false})
                                }
                            }else {
                                //confirmButton
                                this.reportPublish({sendMsg:isPost?true:false})
                            }
                            done()
                        }
                    }
                )
            }
        },

        // 定时发布报告
        async handleSetReportPrepublish(){
            if(!this.taskTime){
				this.$message.warning('请选择定时发布的时间')
				return
			}
			const now=this.$moment().format('YYYY-MM-DD HH:mm:ss')
			// console.log(now);
			// console.log(this.taskTime);
			if(this.$moment(this.taskTime).isBefore(now,'second')){
				this.$message.warning('定时发布不得早于当前时间')
				return
			}
            // 如果该报告已经推送过模板消息
            if(this.reportInfo.MsgIsSend==1){
                apiSmartReport.prePublishReport({
                    SmartReportId:Number(this.$route.query.id),
                    PrePublishTime:this.taskTime,
                    PreMsgSend:0
                }).then(res=>{
                    if(res.Ret===200){
                        this.$message.success('定时发布成功！')
                        this.$router.replace({ path: '/smartReportList' });
                    }
                })
                return
            }

            const isPost = this.permissionBtn.checkPermissionBtn(this.permissionBtn.smartReportManageBtn.reportManage_sendMsg)

            this.$confirm(isPost?'是否发布定时报告，并推送模板消息？':'是否发布定时报告？', '发布提示', {
				confirmButtonText: isPost?'推送':'发布',
				cancelButtonText: isPost?'不推送':'取消',
				type: 'warning',
				distinguishCancelAndClose:true,
				beforeClose:(action, instance,done)=>{
					console.log(action, instance);
					if(action==='close'||action==='cancel') {
						//右上角或者不推送
						if(isPost){
							apiSmartReport.prePublishReport({
								SmartReportId:Number(this.$route.query.id),
								PrePublishTime:this.taskTime,
								PreMsgSend:0,
							}).then(res=>{
								if(res.Ret===200){
									this.$message.success('定时发布成功！')
									this.$router.replace({ path: '/smartReportList' });
								}
							})
						}
					} else {
						//confirmButton
						apiSmartReport.prePublishReport({
							SmartReportId:Number(this.$route.query.id),
							PrePublishTime:this.taskTime,
							PreMsgSend:isPost?1:0,
						}).then(res=>{
							if(res.Ret===200){
								this.$message.success('定时发布成功！')
								this.$router.replace({ path: '/smartReportList' });
							}
						})
					}
					done()
				}
			})
        },

        // 发布报告
        reportPublish({sendMsg}){
            apiSmartReport.publishReport({
                SmartReportId:Number(this.$route.query.id),
                PublishState:2
            }).then(res=>{
                if(res.Ret===200){
                    if(sendMsg){
                        this.reportSendMsg()
                    }
                    this.$router.replace({ path: '/smartReportList' });
                }
            })
        },

        //报告消息推送
        reportSendMsg(){
            apiSmartReport.reportMsgSend({SmartReportId:Number(this.$route.query.id)}).then(res=>{})
        }
    },
    created() {
        this.getPublicSettings()
        this.getReportDetail()
    },
    mounted () {
        window.addEventListener('message',this.setSheetIframeStyle)
        this.timer = setInterval(() => {
			this.handleSaveContent({isAutoSave:true});
		}, 6000);
    },
    destroyed() {
		window.removeEventListener('message',this.setSheetIframeStyle)
        if (this.timer) {
			clearInterval(this.timer);
		}
	},
}
</script>
<style lang='scss' scoped>
div{
    box-sizing: border-box;
}
// .sortable-ghost{
//     height: 5px !important;
//     background-color: #0052D9 !important;
//     overflow: hidden !important;
//     padding: 0 !important;
//     min-height: 0 !important;
//     border: none !important;
// }
.edit-smart-report-page{
    background: var(--unnamed, #F2F6FA);
    min-width: 100vw;
    min-height: 100vh;
    .top-action-wrap{
        position: sticky;
        top: 0px;
        background-color: #fff;
        box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.10);
        height: 60px;
        display: flex;
        justify-content: space-between;
        align-content: center;
        padding: 0 24px;
        .title{
            line-height: 60px;
            font-size: 16px;
        }
        .action-list{
            display: flex;
            align-items: center;
            .action-item{
                height: 36px;
                display: flex;
                align-items: center;
                border-right: 1px solid #C8CDD9;
                padding: 0 30px;
                font-size: 16px;
                cursor: pointer;
                img{
                    width: 16px;
                    height: 16px;
                    margin-right: 4px;
                    position: relative;
                    top: 2px;
                }
                &:last-child{
                    border-right: none;
                }
            }
        }
    }
    .main-wrap{
        display: flex;
        justify-content: center;
    }
}
.report-action-wrap{
    width: 800px;
    flex-shrink: 0;
    margin-left: 90px;
    margin-right: 60px;
    margin-top: 30px;
    position: relative;
    .report-comp-wrap{
            position: absolute;
            left: -62px;
            top: 72px;
            width: 40px;
            border: 1px solid var(--gary-gy-5-line, #C8CDD9);
            background: var(--gary-gy-white, #FFF);
            border-radius: 4px;
            overflow: hidden;
            .comp-item{
                cursor: move;
                height: 40px;
                display: flex;
                align-items: center;
                justify-content: center;
                border-bottom: 1px solid var(--gary-gy-5-line, #C8CDD9);
                &:last-child{
                    border-bottom: none;
                }
                img{
                    width: 16px;
                }
            }
    }
    .top-type-list{
        margin-bottom: 20px;
        display: flex;
        align-items: center;
        background-color: #fff;
        height: 50px;
        border-radius: 4px;
        border: 1px solid var(--gary-gy-5-line, #C8CDD9);
        .item{
            cursor: pointer;
            flex: auto;
            display: flex;
            align-items: center;
            justify-content: center;
            border-right: 1px solid #C8CDD9;
            font-size: 16px;
            &:last-child{
                border-right: none;
            }
            .icon{
                width: 20px;
                height: 20px;
                margin-right: 4px;
            }
        }
    }
    .report-content-box{
        border-radius: 4px;
        border: 1px solid var(--gary-gy-5-line, #C8CDD9);
        background: #FFF;
        padding: 20px 20px 20px 64px;
        height: calc(100vh - 180px);
        position: relative;
        overflow-y: auto;
        
    }
}



.main-wrap{
    .report-html-wrap{
        min-height: 100%;
        .report-drag-item-wrap{
            width: 100%;
            padding: 20px;
            min-height: 80px;
            border: 1px dashed #0052D9;
            position: relative;
            margin-bottom: 10px;
            &:hover{
                border-style: solid;
                .opt-btn-box{
                    display: block !important;
                }
                .resize-drag-box{
                    display: block;
                }
            }
            .opt-btn-box{
                position: absolute;
                left: -36px;
                padding-right: 8px;
                top: 0;
                .drag-btn::after{
                    content: '';
                    display: block;
                    width: 28px;
                    height: 28px;
                    background-image: url('~@/assets/img/smartReport/icon12.png');
                    background-size: cover;
                    cursor: pointer;
                }
                .del-btn::after{
                    content: '';
                    display: block;
                    width: 28px;
                    height: 28px;
                    background-image: url('~@/assets/img/smartReport/icon13.png');
                    background-size: cover;
                    cursor: pointer;
                }
            }
            .resize-drag-box{
                position: absolute;
                right: -4px;
                bottom: -4px;
                width: 8px;
                height: 8px;
                display: none;
                border: 1px solid #0052D9;
                cursor: n-resize;
            }
        }
        .report-drag-item-wrap_child-wrap{
            min-height: 30px;
        }
        .report-drag-item-wrap_child_content{
            min-height: 80px;
            border: 1px dashed #0052D9;
            flex: 1;
            position: relative;
            &:hover{
                border-style: solid;
                .opt-btn-box2{
                    display: block !important;
                }
                .resize-drag-box_lt,
                .resize-drag-box_lb,
                .resize-drag-box_rt,
                .resize-drag-box_rb{
                    display: block;
                }
            }
            .opt-btn-box2{
                position: absolute;
                right: -15px;
                top: 0;
                .drag-btn::after{
                    content: '';
                    display: block;
                    width: 28px;
                    height: 28px;
                    background-image: url('~@/assets/img/smartReport/icon12.png');
                    background-size: cover;
                    cursor: pointer;
                }
                .del-btn::after{
                    content: '';
                    display: block;
                    width: 28px;
                    height: 28px;
                    background-image: url('~@/assets/img/smartReport/icon13.png');
                    background-size: cover;
                    cursor: pointer;
                }
            }
            .resize-drag-box_lt,
            .resize-drag-box_lb,
            .resize-drag-box_rt,
            .resize-drag-box_rb{
                position: absolute;
                width: 8px;
                height: 8px;
                display: none;
                border: 1px solid #0052D9;
            }
            .resize-drag-box_lt{
                left: -4px;
                top: -4px;
                cursor: nw-resize;
            }
            .resize-drag-box_lb{
                left: -4px;
                bottom: -4px;
                cursor: ne-resize;
            }
            .resize-drag-box_rt{
                right: -4px;
                top: -4px;
                cursor: ne-resize;
            }
            .resize-drag-box_rb{
                right: -4px;
                bottom: -4px;
                cursor: nw-resize;
            }
        }
        .blue-bg{
            background: var(--brand-brand-1-light, #ECF2FE);
        }
    }
}

.main-wrap{
    .right-action-wrap{
        height: calc(100vh - 60px);
        overflow: hidden;
        flex: 1;
        position: relative;
        padding-top: 30px;
        padding-left: 75px;
        padding-right: 30px;
        padding-bottom: 30px;
        &::before{
            display: block;
            content: '';
            width: 1px;
            height: 100vh;
            background-color: #C8CDD9;
            position: absolute;
            left: 15px;
            top: 0;
        }
        .close-icon{
            width: 20px;
            height: 20px;
            border-radius: 4px;
            background: #FFF;
            box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.25);
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            position: absolute;
            left: 5px;
            top: 22px;
            img{
                width: 16px;
                height: 16px;
            }
        }
    }
}
</style>