import {checkClipboard,checkClipboardItems,getTextContentSize} from '../../utils/untils';
import {defaultPosition} from "../../utils/config";
import Ediotr from '../TextEditor.vue';
import BaseShape from '../layer/Element/BaseShape.vue';
import LineShape from "../layer/Element/LineShape.vue";
import TextShape from "../layer/Element/TextShape.vue";
import ChartEl from "../formatEl/ChartEl.vue";
import TextEl from "../formatEl/TextEl.vue";
import ImageEl from "../formatEl/ImageEl.vue";
import SheetEl from "../formatEl/SheetEl.vue";
export default {
    components: {
        Ediotr,BaseShape,LineShape,TextShape,ChartEl,TextEl,ImageEl,SheetEl
      },
    props: {
        pageIndex: {//当前是第几页
            type: Number,
            default: 0
        },
        pageItem: {//页数据
            type: Object,
            default: () => {
                return {
                    elements: [],
                };
            },
        },
        choosedId:{//当前选中的页面id
            type:Number
        },
        type: { //edit or show
            type: String,
            default: 'edit'
        },
        isCopy:{//是否显示复制按钮(复制图表名称)
          type:Boolean,
          default:false
        },
        isAdd:{//是否显示添加按钮(添加到我的图库)
          type:Boolean,
          default:false
        },
        isEditLayer:{//父组件是否是图层编辑模式
          type:Boolean,
          default:false
        },
        activeLayerEl:{//当前页面在图层编辑模式时,选中的图层元素
          type:Object,
        },
        isPreview:{//是否是缩略图模式
          type:Boolean,
          default:false
        },
        amendatoryPositionInfo:{//修正后的位置信息，版式内位置发生交换后有值
          type:Object,
          default:()=>{
            return {}
          }
        }
    },
    data() {
        return {
           isClickLayer:false,
           typeMap :{
            'chart':'ChartEl',
            'image':'ImageEl',
            'text':'TextEl',
            'sheet':'SheetEl'
          },
          dragElement:null,
        }
    },
    watch:{},
    computed:{
      TypeName(){
        return function(position){
          return this.getTypeName(position)
        }
      },
      RefName(){
        return function(position){
          return this.getRefName(position)
        }
      },
      Item(){
        return function(position){
          return this.getItem(position)
        }
      }
    },
    methods: {
        //判断当前活跃页该位置是否没有图表/文字,返回布尔值,
        isHintShow(position) {
            return this.pageItem.elements.find((item) => {
                    return item.position === position;
                }) ?
                false :
                true;
        },
        //判断遮罩layers是否显示
        isLayerShow(){
          //在图层编辑模式+是当前ppt+是编辑模式
          return this.isEditLayer&&this.type==='edit'&&this.choosedId===this.pageItem.id
        },
        //判断该渲染哪个图层组件
        getLayerElName(item){
          if(item.type==='shape'){
            return 'BaseShape'
          }
          if(item.type==='line'){
            return 'LineShape'
          }
          if(item.type==='text'){
            return 'TextShape'
          }
        },
        //切换当前选中的图层元素
        changeActEl(item){
          this.isClickLayer = false
          //如果该元素已被选中,则什么也不做
          const id = this.activeLayerEl.id
          if(id===item.id) return 
          this.$emit('changeActEl',item)
          $("#menu").hide()
        },
        //当layer被点击时
        clickLayer(e){
          //取消activeLayerEl的选中状态
          this.isClickLayer = true
          this.$emit('changeActEl',{})
          //取消layer-menu的显示
          $("#menu").hide()
        },
        //右键layer时
        showLayerContentMenu(e){
            if(!this.isLayerShow()) return 
            this.$emit('changeActEl',{})
            e.preventDefault()
            $("#menu").css({ "left": document.body.scrollLeft + e.clientX, "top": 
            document.body.scrollTop + e.clientY}).show();
        },
        //删除某个图层元素
        delLayer(item){
          this.$emit('delLayer',item)
        },
        //复制某个图层元素
        copyShape(item){
            this.$emit('copyShape',item)
        },
        //删除这张图表
        delChart(position) {
            this.$emit('delChart', position)
        },
        //自主黏贴事件:ctrl+v
        handlePaste(file,position){
            if(this.choosedId!==this.pageItem.id){
                return
            }
            let imgObj = {}
            if(this.isHintShow(position)){
                //该位置没有图片/图表
                let bolb = file
                const {msg,status} = checkClipboard(bolb)
                if(!status){
                    this.$message(msg);
                    return
                }
                let readder = new FileReader()
                readder.readAsDataURL(bolb);
                const that = this
                readder.onload = function (e) {
                    imgObj.src= e.target.result;
                    imgObj.position = position
                    that.$emit('pasteImg',imgObj)
                };

            }else{
                this.$message("已无位置,请删除现有图表/图片")
            }
        },
        getText({val,richContent}, position) {
            //console.log('text',val,'position',position)
            this.$emit('changeText', {
              position: position,
              text: val,
              richContent: richContent,
              pageItemId:this.pageItem.id
            })
        },
        initEditor(position){
            //初始化编辑器
            if(this.isHintShow(position)){
                this.getText({val:'',richContent:''},position)
                /* this.$nextTick(()=>{
                  this.$refs[`word_${this.pageIndex}_${position}`].getFocus()  
                }) */
            }
        },
        //获取富文本的值
        getRichContent(position){
            let richContent = ''
            this.pageItem.elements.map((i)=>{
                if(i.position===position){
                    richContent = i.richContent
                }
            })
            return richContent
        },
        //获取富文本区域在编辑页下的宽高
        getTextContentSize(model,position){
          return getTextContentSize(model,position)
        },
        //获取组件的refName
        getRefName(position){
          const el = this.positionInfo[position]
          return `${this.isPreview?'preview_':''}${el.type}_${this.pageIndex}_${position}`
        },
        //获取组件的typeName
        getTypeName(position){
          const el = this.positionInfo[position] 
          return this.typeMap[el.type]
        },
        getItem(position){
          return this.pageItem.elements.find(i=>i.position===position)
        },
        //初始化版式位置信息
        initPositionInfo(){
          let temp = {}
          this.pageItem.elements.map(i=>{
            temp[i.position] = {type:i.type}
          })
          this.positionInfo = {...defaultPosition[this.modelId],...this.amendatoryPositionInfo,...temp}
        },
        //拖拽开始
        onDragStart(e){
          const position = Number(e.currentTarget.dataset['position'])
          const dragInfo = this.positionInfo[position]
          /* if(this.isHintShow(position)){
            e.dataTransfer.effectAllowed = 'none'
            return
          } */
          if(this.choosedId!==this.pageItem.id) return
          this.dragElement = e.currentTarget
          if(dragInfo.type!=='text'){
            //设置拖拽反馈图像
            let img = new Image(); 
            img.src = require(`@/assets/img/ppt_m/format-pic.png`)
            e.dataTransfer.setDragImage(img, 10, 10);
          }
        },
        onDragOver(e){
          e.preventDefault()
        },
        //拖拽结束:交换drag和drop的position
        onDrop(e){
          let dropElement = e.currentTarget
          let dragElement = this.dragElement
          if (dragElement != null && dragElement != dropElement) {
            //获取drag和drop的position
            const dragPosition = Number(dragElement.dataset['position'])
            const dropPosition = Number(dropElement.dataset['position'])
            let dragIndex = this.pageItem.elements.findIndex(i=>i.position===dragPosition)
            let dropIndex = this.pageItem.elements.findIndex(i=>i.position===dropPosition)
            //console.log('dragIndex',dragIndex,'dropIndex',dropIndex)
            if(dragIndex!==-1)this.pageItem.elements[dragIndex].position = dropPosition
            if(dropIndex!==-1)this.pageItem.elements[dropIndex].position = dragPosition
            //同时需要更新positionInfo
            const dragPosInfo = this.positionInfo[dragPosition]
            const dropPosInfo = this.positionInfo[dropPosition]
            this.positionInfo[dragPosition] = {type:dropPosInfo.type}
            this.positionInfo[dropPosition] = {type:dragPosInfo.type}
            //需要重新加载该页
            this.$emit('reload',{id:this.pageItem.id,positionInfo:this.positionInfo})
          }
         },
        //检查该位置图表是否被删除
        checkCopy(position){
          const {chartId} = this.pageItem.elements.find(i=>i.position===position)
          const optionMap = this.$parent.optionMap
          return this.isCopy&&optionMap[chartId] instanceof Object
        },
        //复制图表名称
        async copyChartName(position){
          if(!this.checkCopy(position)) return 
          const {chartId} = this.pageItem.elements.find(i=>i.position===position)
          const chartTitle = this.$store.state.ppt.chartInfoMap[chartId].chartTitle
          console.log('chart_title',chartTitle)
          try{
            await navigator.clipboard.writeText(chartTitle)
            this.$message.success('复制成功')
          }catch(err){
            this.$message.error('复制失败')
          }
        },
        addChart(position){
          const {chartId} = this.pageItem.elements.find(i=>i.position===position)
          /* const chartInfo = this.$store.state.ppt.chartInfoMap[chartId] */
          this.$emit('addChart',chartId)
        }
    },
    mounted(){
      this.initPositionInfo()
    }
};