<template>
  <el-dialog
    :visible.sync="visible"
    :title="$t('module.packingManage.LabelTemplate.DesignDetail')"
    width="40%"
    class="template-design-entry-dialog"
    :close-on-click-modal="false"
  >
    <div style="padding-left: 12px; padding-right: 12px;">
      <el-row :gutter="20" style="margin-bottom: 24px;">
        <el-col :span="12">
          <el-button type="primary" style="width: 100%;" @click="btnClickDesign">
            ① {{ $t('module.packingManage.LabelTemplate.TemplateDesign') }}
          </el-button>
        </el-col>
        <el-col :span="12">
          <el-button type="success" style="width: 100%;" @click="btnClickPrint">
            {{ $t('module.packingManage.LabelTemplate.TemplatePreview') }}
          </el-button>
        </el-col>

        <!-- <el-button icon="md-help" @click="btnClickInfo">
          设计说明
        </el-button> -->
      </el-row>

      <el-form ref="printModel" :model="printModel" :rules="rules" label-position="top">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="$t('module.packingManage.LabelTemplate.LabelCode')" prop="code">
              <el-input v-model="printModel.code" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('module.packingManage.LabelTemplate.LabelName')" prop="name">
              <el-input v-model="printModel.name" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('module.packingManage.LabelTemplate.LabelType')" prop="type">
              <el-select
                v-model="printModel.type"
                filterable
                clearable
                :placeholder="$t('module.packingManage.LabelTemplate.LabelType')"
              >
                <el-option v-for="item in printModelTypeList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item :label="$t('module.packingManage.LabelTemplate.LabelContent')" prop="humanFriendlyContent">
          <el-input
            v-model="printModel.humanFriendlyContent"
            :readonly="false"
            disabled
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 8 }"
          />
        </el-form-item>
        <el-form-item :label="$t('module.packingManage.LabelTemplate.LabelRemark')" prop="remark">
          <el-input v-model="printModel.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" />
        </el-form-item>
      </el-form>
    </div>
    <el-row style="text-align: right">
      <el-button @click="close">{{ 'btn.cancel' | i18nFilter }}</el-button>
      <el-button type="primary" @click.prevent.stop="handleSubmit('printModel')">
        {{ 'btn.confirm' | i18nFilter }}
      </el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import i18n from '@/lang'
import { add, getInfo, update } from '@/api/packing-manage/packing-label.js'
import { getLodop } from '@/assets/libs/LodopFuncs.js'
// import SmallTitle from '@/components/BaseDrawer/components/SmallTitle.vue'

