<template>
    <!-- 图库框架 列表页 -->
    <div class="chart-frame-wrap">
        <!-- 控制目录栏展开收起-->
        <span class="slide-icon slide-right" @click="slideHandle" v-show="isSlideLeft">
            <i class="el-icon-d-arrow-right"></i>
        </span>
        <div class="catalog-wrap page-block-wrap" id="catalog-left" v-show="!isSlideLeft">
            <span class="slide-icon slide-left" @click="slideHandle">
                <i class="el-icon-d-arrow-left"></i>
            </span>
            <span class="move-btn resize" v-drag id="resize"></span>
            <div class="btn-wrap">
                <el-button type="primary" @click="$router.push('/addframe')" 
                v-permission="permissionBtn.chartFramePermission.chartframe_my_editFrame">添加框架</el-button>
            </div>
            <div class="search-wrap">
                <el-select style="width:100%"
                    filterable remote
                    placeholder="请输入框架名称"
                    v-model.trim="searchText"
                    :remote-method="searchHandle"
                    value-key="ChartFrameworkId"
                    clearable
                    >
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                    <el-option
                        v-for="item in searchOptions"
                        :key="item.ChartFrameworkId"
                        :label="item.FrameworkName"
                        :value="item"
                    />
                </el-select>
            </div>
            <div class="catalog-list">
                <div class="public-catalog">
                    <p>公共框架</p>
                    <div class="catalog-tree">
                        <el-tree
                            ref="catalogTree"
                            class="catalog-tree other-tree"
                            empty-text="暂无分类"
                            :data="publicFrameList"
                            node-key="nodeKeyId"
                            :expand-on-click-node="false"
                            @current-change="(data,node)=>{nodeChange(data,node)}"
                            >
                            <span class="custom-tree-node" slot-scope="{ data,node }"
                            >
                                <span class="tree-label">{{ data.name }}</span>
                            </span>
                        </el-tree>
                    </div>
                </div>
                <div class="my-list">
                    <p>我的框架</p>
                    <draggable
                        v-model="myFrameList"
                        class="classify-ul"
                        animation="300"
                        tag="ul"
                        :disabled="!permissionBtn.isShowBtn('chartFramePermission','chartframe_my_move')"
                        @start="menuDragStart"
                        @update="menuDragenter"
                        @end="menuDragOver"
                    >
                        <li class="classify-item" :class="{'active':currentFrame.ChartFrameworkId===item.ChartFrameworkId&&frameType==='my'}"
                            v-for="item in myFrameList" :key="item.ChartFrameworkId"
                            @click="chooseFrame(item)"
                            >
                            <span v-if="permissionBtn.isShowBtn('chartFramePermission','chartframe_my_move')">
                                <img src="~@/assets/img/data_m/move_ico.png"
                                    alt="" class="move"
                                    style="width: 14px; height: 14px;"
                                />
                            </span>
                            <span class="item-label text_oneLine">{{ item.FrameworkName }}</span>
                            <el-dropdown style="margin-right: 10px" @command="handleCommand" trigger="click"
                                v-if="permissionBtn.isShowBtn('chartFramePermission','chartframe_my_show')">
                                <span class="el-dropdown-link  el-dropdown-link-img">
                                    <img class="icon" src="~@/assets/img/chart_m/Group.png" v-if="item.IsPublic === 0">
                                    <img class="icon" src="~@/assets/img/chart_m/User.png" v-else>
                                </span>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item 
                                        :command="{key:'own',value:item}" 
                                        class="el-dropdown-menu-item-chat"
                                        >
                                        <div style="display: flex;align-items: center;">
                                            <img src="~@/assets/img/chart_m/Group.png">
                                            <span style="margin-left:5px">仅自己可见</span>
                                        </div>
                                    </el-dropdown-item>
                                    <el-dropdown-item 
                                        :command="{key:'public',value:item}" 
                                        class="el-dropdown-menu-item-chat"
                                        >
                                        <div style="display: flex;align-items: center;">
                                            <img src="~@/assets/img/chart_m/User.png">
                                            <span style="margin-left:5px">所有人可见</span>
                                        </div>
                                        
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                            <el-dropdown @command="handleCommand" trigger="click"
                                v-if="isDropDownShow"
                            >
                                <span class="el-dropdown-link"> 
                                    <i class="el-icon-more" style="font-size: 16px;transform: rotate(90deg);cursor: pointer"/>
                                </span>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item v-if="permissionBtn.isShowBtn('chartFramePermission','chartframe_my_rename')"
                                        :command="{key:'edit'}">重命名</el-dropdown-item>
                                    <el-dropdown-item v-if="permissionBtn.isShowBtn('chartFramePermission','chartframe_my_delFrame')"
                                        :command="{key:'del'}">删除</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                           
                        </li>
                    </draggable>
                </div>
            </div>
        </div>
        <div class="detail-wrap page-block-wrap" id="detail-right">
            <div class="empty" v-if="!currentFrame.ChartFrameworkId&&currentList.length===0">
                <tableNoData text="暂无数据"/>
            </div>
            <template v-else>
                <div class="list" v-if="model==='list'">
                    <div class="list-item" 
                        v-for="item in currentList" :key="item.nodeKeyId"
                        @click="nodeChange(item,{level:2})"
                        >
                        <div class="item-title text_oneLine">
                            <span>{{item.name}}</span>
                        </div>
                        <div style="height:1px;background:#ECECEC;margin:0 -10px;"></div>
                        <div class="item-image" 
                            :style="`background-image:url(${item.FrameworkImg?item.FrameworkImg:require('@/assets/img/document_m/default-img.png')})`"></div>
                        <div style="height:1px;background:#ECECEC;margin:10px -10px;"></div>
                        <div class="item-time">
                            创建时间:{{item.CreateTime}}
                        </div>
                    </div>
                    <div class="empty" v-if="currentList.length===0">
                        <tableNoData text="暂无数据"/>
                    </div>
                </div>
                <div class="detail" v-else>
                    <div class="top-info">
                        <span>更新时间:{{currentFrame.ModifyTime}}</span>
                        <span class="title text_oneLine">{{currentFrame.FrameworkName}}</span>
                        <div class="tool">
                            <el-button type="text" @click="handleOption('edit',currentFrame)" 
                                v-if="frameType==='my'&&permissionBtn.isShowBtn('chartFramePermission','chartframe_my_editFrame')">编辑</el-button>

                            <el-button type="text" @click="handleOption('copy',currentFrame)" :disabled="!currentFrame.FrameworkContent"
                                v-if="frameType==='my'&&permissionBtn.isShowBtn('chartFramePermission','chartframe_my_copyImg')">复制图片</el-button>
                            <el-button type="text" @click="handleOption('copy',currentFrame)" :disabled="!currentFrame.FrameworkContent"
                                v-if="frameType==='public'&&permissionBtn.isShowBtn('chartFramePermission','chartframe_public_copyImg')">复制图片</el-button>

                            <el-button type="text" @click="handleOption('del',currentFrame)" style="color:red;"
                                v-if="frameType==='my'&&permissionBtn.isShowBtn('chartFramePermission','chartframe_my_delFrame')">删除</el-button>
                        </div>
                    </div>
                    <div class="frame-wrap">
                        <!--沙盘图组件-->
                        <FrameContainer ref="container"
                            :FrameworkContent="currentFrame.FrameworkContent"
                            @showDialog="handleShowDialog"/>
                    </div>
                </div>
            </template>
        </div>
        <!-- 重命名弹窗 -->
        <el-dialog
            title="重命名框架"
            :visible.sync="isRenameDialogShow"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            @close="isRenameDialogShow=false"
            width="589px"
            v-dialogDrag
            center
        >
            <div class="dialog-container">
                <div>
                    <span style="margin-right:5px;">框架名称</span>
                    <el-input v-model.trim="modifyFrame.FrameworkName" placeholder="请输入框架名称"></el-input>
                </div>
            </div>
            <div class="dialog-footer">
                <el-button @click="isRenameDialogShow=false">取消</el-button>
                <el-button type="primary" @click="renameFrame">确定</el-button>
            </div>
        </el-dialog>
        <!-- my eta图表详情弹窗 -->
        <chartDetail 
            :isOpenDetail="myETADetailDialogShow"
            :select_classify="chartClassify"
            :chart_code="chartCode"
            :allChart="chartArr"
            :classifyUserId="classifyUserId"
            @close="myETADetailDialogShow=false"
            @remove="removeChart"
        />
        <!-- my eta图表复制到弹窗 -->
        <el-dialog
            title="复制到我的图库"
            :visible.sync="isCopyDialogShow"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            @close="isCopyDialogShow=false"
            width="589px"
            v-dialogDrag
            center
        >
            <div class="dialog-container" v-loading="copyDialogLoading">
                <div>
                    <span style="margin-right:5px;">复制到</span>
                    <el-select
                        v-model="copyToClassify"
                        placeholder="请选择目录"
                        style="width: 80%;"
                        multiple clearable
                    >
                        <el-option v-for="item in myETAClassArr"
                            :key="item.value"
                            :label="item.name"
                            :value="item.value"
                        />
                    </el-select>
                </div>
            </div>
            <div class="dialog-footer">
                <el-button @click="isCopyDialogShow=false">取消</el-button>
                <el-button type="primary" @click="copyToClass">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import draggable from 'vuedraggable';
