

<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, updateTemplateColumn } from '@/apis/other'
import {markRaw} from "vue";
import { ElMessage } from 'element-plus'
import useClientStore from '@/stores/modules/client'
import icpList from '@/utils/ipc'
import goods from './goods.json'
import goods1 from './goods1.json'
import goods2 from './goods2.json'
import goods4 from './goods4.json'
import goods5 from './goods5.json'
import canvas from './canvas.json'
import canvas1 from './canvas1.json'
import { buildRenderPlans, normalizeGoods } from './generateImagesPlan'
import { renderImagesByPlans, generateAllStyleImageBundles } from './generateImagesRender'

const FIXED_CANVAS_WIDTH = 395
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()
    this.destroyKeyboardNavigation()
  },
  data() {
    return {
      disabled:false,

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

      hasLoadedTpl:false,

      canvasForm:{
        type:'add',
        width: FIXED_CANVAS_WIDTH,
        height: '1024',
        color:"#fff",
        bg_color:'#fff',
        visible:false,
        canvas_type: 'normal', // normal:普通画布 model:模特图 scene:场景图
        multi_goods_mode: '', // 多货号模式：''(默认单货号), 'single'(一个货号多角度), 'multiple'(多个货号同角度)
        max_goods_count: null, // 多货号模式下，最多可追加多少个货号
      },

      // 新增商品文字对话框
      addGoodsTextForm: {
        visible: false,
        key: '',
        value: ''
      }

    }
  },
  template: tpl(),
  computed: {
    isEmpty(){
      return this.data.length === 0
    },
    this_canvas(){
      return this.data[this.index]
    }
  },
  watch: {
    data: {
      handler(newData, oldData) {
        // 当data从空数组变为有数据时（编辑模式加载数据），需要重新初始化
        // 避免在组件初始挂载时重复初始化
        if (oldData && oldData.length === 0 && newData && newData.length > 0 && this.fcanvas) {
          this.saveCanvasSnapshot()
          this.destroyCanvasInstance()
          this.$nextTick(() => {
            this.init()
          })
        }
      },
      deep: true
    },
    index(newValue, oldValue) {
      if (this.isEmpty) return
      const redirectIndex = this.findEditableCanvas(newValue)
      const target = this.data[newValue]
      // 模特图/场景图不进入编辑，自动跳到下一个普通画布
      if(
        target &&
        (target.canvas_type === 'model' || target.canvas_type === 'scene')
      ){
        // 如果没有可切换的普通画布，保持当前索引，避免递归更新
        if(redirectIndex !== -1 && redirectIndex !== newValue){
          this.$emit('update:index', redirectIndex)
        }
        return
      }
      this.saveCanvasSnapshot(oldValue)
      this.destroyCanvasInstance()
      this.$nextTick(() => {
        this.init()
        this.scrollToCanvas(newValue)
      })
    }
  },
  mounted() {
    // 延迟初始化，等待父组件设置数据
    this.$nextTick(() => {
      if(this.$route?.name === 'editTpl'){
        this.loadTemplate()
      }
      this.init()
    })
  },
  activated(){
  },
  deactivated() {
  },
  methods: {
    loadTemplate(){
      if(this.hasLoadedTpl) return
      const tplData = JSON.parse(JSON.stringify(this.data)).map(item => ({
        canvas_type: item.canvas_type || 'normal',
        canvas_json: (item.canvas_type === 'model' || item.canvas_type === 'scene') ? (item.canvas_type) : (item.canvas_json || ''),
        ...item,
      }))
      this.data.splice(0, this.data.length, ...tplData)
      this.$emit('update:index', 0)
      this.hasLoadedTpl = true
    },
    // 加载模板后的初始化处理
    setTpl(){
      if(!this.fcanvas) return
      try {
        // 确保所有对象都是可选的，并且控件可见
        this.fcanvas.getObjects().forEach(obj => {
          // 确保对象可选中和可交互
          obj.set({
            selectable: true,
            evented: true
          })
          // 根据对象类型设置控件可见性（与原有逻辑保持一致）
          if(obj.type === 'image' || obj.type === 'textbox' || obj.type === 'group'){
            obj.setControlsVisibility({
              'mtr': false
            })
          }
          // 特殊对象处理（参考原有逻辑）
          if(obj.name === 'scene'){
            obj.set({
              selectable: false,
              delable: false
            })
          }
          if(obj.name === 'subject'){
            obj.set({
              delable: false
            })
          }
        })
        // 确保画布尺寸正确
        if(this.this_canvas){
          this.fcanvas.setWidth(this.this_canvas.width)
          this.fcanvas.setHeight(this.this_canvas.height)
        }
        // 更新图层列表
        this.getLayers()
        // 恢复选中状态
        this.undoAfterSelectLayers()
        this.fcanvas.renderAll()
      } catch (e) {
        console.warn('[marketingEdit] setTpl failed', e)
      }
    },
    // 初始化
    async init() {


      //不存在数据（新建场景）
      if(this.isEmpty ){
        this.addCanvas()
        return;
      }

      // 模特图/场景图不初始化 fabric，直接跳过
      const canvasType = this.this_canvas?.canvas_type || 'normal'
      if (canvasType === 'model' || canvasType === 'scene') {
        const redirectIndex = this.findEditableCanvas(this.index)
        if(redirectIndex !== -1 && redirectIndex !== this.index){
          this.$emit('update:index', redirectIndex)
        }
        // 模特/场景图不需要 fabric，保持占位
        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 = markRaw(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, () => {
          // 如果是加载模板，调用专门的初始化函数
          if(this.hasLoadedTpl){
            this.setTpl()
          }
          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.canvas_type = 'normal'
      this.canvasForm.multi_goods_mode = ''
      this.canvasForm.max_goods_count = null
      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.canvas_type = this.this_canvas.canvas_type || 'normal'
      this.canvasForm.multi_goods_mode = this.this_canvas.multi_goods_mode || ''
      this.canvasForm.max_goods_count = this.this_canvas.max_goods_count || null
      this.canvasForm.visible = true;
    },
    handleCanvasTypeChange(type){
      if(this.canvasForm.type !== 'add') return
      if(type === 'model'){
        this.canvasForm.name = '模特图'
      }else if(type === 'scene'){
        this.canvasForm.name = '场景图'
      }else if(!this.canvasForm.name || this.canvasForm.name === '模特图' || this.canvasForm.name === '场景图'){
        this.canvasForm.name = '画布_'+new Date().getTime().toString().substr(8)+Math.round(100)
      }
    },
    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_type: this.canvasForm.canvas_type || 'normal',
               canvas_json: (this.canvasForm.canvas_type === 'model' || this.canvasForm.canvas_type === 'scene') ? this.canvasForm.canvas_type : '',
               preview:'',
               multi_goods_mode: this.canvasForm.multi_goods_mode || '',
               max_goods_count: this.canvasForm.multi_goods_mode ? (this.canvasForm.max_goods_count || null) : null,
        })
        const nextIndex = this.data.length - 1
        this.$emit('update:index',nextIndex)
        if(nextIndex === this.index){
          this.$nextTick(() => {
            this.init()
            // 新增画布后也需要滚动
            this.scrollToCanvas(nextIndex)
          })
        }
/*        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 = Number(this.canvasForm.height) || this.this_canvas.height;
        const oldHeight = Number(this.this_canvas.height) || 0;
        const newColor = this.canvasForm.bg_color;

        // 更新 fcanvas 的宽度和高度
        if(this.fcanvas){
          // 更新画布尺寸
          // 注意：Fabric.js 中对象的坐标是相对于画布左上角的，所以当画布高度变化时
          // 对象的 top 值会自动保持相对于顶部的距离不变，实现从底部扩展/收缩的效果


          if(newWidth !== this.this_canvas.width || newHeight !== oldHeight){
            this.fcanvas.setDimensions({ width: newWidth, height: newHeight });
          }
         /* if(newHeight !== oldHeight){
            this.fcanvas.setHeight(newHeight);
            // 高度变小：检查是否有对象超出新高度
            if(newHeight < oldHeight){
              const objects = this.fcanvas.getObjects();
              const outOfBounds = objects.filter(obj => {
                const objBottom = obj.top + (obj.height * obj.scaleY || 0);
                return objBottom > newHeight;
              });
              if(outOfBounds.length > 0){
                this.$message.warning(`有 ${outOfBounds.length} 个对象超出新画布高度，请手动调整位置`);
              }
            }
          }*/
          if(newColor !== this.this_canvas.bg_color)this.fcanvas.setBackgroundColor(newColor);
          let objects = this.fcanvas.getObjects();

          objects.forEach(function(object) {
            // 调整对象的位置
            object.left = object.left;
            object.top = object.top ;
            object.controls = fabric.Object.prototype.controls

          });

          // 重新渲染以应用更改
          this.fcanvas.requestRenderAll();
        }

        this.data[this.index].name = this.canvasForm.name
        this.data[this.index].width = FIXED_CANVAS_WIDTH
        this.data[this.index].height = newHeight
        this.data[this.index].bg_color = this.canvasForm.bg_color
        this.data[this.index].canvas_type = this.canvasForm.canvas_type || 'normal'
        this.data[this.index].multi_goods_mode = this.canvasForm.multi_goods_mode || ''
        this.data[this.index].max_goods_count = this.canvasForm.multi_goods_mode ? (this.canvasForm.max_goods_count || null) : null
        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)
    },
    handleDeleteCanvas(targetIndex){
      if(this.data.length <= 1){
        this.$message.warning('至少需要保留一个画布')
        return
      }
      // 如果删除的是当前激活的画布，需要先保存快照并销毁实例
      if(targetIndex === this.index){
        this.saveCanvasSnapshot()
        this.destroyCanvasInstance()
      }
      // 从数组中移除画布
      this.data.splice(targetIndex, 1)
      // 计算新的激活索引
      let newIndex = this.index
      if(targetIndex < this.index){
        // 删除的画布在当前画布之前，索引减1
        newIndex = this.index - 1
      } else if(targetIndex === this.index){
        // 删除的是当前画布，切换到前一个（如果存在），否则切换到第一个
        newIndex = targetIndex > 0 ? targetIndex - 1 : 0
      }
      // 确保索引不超出范围
      if(newIndex >= this.data.length){
        newIndex = this.data.length - 1
      }
      if(newIndex < 0){
        newIndex = 0
      }
      // 更新激活索引
      this.$emit('update:index', newIndex)
      // 如果删除的是当前画布，需要重新初始化
      if(targetIndex === this.index){
        this.$nextTick(() => {
          this.init()
        })
      }
      this.$message.success('画布已删除')
    },
    scrollToCanvas(idx){
      // 使用重试机制，确保 DOM 已渲染
      const tryScroll = (attempt = 0) => {
        if (attempt > 10) return // 最多重试10次

        // 增加延迟，确保 DOM 完全渲染
        setTimeout(() => {
          this.$nextTick(() => {
            // 获取滚动容器
            const scrollContainer = this.$refs.wrap
            if (!scrollContainer) {
              if (attempt < 10) {
                setTimeout(() => tryScroll(attempt + 1), 100 * (attempt + 1))
              }
              return
            }

            const ref = this.$refs[`canvasItem-${idx}`]
            const el = Array.isArray(ref) ? ref[0] : ref
            const target = el || document.getElementById(`marketing-canvas-${idx}`)?.closest('.canvas-stack_item')

            if (target && scrollContainer) {
              // 计算目标元素相对于滚动容器的位置
              const containerRect = scrollContainer.getBoundingClientRect()
              const targetRect = target.getBoundingClientRect()

              // 计算需要滚动的距离（目标元素顶部 - 容器顶部 - 导航栏高度100px）
              const scrollTop = scrollContainer.scrollTop
              const targetPosition = scrollTop + (targetRect.top - containerRect.top) - 100

              // 在滚动容器上平滑滚动
              scrollContainer.scrollTo({
                top: Math.max(0, targetPosition), // 确保不为负数
                behavior: 'smooth'
              })
            } else if (attempt < 10) {
              // 如果元素还没准备好，延迟重试
              setTimeout(() => tryScroll(attempt + 1), 100 * (attempt + 1))
            }
          })
        }, attempt * 50) // 每次尝试增加延迟
      }

      // 使用 requestAnimationFrame 确保在下一帧执行
      requestAnimationFrame(() => {
        tryScroll(0)
      })
    },
    canvasBodyStyle(item){
      const canvasType = item?.canvas_type || 'normal'
      // 模特图 / 场景图：保持方形显示
      if(canvasType === 'model' || canvasType === 'scene'){
        return {
          width: `${FIXED_CANVAS_WIDTH}px`,
          height: `${FIXED_CANVAS_WIDTH}px`,
          lineHeight: `${FIXED_CANVAS_WIDTH}px`,
          margin: '0 auto'
        }
      }
      // 普通画布
      const height = Number(item?.height)
      const width = Number(item?.width) || FIXED_CANVAS_WIDTH
      const style = {
        width: `${width}px`,
        margin: '0 auto'
      }
      if(!height || Number.isNaN(height)){
        style.minHeight = '200px'
      }else{
        style.height = `${height}px`
      }
      return style
    },
    handleBack(){
      if(this.$router && typeof this.$router.back === 'function'){
        this.$router.back()
      }else{
        this.$emit('back')
      }
    },
    async handleSave(){
      // 先确保当前激活画布的快照是最新的
      this.saveCanvasSnapshot()
      // 上传每个画布的预览图，生成线上地址
      console.log('this.data' , this.data)
      const payload = await Promise.all(this.data.map(async (item, idx) => {
        let previewUrl = item.preview || ''
        if(item.preview && typeof item.preview === 'string' && item.preview.indexOf('data:') === 0){
          try{
            const res = await uploadBaseImg({ image: item.preview })
            previewUrl = res?.data?.url || res?.url || previewUrl
          }catch (e){
            console.warn('[marketingEdit] upload preview failed', e)
          }
        }
        return {
          index: idx,
          preview: previewUrl,
          canvas_json: item.canvas_json || '',
          width: item.width,
          height: item.height,
          bg_color: item.bg_color,
          name: item.name || '',
          tpl_url: item.tpl_url || '',
          image_path: item.image_path || '',
          canvas_type: item.canvas_type || 'normal',
          multi_goods_mode: item.multi_goods_mode || '',
          max_goods_count: item.max_goods_count || null,
        }
      }))
      this.$emit('save', payload)
      return payload;
    },
    async createImg(){
       // 1. 组装数据源（后续可以从接口/其他页面传入）
       const goodsData = [
        JSON.parse(JSON.stringify(goods)),
        // JSON.parse(JSON.stringify(goods1)),
        // JSON.parse(JSON.stringify(goods2)),
        JSON.parse(JSON.stringify(goods4)),
        JSON.parse(JSON.stringify(goods5))
      ]

       const canvasJson = JSON.parse(JSON.stringify(canvas1))

       // 2. 针对每个款号，生成所有画布图片 + 组合长图（在内存中生成 dataURL）
       const bundles = await generateAllStyleImageBundles(canvasJson, goodsData)
       if (!bundles || !bundles.length) {
         ElMessage.warning('没有可生成的图片')
         return { bundles: [] }
       }

       // 3. 如果在 Electron 客户端中，直接通过 IPC 把图片写入 EXE 同级的 output 目录
       const clientStore = useClientStore()
       if (clientStore?.ipc && clientStore.isClient) {
         try {
           const result = await clientStore.ipc.invoke(icpList.utils.saveGeneratedImages, { bundles })
           if (result?.code === 0) {
             ElMessage.success(`生成完成，已保存到 output 文件夹（共 ${result.data?.fileCount || 0} 张）`)
           } else {
             ElMessage.error(result?.msg || '保存生成图片失败')
           }
         } catch (e) {
           console.error('[marketingEdit] saveGeneratedImages ipc error', e)
           ElMessage.error('保存生成图片失败')
         }
       } else {
         console.log('[marketingEdit] bundles (非客户端环境，仅返回数据)', bundles)
       }

       return { bundles }
    },
    saveCanvasSnapshot(targetIndex){
      const snapshotIndex = typeof targetIndex === 'number' ? targetIndex : this.index
      if(snapshotIndex === undefined || snapshotIndex === null) return
      const canvasData = this.data[snapshotIndex]
      if(!canvasData) return

      // 模特图 / 场景图：不生成 JSON，只保存类型占位，预览留空
      if(canvasData.canvas_type === 'model' || canvasData.canvas_type === 'scene'){
        this.data[snapshotIndex] = {
          ...canvasData,
          canvas_json: canvasData.canvas_type,
          preview: ''
        }
        return
      }

      if(!this.fcanvas) return
      const json = JSON.stringify(this.fcanvas.toJSON(['name','sort','mtr','id','selectable','erasable','data-key','data-type','data-value']))
      let preview = canvasData.preview || ''
      try{
        preview = this.fcanvas.toDataURL({
          format: 'png',
          multiplier: 1,
          enableRetinaScaling: true
        })
      }catch (err){
        console.warn('[marketingEdit] snapshot preview failed', err)
      }
      const updated = {
        ...canvasData,
        canvas_json: json,
        preview
      }
      this.data.splice(snapshotIndex, 1, updated)
    },
    // 打开大图预览（由模板 header 调用）
    openPreview(url) {
      this.previewImageUrl = url
      this.previewDialogVisible = true
    },
    handleMoveCanvas(idx, direction){
      const offset = direction === 'up' ? -1 : 1
      const targetIdx = idx + offset
      if(targetIdx < 0 || targetIdx >= this.data.length) return
      this.saveCanvasSnapshot()
      const currentCanvas = this.data[this.index]
      const [moved] = this.data.splice(idx, 1)
      this.data.splice(targetIdx, 0, moved)
      this.$nextTick(() => {
        const newIndex = this.data.indexOf(currentCanvas)
        if(newIndex !== -1 && newIndex !== this.index){
          this.$emit('update:index', newIndex)
        }else{
          this.reloadCurrentCanvas(false)
        }
        this.reloadAllNormalCanvases()
      })
    },
    reloadCurrentCanvas(scroll = true){
      if(this.isEmpty) return
      this.destroyCanvasInstance()
      const canvasType = this.this_canvas?.canvas_type || 'normal'
      if(canvasType === 'model' || canvasType === 'scene'){
        return
      }
      this.$nextTick(() => {
        this.init()
        if(scroll){
          this.scrollToCanvas(this.index)
        }
      })
    },
    reloadAllNormalCanvases(){
      // 简单策略：重新加载当前画布即可，避免重复显示；其他画布在切换时再加载
      this.reloadCurrentCanvas(false)
    },
    findEditableCanvas(startIndex = 0){
      if(this.isEmpty) return -1
      const total = this.data.length
      const isEditable = (item) =>
        item && item.canvas_type !== 'model' && item.canvas_type !== 'scene'

      for(let i = startIndex; i < total; i++){
        if(isEditable(this.data[i])) return i
      }
      for(let i = startIndex - 1; i >= 0; i--){
        if(isEditable(this.data[i])) return i
      }
      return -1
    },
    destroyCanvasInstance(){
      if(!this.fcanvas && !this.fcanvasId) return
      const canvasEl = this.fcanvas && this.fcanvas.getElement ? this.fcanvas.getElement() : document.getElementById(this.fcanvasId)
      const wrapper = canvasEl && canvasEl.parentNode && canvasEl.parentNode.classList?.contains('fcanvas')
        ? canvasEl.parentNode
        : null
      const parentNode = wrapper ? wrapper.parentNode : (canvasEl ? canvasEl.parentNode : null)
      const nextSibling = wrapper ? wrapper.nextSibling : (canvasEl ? canvasEl.nextSibling : null)
      try{
        this.fcanvas && this.fcanvas.dispose()
      }catch(err){
        console.warn('[marketingEdit] dispose canvas failed', err)
      }finally{
        // 安全移除 DOM，避免 NotFoundError
        if(wrapper && parentNode && parentNode.contains(wrapper)){
          parentNode.removeChild(wrapper)
        }else if(canvasEl && canvasEl.parentNode && canvasEl.parentNode.contains(canvasEl)){
          canvasEl.parentNode.removeChild(canvasEl)
        }
        // 仅当当前 id 对应的 canvas 不存在时，才补一个占位 canvas，避免重复
        if(parentNode && this.fcanvasId && !document.getElementById(this.fcanvasId)){
          const placeholder = document.createElement('canvas')
          placeholder.id = this.fcanvasId
          placeholder.width = Number(this.this_canvas?.width) || FIXED_CANVAS_WIDTH
          placeholder.height = Number(this.this_canvas?.height) || 0
          placeholder.style.width = '100%'
          placeholder.style.height = '100%'
          parentNode.insertBefore(placeholder, nextSibling || null)
        }
        this.fcanvas = null
        this.fcanvasId = ''
      }
    },

    // 显示新增商品文字对话框
    showAddGoodsTextDialog() {
      this.addGoodsTextForm.key = ''
      this.addGoodsTextForm.value = ''
      this.addGoodsTextForm.visible = true
    },

    // 确认新增商品文字
    async confirmAddGoodsText() {
      if (!this.addGoodsTextForm.key.trim() || !this.addGoodsTextForm.value.trim()) {
        this.$message.warning('请填写完整的商品文字信息')
        return
      }

      // 检查是否已存在相同的 key
      const existingIndex = this.goods_text.findIndex(item => item.key === this.addGoodsTextForm.key.trim())
      if (existingIndex !== -1) {
        this.$message.warning('该商品文字键名已存在，请使用不同的键名')
        return
      }

      try {
        // 获取模板ID（编辑模式下）
        const templateId = this.$route?.params?.id
        if (!templateId) {
          this.$message.error('无法获取模板ID，请刷新页面后重试')
          return
        }

        // 准备新的商品文字数组（包含新添加的）
        const newGoodsText = [
          ...this.goods_text,
          {
            key: this.addGoodsTextForm.key.trim(),
            value: this.addGoodsTextForm.value.trim()
          }
        ]

        // 调用接口更新商品文字字段
        const response = await updateTemplateColumn({
          id: templateId,
          template_excel_headers: newGoodsText
        })

        if (response.code === 0) {
          // 接口调用成功，更新本地数据
          this.goods_text.push({
            key: this.addGoodsTextForm.key.trim(),
            value: this.addGoodsTextForm.value.trim()
          })

          this.addGoodsTextForm.visible = false
          this.$message.success('商品文字添加成功')
        } else {
          this.$message.error(response.msg || '更新商品文字失败')
        }
      } catch (error) {
        console.error('更新商品文字失败:', error)
        this.$message.error('更新商品文字失败，请稍后重试')
      }
    }
  }
}
</script>

