

<script>
import fabric from '../PictureEditor/js/fabric-adapter'
import tpl from './tpl/index'
import viewMixins from '@/views/components/PictureEditor/mixin/view/index'
import actionsMixins from '@/views/components/PictureEditor/mixin/actions/index'
import layerMixins from '@/views/components/PictureEditor/mixin/layer/index'
import colorMixins from '@/views/components/PictureEditor/mixin/color/index'
import editMixins from '@/views/components/PictureEditor/mixin/edit/index'
import { uploadBaseImg } from '@/apis/other'

const FIXED_CANVAS_WIDTH = 800
export default {
  name: 'marketingImageEditor',
  mixins: [ viewMixins,actionsMixins,layerMixins,colorMixins,editMixins],

  props: {
    data: {
      type: Array,
      default:()=>{
        return []
      }
    },
    index:{
      type: Number,
      default: 0
    },
    goods_text:{
      type: Array,
      default: ()=>{
        return []
      }
    },
    goods_images:{
      type: Array,
      default: ()=>{
        return []
      }
    },

  },
  beforeDestroy() {
    this.saveCanvasSnapshot()
    this.destroyCanvasInstance()
  },
  data() {
    return {
      disabled:false,

      fcanvas: null,
      fcanvasId: '',
      scale: 1,
      sceneTplImg:"",//生成的时候记录下来，用户重做


      canvasForm:{
        type:'add',
        width: FIXED_CANVAS_WIDTH,
        height: '1024',
        color:"#fff",
        bg_color:'#fff',
        visible:false,
      }

    }
  },
  template: tpl(),
  computed: {
    isEmpty(){
      return this.data.length === 0
    },
    this_canvas(){
      return this.data[this.index]
    }
  },
  watch: {
    index(newValue, oldValue) {
      if (this.isEmpty) return
      this.saveCanvasSnapshot(oldValue)
      this.$nextTick(() => {
        this.init()
      })
    }
  },
  mounted() {
    this.init()
  },
  activated(){
  },
  deactivated() {
  },
  methods: {
    // 初始化
    async init() {


      //不存在数据
      if(this.isEmpty ){
        this.addCanvas()
        return;
      }


/*
      //画布下不存在模板OSS地址
      if(!this.this_canvas){
        this.$emit('update:index', 0)
        return;
      }


      if(this.this_canvas.tpl_url){
        return;
      }*/
      this.$emit('canvasStyle:update',{
        width: this.this_canvas.width,
        height: this.this_canvas.height
      })
      await this.viewInit()
      await  this.$nextTick()
      const canvasId = `marketing-canvas-${this.index}`
      const canvasEl = document.getElementById(canvasId)
      if (!canvasEl) return
      this.destroyCanvasInstance()
      this.fcanvas = new fabric.Canvas(canvasId, {
        backgroundColor: this.this_canvas.bg_color,
        containerClass:"fcanvas",
        // 元素对象被选中时保持在当前z轴，不会跳到最顶层
        preserveObjectStacking:true,
        width: this.this_canvas.width,
        height: this.this_canvas.height
      })
      this.fcanvasId = canvasId
      const hydrateCanvas = () => {
        this.updateCanvasState()
        // this.minimapInit()
        this.actionInit()
        this.layerInit();
        this.$nextTick(() => {
          this.$emit('init')
        })
      }
      if(this.this_canvas.canvas_json){
        const jsonData = typeof this.this_canvas.canvas_json === 'string'
          ? this.this_canvas.canvas_json
          : JSON.stringify(this.this_canvas.canvas_json)
        this.fcanvas.loadFromJSON(jsonData, () => {
          this.fcanvas.renderAll()
          hydrateCanvas()
        })
      }else{
        hydrateCanvas()
      }

    },
    addCanvas(){

      this.canvasForm.type = 'add'
      this.canvasForm.name = '画布_'+new Date().getTime().toString().substr(8)+Math.round(100)
      this.canvasForm.width = FIXED_CANVAS_WIDTH
      this.canvasForm.height = 1024
      this.canvasForm.bg_color = '#fff'
      this.canvasForm.visible = true;
    },
    handleAdjustCanvas() {
      if(!this.this_canvas) return;
      this.canvasForm.type = 'edit'
      this.canvasForm.name = this.this_canvas.name
      this.canvasForm.width = FIXED_CANVAS_WIDTH
      this.canvasForm.height = this.this_canvas.height
      this.canvasForm.bg_color = this.this_canvas.bg_color
      this.canvasForm.visible = true;
    },
    submitCanvasInfo() {
      // 假设 this.canvasForm 包含最新的 width, height 和 color

      if(this.canvasForm.type === 'add'){
        this.saveCanvasSnapshot()
        this.data.push({
               tpl_url:"",
               image_path:"",
               name:this.canvasForm.name,
               width:FIXED_CANVAS_WIDTH,
               height:this.canvasForm.height,
               bg_color:this.canvasForm.bg_color,
               canvas_json:'',
        })
        const nextIndex = this.data.length - 1
        this.$emit('update:index',nextIndex)
        if(nextIndex === this.index){
          this.$nextTick(() => {
            this.init()
          })
        }
/*        this.index = this.data.length - 1*/
        this.canvasForm.visible = false;
      }else{

        if(!this.this_canvas){
          this.canvasForm.visible = false;
          return;
        }


        const newWidth = FIXED_CANVAS_WIDTH;
        const newHeight = this.canvasForm.height;
        const newColor = this.canvasForm.bg_color;

        // 更新 fcanvas 的宽度和高度
        if(this.fcanvas){
          if(newWidth !== this.this_canvas.width)this.fcanvas.setWidth(newWidth);
          if(newHeight !== this.this_canvas.height)this.fcanvas.setHeight(newHeight);
          if(newColor !== this.this_canvas.bg_color)this.fcanvas.setBackgroundColor(newColor);
          // 重新渲染以应用更改
          this.fcanvas.renderAll();
        }

        this.data[this.index].name = this.canvasForm.name
        this.data[this.index].width = FIXED_CANVAS_WIDTH
        this.data[this.index].height = this.canvasForm.height
        this.data[this.index].bg_color = this.canvasForm.bg_color
        this.canvasForm.visible = false;
      }


    },
    resizeCanvas(width, height) {
      // TODO: 实现具体的画布调整逻辑
      console.log('调整画布尺寸为:', width, 'x', height);
    },
    handleSelectCanvas(index){
      if(index === this.index) return
      this.saveCanvasSnapshot()
      this.$emit('update:index', index)
    },
    canvasBodyStyle(item){
      const height = Number(item?.height)
      if(!height || Number.isNaN(height)){
        return {
          minHeight: '200px'
        }
      }
      return {
        height: `${height}px`
      }
    },
    saveCanvasSnapshot(targetIndex){
      const snapshotIndex = typeof targetIndex === 'number' ? targetIndex : this.index
      if(!this.fcanvas || snapshotIndex === undefined || snapshotIndex === null) return
      const canvasData = this.data[snapshotIndex]
      if(!canvasData) return
      const json = JSON.stringify(this.fcanvas.toJSON(['name','sort','mtr','id','selectable','erasable','data-key','data-value']))
      if(Object.prototype.hasOwnProperty.call(canvasData, 'canvas_json')){
        canvasData.canvas_json = json
      }else{
        const updated = {
          ...canvasData,
          canvas_json: json
        }
        this.data.splice(snapshotIndex, 1, updated)
      }
    },
    destroyCanvasInstance(){
      if(!this.fcanvas) return
      try{
        this.fcanvas.dispose()
      }catch(err){
        console.warn('[marketingEdit] dispose canvas failed', err)
      }finally{
        this.fcanvas = null
        this.fcanvasId = ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/fcanvas.scss';
.picture-editor-wrap {
  position: absolute;
  left: 0;
  top:0;
  right: 0;
  bottom:0;
  background: #e6e6e6;
  overflow: auto;

  .picture-editor-wrap_canvas {
    position: relative;
    margin-top: 85px;
    box-sizing: border-box;
    .picture-editor-canvas {
      min-height: calc(100vh - 85px);
      display: flex;
      align-items: flex-start;
      justify-content: center;
    }

  }
  @import '../PictureEditor/mixin/actions/index.scss';
  @import '../PictureEditor/mixin/view/index.scss';
  @import '../PictureEditor/mixin/layer/index.scss';
  @import '../PictureEditor/mixin/color/index.scss';
  @import '../PictureEditor/mixin/edit/index.scss';
  @import './tpl/header.scss';


  .picture-editor-empty {
    top:0;
    height: 100%;
    background: #fff;
    z-index: 10;
  }

  .add-action-wrap {
    position: fixed;
    top:80px;
    overflow: auto;
    left: 0px;
    z-index: 10;
    bottom: 0;
    width: 210px;

    background:#fff;
    box-shadow: 0px 2px 4px 0px rgba(170,177,255,0.54);

    .icon {
      margin-right: 5px;
    }
    .icon-img {
      width: 30px;
      height: 30px;
      border-radius: 5px;
      margin-right: 10px;
    }

    .add-action_title {
      border-bottom: 1px solid #eee;
      background: #fafafa;
    }
    .active {
      .icon {
        border:1px solid $primary2;
      }
      .text {
        color: #000;
      }
    }
  }

}


.canvas-stack {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding-bottom: 40px;
}

.canvas-stack_item {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 6px 16px rgba(0,0,0,0.06);
  padding: 16px;
  box-sizing: border-box;
}

.canvas-stack_header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.canvas-stack_title {
  display: flex;
  gap: 12px;
  font-size: 16px;
  font-weight: 600;
}

.canvas-stack_title .size {
  font-size: 13px;
  color: #666;
}

.canvas-stack_body {
  background: #fff;
  border-radius: 6px;
  padding: 12px;
  box-sizing: border-box;
}

.canvas-stack_body canvas {
  display: block;
  margin: 0 auto;
}

.canvas-stack_placeholder {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  color: #888;
  font-size: 14px;
  text-align: center;
}

.canvas-stack_placeholder img {
  max-width: 100%;
  border-radius: 4px;
  margin-bottom: 8px;
}

.canvas-stack_empty {
  width: 100%;
  text-align: center;
  padding: 80px 0;
  color: #666;
}

.fixed-width-tip {
  line-height: 32px;
  color: #666;
}


</style>