import FrameContainer from './components/frameContainer.vue';
import chartDetail from '@/views/mychart_manage/components/chartDetailDia.vue';
import { mychartInterface,chartFrameInterface } from '@/api/api.js';
import {copyBlob} from '@/utils/svgToblob.js';
export default {
    components:{ draggable, FrameContainer,chartDetail},
    directives: {//自定义指令调整目录栏宽度
        drag(el, bindings) {
            el.onmousedown = function (e) {
                let init = e.clientX;
                let left = $('#catalog-left')[0];
                let initWidth = left.offsetWidth;
                document.onmousemove = function (e) {
                let end = e.clientX;
                let newWidth = end - init + initWidth;
                left.style.width = newWidth+'px';
                //reloadFrame()
                };
                document.onmouseup = function () {
                document.onmousemove = document.onmouseup = null;
                e.releaseCapture && e.releaseCapture();
                };
                e.setCapture && e.setCapture();
                return false;
            };
        },
    },
    data() {
        return {
            isSlideLeft:false,//控制左侧目录栏是否显示

            /* drag 我的框架相关 */
            dragStartIndex:0,
            dragFrame:null,
            prevFrame:null,
            nextFrame:null,

            /* search */
            searchText:'',
            searchOptions:[],
            
            /* select frame*/
            model:'frame',
            frameType:'my',
            publicFrameList:[],//公共框架列表
            currentList:[],//选择公共框架时,框架列表
            myFrameList:[],//我的框架列表
            currentFrame:{},//选择的框架
            /* frame node */
            myETADetailDialogShow:false,//点击节点时,弹出myeta图表详情弹框
            modifyFrame:{},//正在修改的框架
            isRenameDialogShow:false,//重命名弹窗
            /*my eta 图表详情操作相关 */
            chartClassify:0,
            classifyUserId:0,
            chartCode:'',
            chartArr:[],
            isCopyDialogShow:false,
            myETAClassArr:[],
            copyToClassify:[],
            modeId:0,
            /* 页面loading */
            lockLoding:null,
        };
    },
    watch:{
        searchText(newVal){
            newVal&&this.chooseFrame(newVal)
        }
    },
    computed:{
        adminId(){
            return Number(localStorage.getItem('AdminId'))
        },
        isDropDownShow(){
            return this.permissionBtn.isShowBtn('chartFramePermission','chartframe_my_rename')
                || this.permissionBtn.isShowBtn('chartFramePermission','chartframe_my_delFrame')
        }
    },
    methods: {
        slideHandle(){
            this.isSlideLeft = !this.isSlideLeft;
        },
        getPublicList(){
            chartFrameInterface.getPublicFrameList().then(res=>{
                if(res.Ret!==200) return 
                this.publicFrameList = res.Data||[]
                this.publicFrameList = this.publicFrameList.map(list=>{
                    list.name = list.MenuName
                    list.nodeKeyId = 'list'+list.AdminId
                    if(list.Frameworks){
                        list.children = list.Frameworks.map(item=>{
                            return {
                                ...item,
                                ...{
                                    nodeKeyId:'item'+item.ChartFrameworkId,
                                    name:item.FrameworkName
                                }
                            }
                        })
                    }
                    return list
                })
            })
        },
        async getMyList(type){
            const res = await chartFrameInterface.getMyFrameList({AdminId:this.adminId})
            if(res.Ret!==200) return 
            this.myFrameList = res.Data||[]
            if(type!=='init') return 
            //如果是其他页面跳转来的
            if(this.$route.query.frameId){
                this.currentFrame = this.myFrameList.find(i=>i.ChartFrameworkId===Number(this.$route.query.frameId))||{}
            }else{
                //否则选择myFrameList的第一个
                this.currentFrame = this.myFrameList[0]||{}
            }
            this.handleInitGraph()
        },
        searchHandle(keyword){
            chartFrameInterface.getMyFrameList({
                AdminId:this.adminId,
                Keyword:keyword,
            }).then(res=>{
                if(res.Ret!==200) return
                this.searchOptions = res.Data||[]
            })
        },
        nodeChange(data,node){
            this.frameType = 'public'
            this.changeModel(node.level===2?'frame':'list',data)
            this.$nextTick(()=>{
                this.$refs.catalogTree.setCurrentKey(data.nodeKeyId)
            })
        },
        changeModel(type,data){
            if(type==='frame'&&data.ChartFrameworkId===this.currentFrame.ChartFrameworkId) return 
            this.model = type
            //销毁画布
            this.$refs.container&&this.$refs.container.dispose()
            if(type==='frame'){
                this.currentFrame = data
                this.handleInitGraph()
            }else{
                this.currentList = data.children||[]
                this.currentFrame={}
            }
        },
        handleInitGraph(){
            //判断一下框架内容是否是合法的JSON,否则置为空
            try{
                JSON.parse(this.currentFrame.FrameworkContent)
            }catch(e){
                this.currentFrame.FrameworkContent = ''
            }
            this.$nextTick(()=>{
                //若框架有内容,才加载画布
                this.currentFrame.FrameworkContent&&this.$refs.container.init()
            })
        },
        /* 拖动相关 */
        menuDragStart({oldIndex}){
            this.dragStartIndex = oldIndex
            this.dragFrame = this.myFrameList[oldIndex]
        },
        menuDragenter({newIndex}){
            //置顶
            if(newIndex===0){
                this.prevFrame=null
                this.nextFrame=this.myFrameList[newIndex+1]
            }
            //置底
            if(newIndex===this.myFrameList.length-1){
                this.prevFrame = this.myFrameList[newIndex-1]
                this.nextFrame = null
            }
            if(newIndex!==0&&newIndex!==this.myFrameList.length-1){
                this.prevFrame = this.myFrameList[newIndex-1]
                this.nextFrame = this.myFrameList[newIndex+1]
            }
        },
        menuDragOver({newIndex}){
            if(newIndex===this.drageStartIndex) return
            if(!this.dragFrame) return
            chartFrameInterface.moveFrame({
                ChartFrameworkId:this.dragFrame.ChartFrameworkId,
                PrevChartFrameworkId:this.prevFrame?this.prevFrame.ChartFrameworkId:0,
                NextChartFrameworkId:this.nextFrame?this.nextFrame.ChartFrameworkId:0,
            }).then(res=>{
                if(res.Ret!==200) return 
                this.$message.success("移动成功")
                this.getMyList()
            })
        },
        /*下拉框 */
        handleCommand(command){
            if(command.key==='edit'){
                this.modifyFrame = _.cloneDeep(this.currentFrame)
                this.isRenameDialogShow = true
            }
            if(command.key==='del'){
                this.deleteFrame(this.currentFrame)
            }
            if(['own','public'].includes(command.key)){
                chartFrameInterface.changePublicFrame({
                    ChartFrameworkId:command.value.ChartFrameworkId,
                    IsPublic:command.key==='own'?0:1
                }).then(res=>{
                    if(res.Ret!==200) return
                    this.getPublicList()
                    this.getMyList()
                    this.$message.success(`操作成功`)
                })
            }
        },
        //选择我的框架
        chooseFrame(item){
            this.frameType = 'my'
            this.changeModel('frame',item)
            this.$nextTick(()=>{
                this.$refs.catalogTree.setCurrentKey(null)
            })
        },
        /* 框架操作相关 */
        handleOption(type,data){
            const optionMap = {
                'edit':this.handleEditFrame,
                'copy':this.copyFrameImg,
                'del':this.deleteFrame,
            }
            optionMap[type](data)
        },
        handleEditFrame(data){
            this.$router.push({path:'/editframe',query:{frameId:data.ChartFrameworkId}})
        },
        copyFrameImg(data){
            this.lockLoding = this.$loading({
                lock: true,
                text: '复制图片中...',
                target: '.frame-container-wrap',
                spinner: 'el-icon-loading',
                background: 'rgba(255, 255, 255, 0.8)'
            });
            const svgData = this.$refs.container.getContentPic()
            copyBlob(svgData,()=>{
                this.lockLoding && this.lockLoding.close();
            },1,'svg')
        },
        deleteFrame(data){
            this.$confirm("删除后不可恢复，确认删除吗？","提示",{
                confirmButtonText:"确定",
                cancelButtonText:"取消",
                type:"warning"
            }).then(()=>{
                chartFrameInterface.deleteFrame({
                    ChartFrameworkId:data.ChartFrameworkId
                }).then(res=>{
                    if(res.Ret!==200) return
                    this.$message.success("删除成功")
                    this.getPublicList()
                    this.getMyList()
                    this.currentFrame = {}
                })
            }).catch(()=>{})
        },
        renameFrame(){
            if(!this.modifyFrame.FrameworkName.length){
                this.$message.warning("请输入框架名称")
                return
            }
            chartFrameInterface.reNameFrame({
                ChartFrameworkId:this.modifyFrame.ChartFrameworkId,
                FrameworkName:this.modifyFrame.FrameworkName
            }).then(async res=>{
                if(res.Ret!==200) return
                this.getPublicList()
                await this.getMyList()
                this.currentFrame = this.myFrameList.find(item=>item.ChartFrameworkId===this.modifyFrame.ChartFrameworkId)||{}
                this.$message.success("编辑成功")
                this.isRenameDialogShow = false
            })
            
        },
        //点击框架内节点
        handleShowDialog({id,nodeLink}){
            //请求接口看有没有数据
            mychartInterface.myList({
                PageSize:1200,
                CurrentIndex:1,
                MyChartClassifyId: Number(id),
            }).then(res=>{
                if(res.Ret!==200) return 
                if(res.Data&&res.Data.List){
                    if(res.Data.List.length){
                        this.chartClassify = id
                        this.classifyUserId = nodeLink.AdminId||0
                        this.chartCode = res.Data.List[0].UniqueCode
                        this.chartArr = res.Data.List.map(item => item.UniqueCode)
                        this.myETADetailDialogShow = true
                    }
                }else{
                    this.$message.warning('该节点链接的图库没有图表')
                }
            })
        },
        //打开复制到弹窗
        async moveMychart(id) {
            this.isCopyDialogShow = true
            this.copyDialogLoading = true
            this.modeId = id
            //获取当前图表所属分类
            const { Data : chartClassifyList=[]} = await mychartInterface.getChartInClassify({ChartInfoId: id })
            //获取myETA全部分类
            const {Data} = await mychartInterface.classifyList()
            const classifyListData = Data?Data.List.map(item=>{
                return {...item,fromPublic: 0}
            }):[]
            //过滤掉所属分类
            this.myETAClassArr = classifyListData
                .map((item) => ({
                name: item.MyChartClassifyName,
                value: item.MyChartClassifyId,
                }))
                .filter((x) => !chartClassifyList.includes(x.value))
            this.copyDialogLoading = false
        },
        //将图表复制到其他目录
        copyToClass(){
            mychartInterface.copyMyChart({
                ChartInfoId: this.modeId,
                MyChartClassifyId: this.copyToClassify,
            })
            .then((res) => {
                if (res.Ret !== 200) return;
                this.$message.success('复制成功');
                this.isCopyDialogShow = false;
            });
        },
        //弹窗中移除了图表,对chartArr做对应改动
        removeChart(UniqueCode){
            this.chartArr.splice(this.chartArr.findIndex(item => item === UniqueCode), 1)
        }
    },
    mounted(){
        this.getPublicList()
        this.getMyList('init')
    }
};
</script>

<style lang="scss">
@import "./css/customTree.scss";
</style>
<style scoped lang="scss">
@import "./css/basePage.scss";
</style>
