<template>
  <kr-print-designer ref="printDesigner" :temp-value="value" :widget-options="widgets" @save="handleSave" />
</template>
<script>
// import { OutStockOptions, InStockOptions } from '../data/options'
const baseUrl = process.env.VUE_APP_BASE_API;
export default {
  data() {
    return {
      tenantId: '',
      printData: [],
      value: {
        title: 'demo',
        width: 750,
        height: 550,
        pageWidth: 750,
        pageHeight: 550,
        tempItems: [],
      },
      widgets: [],
    }
  },

  methods: {
    handleSave(data) {
      const obj = {
        id: data.id,
        tenantId: this.tenantId,
        type: data.type,
        title: data.title,
        width: data.width,
        height: data.height,
        pageWidth: data.pageWidth,
        pageHeight: data.pageHeight,
        tempItems: data.tempItems,
      }
      console.log(obj, 'handleSave')
      this.addNewModel(obj)
    },

    // 手动初始话模板数据
    initTemp() {
      this.$refs.printDesigner.initTemp(this.value, this.widgets)
    },

    addNewModel(data) {
      this.$axios.post(baseUrl + "/print/saveTemplates", data)
        .then(res => {
          console.log(res, 'res')
          if (res.data.code == 200) {
            this.$message.success("新增成功！")
            this.$router.back()
          } else {
            this.$message.error("新增失败！")
          }
        })
        .catch(err => {
          console.error(err);
          this.$message.error("新增失败！")
        });
    },

    getWidgets() {
      const url = baseUrl + "/print/printDatas?type=2"
      this.$axios.get(url)
        .then(res => {
          console.log(res, 'res')
          const arr = []
          res.data.data.forEach(item => {
            delete item.printComponents.defaultValue
            arr.push(item.printComponents)
          });
          this.widgets = arr
          console.log(this.widgets, 'this.widgets ')

          //传入值变化后，需要手动初始化模板数据，否则不会同步
          this.initTemp()
        })
        .catch(err => {
          console.error(err);
        });
    }
  },

  created() {
    this.printData = this.$route.query.printData
    this.tenantId = this.$route.query.tenantId
    try {
      this.value = this.printData
      this.getWidgets(this.value.type)
    } catch (err) {
      console.error(err)
    }
  },
}
</script>
