<template>
  <!-- 全屏设计器弹窗 -->
  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :fullscreen="true"
    :default-fullscreen="true"
    :close-on-click-modal="false"
    @closed="handleDialogClosed"
  >
    <div class="fonts" style="height: calc(100vh - 165px)">
      <Designer
        v-if="designerReady"
        ref="designerRef"
        :events="designerEvent"
        theme="winter"
        headerTitle="设计器"
        authKey="53616C7465645F5F286B418F99190EA3DC1F152B8B1B393ECD4C3D064C735A6A"
        :template="templateData"
        :headerNewMenu="headerNewMenu"
        :headerMenuList="headerMenuList"
        :showOption="showDesignerOption"
        :styleOption="styleOption"
        :plugins="plugins"
        :config="designerConfig"
        :providers="providers" 
        :providerMap="providerMap"
        @on-designed="onDesigned"
      >
        <template #header></template>
      </Designer>
      <div v-else class="loading-container">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>加载中...</span>
      </div>
    </div>
    <template #footer>
      <div class="designer-footer">
        <el-button type="default" @click="handlePreview">预览</el-button>
        <el-button @click="handleSave(0)" v-if="formData.designStatus != 2">暂存</el-button>
        <el-button type="primary" @click="handleSave(1)">完成设计</el-button>
      </div>
    </template>
  </Dialog>
  <!--打印预览组件-->
  <DialogPreview ref="dialogPreviewRef" :has-print-button="false" title="模板预览" />
</template>
<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElIcon } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { Dialog } from '@/components/Dialog'
import { Designer, Header } from '@sv-print/vue3'
import pluginTextAuto from '@sv-print/plugin-text-auto'
import pluginEleBwip from "@sv-print/plugin-ele-bwip-js";
import { hiprint } from 'sv-print'
import { fontStyleAdv } from './fontStyleAdv.js'
import fontStyle from './fontStyle.js';
import fontSize from './fontSize.js'
import lineHeight from './lineHeight.js'
import { fieldAdv } from './fieldAdv.js'
import templateJson from './testTemplate.json'
import { getTemplate, createTemplateDetails, createTemplate } from '@/api/print/template'
import DialogPreview from '@/components/PrintDesginer/dialogPreview.vue'
import { useFontStore } from '@/store/modules/font' 
import testProvider from './testProvider.js';

const providers = ref([testProvider({title: 'testModule'})]);
const providerMap = ref({
  container: '.hiprintEpContainer', // 容器 $('.hiprintEpContainer')
  value: 'testModule' // testProvider 中 addPrintElementTypes("testModule") 定义的值
});
const plugins = ref([
  pluginTextAuto({
    sizeList: [10, 9, 8, 7, 6, 5], // 适应最小字体选项
    maxIterations: 15, // 适应次数
    enablePrecision: true, // 启用精确适应
    precision: 0.5, // 适应精确step
    precisionCount: 10, // 适应精确次数
    lineHeightMode: 'auto', // 行高模式 auto | original | normal | unset
    overrideHidden: false, // 超出是否隐藏
    extendsCss: {
      // 扩展css
      'word-wrap': 'break-word' // 单词换行
    }
  }), // 插件参数
  pluginEleBwip({})
])
// const fontStore = useFontStore()
// const loadedFonts = computed(() => fontStore.getLoadedFonts || [])
// const initFontList = ref([
//   { title: '微软雅黑', value: 'Microsoft YaHei' },
//   { title: '苹方', value: 'PingFang SC' },
//   { title: '冬青黑体', value: 'Hiragino Sans GB' },
//   { title: '思源黑体', value: 'Noto Sans SC' },
//   { title: '黑体', value: 'SimHei' },
//   { title: 'Arial', value: 'Arial' }, // Arial，Noto Sans SC
//   { title: 'Helvetica', value: 'Helvetica' },
//   { title: '宋体', value: 'SimSun' },
//   { title: '新宋体', value: 'NSimSun' },
//   { title: '思源宋体', value: 'Noto Serif SC' },
//   { title: 'Times New Roman', value: 'Times New Roman' },
//   { title: 'Georgia', value: 'Georgia' },
//   { title: '楷体', value: 'KaiTi' },
//   { title: '隶书', value: 'LiSu' },
//   { title: 'Consolas', value: 'Consolas' },
//   { title: 'Monaco', value: 'Monaco' },
//   { title: 'Menlo', value: 'Menlo' }
// ])
// const fontList = computed(() => [...loadedFonts.value, ...initFontList.value])