export default {
  name: 'AddLabelPanel',
  data() {
    return {
      visible: false,
      // content: '',
      printModel: {
        id: '',
        code: '',
        name: '',
        content: '',
        base64Content: '',
        humanFriendlyContent: '',
        type: 1,
        isDefault: 0,
        isPreview: 1,
        state: 'normal',
        remark: ''
      },
      printModelTypeList: [
        {
          id: 0,
          name: i18n.t('module.packingManage.LabelTemplate.CustomTemplate')
        },
        {
          id: 1,
          name: i18n.t('module.packingManage.LabelTemplate.ModalTemplate')
        },
        {
          id: 2,
          name: i18n.t('module.packingManage.LabelTemplate.GradeTemplate') // 修改标签类型和主页的数据字典不对应问题
        }
      ],
      rules: {
        code: [
          { required: true, message: i18n.t('module.packingManage.LabelTemplate.LabelCodeHint'), trigger: 'blur' },
          { min: 1, message: i18n.t('module.packingManage.LabelTemplate.LengthHint'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: i18n.t('module.packingManage.LabelTemplate.LabelNameHint'), trigger: 'blur' },
          { min: 1, message: i18n.t('module.packingManage.LabelTemplate.LengthHint'), trigger: 'blur' }
        ],
        type: [
          {
            required: true,
            message: this.$t('module.basicData.visual.hints.selectTags'),
            trigger: 'change'
          }
        ],
        content: [
          { required: true, message: i18n.t('module.packingManage.LabelTemplate.LabelContentHint'), trigger: 'blur' },
          { min: 1, message: i18n.t('module.packingManage.LabelTemplate.LengthHint'), trigger: 'blur' }
        ]
      },
      id: null
    }
  },
  created() {
    this.init()
  },
  methods: {
    initDataForm() {
      this.printModel = {
        id: null,
        code: '',
        name: '',
        content: '',
        base64Content: '',
        humanFriendlyContent: '',
        type: 1,
        isDefault: 0,
        isPreview: 1,
        state: 'normal',
        remark: ''
      }
    },

    init(id) {
      this.initDataForm()
      this.id = id

      if (id) {
        getInfo({ id: this.id }).then(res => {
          if (res.data) {
            this.printModel = res.data
            this.afterGetInfo() // 服务器来回数据后，先解析填充一下
          }
        })
      }

      this.$nextTick(() => {
        this.visible = true
      })
    },

    afterGetInfo() {
      if (this.printModel.content !== '') {
        try {
          // aka. parseLabelContent()
          // 对打印设计返回来的数据进行解包装，将服务器返回的字符串转为明文和编码
          // obj: { h: xxx, e: xxx } ===> important, 'h' stands for 'humen' and 'e' stands for 'encodedContent'
          const strContent = JSON.parse(this.printModel.content)
          const { h, e } = strContent
          this.printModel.humanFriendlyContent = h
          this.printModel.base64Content = e
        } catch (error) {
          // 提示开发者
          console.error('afterGetInfo(): JSON 格式不正确', error)
          // 提供向后兼容的功能
          this.printModel.humanFriendlyContent = this.printModel.content
        }
      }
    },

    beforeSend() {
      // aka. encodeContent()
      // 对打印设计返回来的数据进行包装，将明文和编码包装到一起作为字符串上传到服务器
      this.printModel.content = JSON.stringify({
        h: this.printModel.humanFriendlyContent,
        e: this.printModel.base64Content
      })
    },

    handleSubmit(formName) {
      // console.log('handleSubmit')
      this.$refs[formName].validate(valid => {
        if (!valid) {
          return false
        }
        this.beforeSend() // 发送前的准备事项
        if (this.id) {
          update(this.printModel).then(res => {
            this.$message.success({
              message: '操作成功',
              duration: 1500,
              onClose: () => {
                setTimeout(() => {
                  this.close()
                }, 300)
              }
            })
          })
        } else {
          add(this.printModel).then(res => {
            this.$message.success({
              message: '操作成功',
              duration: 1500,
              onClose: () => {
                setTimeout(() => {
                  this.close()
                }, 300)
              }
            })
          })
        }
      })
    },
    close() {
      // this.$router.push({ path: this.$route.query.redirect })
      this.visible = false
      // this.$nextTick(() => {
      this.$emit('destory')
      // })
    },

    btnClickDesign() {
      const LODOP = getLodop()
      LODOP.PRINT_INIT('初始化打印')
      LODOP.SET_PRINT_MODE('PROGRAM_CONTENT_BYVAR', true) // 生成程序时，内容参数有变量用变量，无变量用具体值
      LODOP.SET_SHOW_MODE('DESIGN_IN_BROWSE', 1)
      LODOP.ADD_PRINT_DATA('ProgramData', this.printModel.base64Content) // 装载模板
      // this.printModel.content = LODOP.PRINT_DESIGN()
      LODOP.PRINT_DESIGN()

      if (LODOP.CVERSION) {
        LODOP.On_Return = (TaskID, Value) => {
          // console.log('CVERSION')
          // console.log(typeof Value)
          // this.$set(this.printModel, humanFriendlyContent, Value)
          this.printModel.humanFriendlyContent = Value
          this.$forceUpdate()
          // console.log('printModel', this.printModel)
          // this.content = Value
          // console.log('here: ', this.printModel.humanFriendlyContent)
          this.getProgramData()
        }
      }
    },
    getProgramData() {
      const LODOP = getLodop()
      // console.log('getProgramData')
      LODOP.GET_VALUE('ProgramData', 0) // 获得文档式模板
      // const content = LODOP.GET_VALUE('ProgramData', 0) // 获得文档式模板
      // console.log('GET_VALUE: ', content)
      if (LODOP.CVERSION) {
        LODOP.On_Return = (TaskID, Value) => {
          // console.log('On_Return Value: ', Value)
          this.printModel.base64Content = Value
        }
      }
    },
    btnClickPrint() {
      const LODOP = getLodop()
      // const modelCode = this.printModel.content
      // LODOP.ADD_PRINT_DATA('ProgramData', modelCode) // 装载模板
      LODOP.ADD_PRINT_DATA('ProgramData', this.printModel.base64Content) // 装载模板
      // 按类名赋值
      LODOP.SET_PRINT_STYLEA('name', 'CONTENT', '张三')
      LODOP.SET_PRINT_STYLEA('code', 'CONTENT', '123455')
      LODOP.PREVIEW()
    },
    btnClickInfo() {}
  }
}
</script>

<style scoped>
.template-design-entry-dialog >>> .el-form--label-top .el-form-item__label {
  padding: 0;
}
</style>