<style lang="scss" >
@import './tpl/header.scss';

</style>
<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';


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

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

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

    .icon {
      margin-right: 5px;
    }
    .icon-img {
      width: 50px;
      height: 50px;
      object-fit: contain;
      // 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: 0;
}

.canvas-stack_item {
  width: 100%;
  border-radius: 0;
  box-shadow: none;
  padding: 0;
  box-sizing: border-box;
  position: relative;
  border-bottom: 1px solid #f0f0f0;
}

.canvas-stack_body {
  background: transparent;
  border-radius: 0;
  padding: 0;
  box-sizing: border-box;
  position: relative;
  overflow: visible;
  transition: background 0.2s, box-shadow 0.2s, border 0.2s;
  &.inactive {
    ::v-deep {

      canvas {
        display: none;
      }
    }
  }
}

.canvas-stack_body.active {
  background: #f6fbff;
  box-shadow: 0 0 10px rgb(0 0 0 / 20%);
}

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

.canvas-stack_body .fcanvas {
  width: 100% !important;
  height: 100% !important;
}

.canvas-stack_body .upper-canvas,
.canvas-stack_body .lower-canvas {
  width: 100% !important;
  height: 100% !important;
}

.canvas-stack_controls {
  position: absolute;
  top: 10px;
  right: -30px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 6px;
  width: 30px;
}