const fontStyleList = [{
  fontStyle: 'normal',
  fontStyleName: '正常',
}, {
  fontStyle: 'italic',
  fontStyleName: '斜体',
}]
const designerConfig = ref({})
// 初始化字段配置
const initFieldConfig = (fieldList?: any[]) => {
  designerConfig.value = {
    optionItems: [
      fontStyleAdv({isInput: false, fontStyleList}), // 使用选择框，并传递字体字形列表
      fieldAdv({ isInput: false, fieldList }), // 使用选择框，并传递字段列表
      fontSize, // 字体大小
      lineHeight, // 行高
    ],
    // 文本元素
    text: {
      tabs: [
        {
          name: '基础'
        },
        // 当修改第二个 tabs 时,必须把他之前的 tabs 都列举出来.
        {
          name: '样式', options: [
            {
              name:'fontStyle',
              before: 'letterSpacing', // 自定义参数，插入在 letterSpacing字间距 之前
              hidden: false
            },
          ]
        },
      ],
    },
    longText: {
      tabs: [
        {
          name: '基础'
        },
        // 当修改第二个 tabs 时,必须把他之前的 tabs 都列举出来.
        {
          name: '样式', options: [
            {
              name:'fontStyle',
              before: 'letterSpacing', // 自定义参数，插入在 letterSpacing字间距 之前
              hidden: false
            },
          ]
        },
      ],
    }
  }
  hiprint.setConfig(designerConfig.value)
}

// 初始执行一次
// initFieldConfig()

interface Props {
  visible: boolean
  template: any
  designerTemplateColumns: any[]
  fontList: any[]
  title: string
}
const templateId = ref<number | undefined>()
const dialogPreviewRef = ref<any>(null)
const props = defineProps<Props>()
// 弹窗标题
const dialogTitle = ref(props.title)
const emit = defineEmits<{
  'update:visible': [visible: boolean]
  save: [data: any]
}>()

// 处理v-model双向绑定
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})
const saveTemplate = async (type: number, data: unknown) => {
  try {
    let newDataFlag = false
    if (!templateId.value) {
      // 没有模板标签，先调用保存模板接口，再调用保存设计接口
      const res = await createTemplate(formData.value)
      templateId.value = res
      formData.value.id = res
      newDataFlag = true
    }
    let saveObj = {
      ...formData.value,
      contentText: JSON.stringify(data),
      designStatus: 1
    }
    if (type == 1) {
      saveObj.designStatus = 2
      if (newDataFlag) {
        saveObj.status = 1
      }
    }
    await createTemplateDetails(saveObj)
    console.log('保存模板详情成功')
    ElMessage.success('保存成功')
    // if (type == 1) {
    //   emit('update:visible', false)
    //   emit('closed')
    // }
  } catch (error) {
    console.error('保存模板详情失败:', error)
    // ElMessage.error('保存失败');
  }
  emit('tableListRefresh')
}
const initPanels = [
    {
        "index": 0,
        "name": 1,
        "paperType": "自定义",
        "width": 120,
        "height": 100,
        "paperList": {
            "type": "自定义",
            "width": 120,
            "height": 100
        },
        "paperHeader": 0,
        "paperFooter": 839.0551181102363,
        "field": null,
        "fontFamily": "Arial",
        "paperNumberDisabled": true,
        "paperNumberContinue": true,
        "panelAngle": 0,
        "overPrintOptions": {
            "content": "",
            "opacity": 0.7,
            "type": 1
        },
        "watermarkOptions": {
            "content": "",
            "fillStyle": "rgba(184, 184, 184, 0.3)",
            "fontSize": "14px",
            "rotate": 25,
            "width": 200,
            "height": 200,
            "timestamp": false,
            "format": "YYYY-MM-DD HH:mm"
        },
        "panelLayoutOptions": {
            "layoutType": "column",
            "layoutRowGap": 0,
            "layoutColumnGap": 0
        },
        "printElements": [],
        "paperNumberLeft": 565,
        "paperNumberTop": 819
    }
]
const templateData = ref({
  template: {
    panels: initPanels
  },
  fontList: props.fontList
})
const designerRef = ref<InstanceType<typeof Designer>>()
const designerUtilsClass = ref<any>()
const formData = ref<any>({}) // 存储模板详情数据
const designerReady = ref(false) // 控制Designer组件是否显示
const headerNewMenu = ref(true)
const headerMenuList = ref([])
// const headerMenuList = ref([{
//   icon: "sv-save",
//   title: "暂存",
//   desc: "",
//   click: (util: any) => util.save(),
// }, {
//   icon: "sv-save",
//   title: "完成",
//   desc: "",
//   click: (util: any) => {
//     console.log('完成', util)
//     saveTemplate(1, util.printTemplate.lastJson)
//   },
// }]);
const designerEvent = ref({
  // 保存模板
  onSave: async (key: string, data: unknown) => {
    console.log('---------保存模板-------', data)
    await saveTemplate(0, data)
    return true // 返回 true 阻止冒泡
  },
  // 编辑模板
  onEdit: (data: unknown) => {
    console.log('编辑模板', data)
    return true // 返回 true 阻止冒泡
  },
  // 编辑打印数据
  onEditData: (data: unknown) => {
    console.log('编辑打印数据')
    return true // 返回 true 阻止冒泡
  },
  // 快捷键
  onKeyDownEvent: (e: KeyboardEvent, designerUtils: unknown) => {
    console.log('---------快捷键---------', designerUtils)
    return true // 返回 true 阻止冒泡
  }
})