.canvas-stack_switch {
  width: 100%;
  height: 60px;
  background: rgba(104, 188, 165, 0.1);
  border-color: rgba(104, 188, 165, 0.3);
  color: #68BCA5;
  white-space: break-spaces;
  padding: 5px !important;
  ::v-deep {
    span {
      display: block;
      width: 100%;
      height: 100%;
    }
  }
}

.canvas-stack_body.active .canvas-stack_switch {
  background: $primary1;
  border-color: $primary1;
  color: #fff;
}

.canvas-stack_sort {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.canvas-stack_sort .el-button {
  width: 100%;
  padding: 0;
  height: 28px;
  margin-left: 0px !important;
}

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

.canvas-stack_placeholder img {
  max-width: 100%;
  display: block;
}

.canvas-stack_empty {
  width: 100%;
  text-align: center;
  padding: 40px 0;
  color: #666;
  border-bottom: 1px solid #f0f0f0;
}

.goods-mode-samples {
  display: flex;
  gap: 12px;
  margin-top: 8px;
  padding-left: 100px; /* 与表单 label 宽度对齐 */
}
.goods-mode-samples .sample-row {
  display: flex;
  gap: 12px;
  justify-content: flex-end; /* 靠右对齐图片 */
}
.goods-mode-samples .sample-item {
  display: flex;
  flex-direction: column;
  align-items: flex-end; /* 让图片和 label 的右对齐 */
  width: 140px;
}
.goods-mode-samples .sample-item img,
.goods-mode-samples .sample-item .el-image__inner {
  width: 140px;
  height: 90px;
  object-fit: contain;
  border: 1px solid #eee;
  border-radius: 6px;
  background: #fff;
}
.goods-mode-samples .sample-label {
  margin-top: 6px;
  font-size: 12px;
  color: #666;
  text-align: right; /* 右对齐标签文本 */
}

.goods-mode-samples .sample-actions {
  align-self: flex-end;
  margin-bottom: 6px;
}

.goods-mode-samples .sample-row {
  display: flex;
  gap: 12px;
}
.goods-mode-samples .sample-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 140px;
}
.goods-mode-samples .sample-item img {
  width: 140px;
  height: 90px;
  object-fit: contain;
  border: 1px solid #eee;
  border-radius: 6px;
  background: #fff;
}
.goods-mode-samples .sample-label {
  margin-top: 6px;
  font-size: 12px;
  color: #666;
}

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

.add-goods-text-item {
  border-top: 1px solid #f0f0f0;
  margin-top: 8px;
  padding-top: 8px;

  &:hover {
    background-color: #f5f7fa;
  }

  .el-icon {
    margin-right: 6px;
  }

}


</style>