const onDesigned = (e: any) => {
  console.log('onDesigned')
  console.log(e)
  const { hiprint, designerUtils } = e.detail
  hideSvTool()
  console.log(hiprint)
  console.log(designerUtils)
  console.log(designerUtils.printTemplate)
  nextTick(() => {
    setTimeout(() => {
      designerUtils.toolbar.setZoom(2); // 缩放默认200
      designerUtils.printTemplate.zoom(2); // 缩放默认200
      designerUtilsClass.value = designerUtils
    }, 1200)
  })
}
const showDesignerOption = ref({
  showHeader: false, // 是否显示 顶部 Header
  showToolbar: true, // 是否显示 工具栏 Toolbar
  showFooter: false, // 是否显示 底部 Footer
  // 即将废弃移除
  showPower: false // 是否显示 "powered by sv-print" 需要 authKey 支持
})
const styleOption = ref({
  panels: {
    // 多面板
    mode: 'left',
    style: 'left:calc(28%);top:100px;'
  },
  draggableEls: {
    // 可拖拽元素
    mode: 'default', // 拖拽模式: default(默认), top(上), bottom(下), left(左), right(右), fixed(固定)
    show: true, // 是否显示  默认: true
    html: '<i class="svicon sv-element"></i><span>拖拽元素</span>', // 缩放 左侧的 按钮/icon (一般不用)
    style: 'left:20px;top:95px;width:200px;height:calc(100% - 340px);' // 样式
  },
  options: {
    // 属性
    mode: 'default',
    html: '<i class="svicon sv-options"></i><span>属性</span>',
    style: 'right:0;top:95px;width:250px;'
  },
  pageStructure: {
    // 页面结构
    mode: 'default',
    show: false,
    html: '<i class="svicon sv-structure"></i><span>页面结构</span>',
    style: 'right:210px;top:95px;width:200px;'
  },
  locationExchange: {
    // 位置交换
    mode: 'default',
    show: false,
    html: '<i class="svicon sv-switch"></i><span>位置交换</span>',
    style: 'right:490px;top:95px;width:300px;height:400px'
  },
  miniMap: {
    // 小地图
    mode: 'default',
    html: '<i class="svicon sv-flow"></i><span>概览图</span>',
    style: 'left:20px;bottom:30px;width:240px;min-height:200px;height:200px'
  },
  editableTools: {
    // 编辑工具
    mode: 'top',
    style: 'left:280px;top:180px;'
  },
  zIndexTools: {
    // 层级工具
    mode: 'top',
    style: 'left:280px;top:300px;'
  },
  fontTools: {
    // 字体工具
    mode: 'top',
    style: 'left:280px;top:420px;'
  },
  zoomTools: {
    // 缩放工具
    mode: 'left',
    style: 'left:240px;top:100px;',
    show: false
  },
  rotateTools: {
    // 旋转工具
    mode: 'bottom',
    style: 'left:440px;top:180px;',
    show: false
  },
  history: {
    // 历史记录
    show: false
  }
})
const handleSave = (type: number) => {
  setTimeout(() => {
    console.log('handleSave', designerUtilsClass.value.printTemplate.lastJson)
    saveTemplate(type, designerUtilsClass.value.printTemplate.lastJson)
  }, 200)
  // ElMessage.success('设计器保存成功')
  // emit('update:visible', false)
  // emit('save', {})
}
const handleDialogClosed = () => {
  designerReady.value = false
  templateId.value = undefined
}
const getTemplateDetail = async (row: any) => {
  designerReady.value = false
  templateId.value = row.id
  formData.value = row
  dialogTitle.value = `模板设计器-${row.templateName}`
  if (row.id) {
    try {
      initFieldConfig(props.designerTemplateColumns)
      templateData.value.fontList = props.fontList
      console.log('字体:', props.fontList)
      const data = await getTemplate(row.id)
      formData.value = data
      templateData.value.template = JSON.parse(data.contentText || JSON.stringify({
        panels: initPanels
      }))
      templateData.value.template.panels[0].printElements.forEach((element: any) => {
        if (element.printElementType.type === 'text' || element.printElementType.type === 'longText') {
          element.options.styler = `function(value, options, target,templateData,paperNo,rootData){ return { wordBreak:'normal', whiteSpace:'normal' }; }`
        }
      })
      console.log('获取模板详情成功:', data)
      console.log('模板数据', templateData.value.template)
      // 等待字体加载完成
      await globalThis.document.fonts.ready
      // 你的 字体 什么时候 加载的， 在线字体，不是这个
      // 在线字体我还没加呢
      designerReady.value = true // 获取数据成功后显示Designer组件
      // 找到class名为sv-designer的元素
    } catch (error) {
      console.error('获取模板详情失败:', error)
      ElMessage.error('获取模板详情失败')
      designerReady.value = true // 即使失败也显示Designer组件，避免一直加载
      hideSvTool()
    }
  } else {
    initFieldConfig(props.designerTemplateColumns)
    templateData.value.template = {
      panels: initPanels
    }
    templateData.value.fontList = props.fontList
    console.log('字体:', props.fontList)
    // 等待字体加载完成
    await globalThis.document.fonts.ready
    designerReady.value = true
    hideSvTool()
  }
}
const hideSvTool = () => {
  const svToolEle = document.querySelector('.sv-tool')
  if (svToolEle) {
    svToolEle.style.display = 'none'
  }
}
const handleTemplateMockData = (template: any) => {
  const mockData = []
  if (!template.panels) {
    return mockData
  }
  template.panels.forEach((item: any) => {
    let obj = {}
    item.printElements.forEach((element: any) => {
      console.log('element', element)
      // obj[element.options.field] = element.options.testData
      const label = props.designerTemplateColumns.find((item: any) => item.fieldName === element.options.field)?.columnComment || element.options.field
      let val = element.options.field ? `{{${label}}}` : element.options.testData
      if (element.printElementType.type === 'barcode' || element.options.textType === 'barcode') {
        val = element.options.testData
      }
      obj[element.options.field] = val
    })
    mockData.push(obj)
  })
  console.log('------模板打印模拟数据-------', mockData)
  return mockData
}
// 预览
const handlePreview = () => {
  console.log('------模板数据-------', designerUtilsClass.value.printTemplate.lastJson)
  const templateJson = designerUtilsClass.value.printTemplate.lastJson
  const mockData = handleTemplateMockData(templateJson)
  dialogPreviewRef.value?.open({
    template: templateJson,
    printData: mockData
  })
}
// 监听designerTemplateColumns变化
// watch(
//   () => props.designerTemplateColumns,
//   (newColumns) => {
//     if (newColumns && newColumns.length > 0) {
//       initFieldConfig(newColumns)
//     }
//   },
//   { deep: true }
// )

// 暴露方法给父组件
defineExpose({
  getTemplateDetail
})
</script>

<style scoped>
/**.fonts {
  font-family: Arial, "Noto Sans SC";
}**/
.designer-footer {
  display: flex;
  justify-content: flex-end;
}

.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 16px;
  color: #606266;
}

.loading-container .is-loading {
  margin-right: 8px;
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
