<!-- @desc:打印模板设置  @auth:张潇木  @time:2023/6/14 15:17 -->
<template>
  <div class="main-div" style="width:100%;height:100%;">
    <Layout style="height:100%">
      <Layout style="height: calc(100% - 68px)">
        <!--   左侧可拖拽元素     -->
        <Sider class="side" :width="200">
          <div class="title">
            <Icon type="ios-apps" :size="20" class="icon"/>
            基础元素
          </div>
          <DkRow>
            <DkCol span="12">
              <!--    条形码     -->
              <div class="ep-draggable-item" tid="DKModule.barcode">
                <div class="label">
                  <span class="glyphicon glyphicon-barcode" aria-hidden="true"></span>
                </div>
                <span class="label">条形码</span>
              </div>
            </DkCol>
            <DkCol span="12">
              <!--    二维码     -->
              <div class="ep-draggable-item" tid="DKModule.qrcode">
                <div class="label">
                  <span class="glyphicon glyphicon-qrcode" aria-hidden="true"></span>
                </div>
                <span class="label">二维码</span>
              </div>
            </DkCol>
          </DkRow>
          <DkRow>
            <DkCol span="12">
              <!--    文本     -->
              <div class="ep-draggable-item" tid="DKModule.text">
                <div class="label">
                  <span class="glyphicon glyphicon-text-size" aria-hidden="true"></span>
                </div>
                <span class="label">文本</span>
              </div>
            </DkCol>
            <DkCol span="12">
              <!--    图片     -->
              <div class="ep-draggable-item" tid="DKModule.image">
                <div class="label">
                  <span class="glyphicon glyphicon-picture" aria-hidden="true"></span>
                </div>
                <span class="label">图片</span>
              </div>
            </DkCol>
              <DkCol span="12">
                <!--    表格     -->
                <div class="ep-draggable-item" tid="DKModule.table">
                  <div class="label">
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
                  </div>
                  <span class="label">表格</span>
                </div>
              </DkCol>
          </DkRow>
          <div class="title">
            <Icon type="ios-apps" :size="20" class="icon"/>
            辅助元素
          </div>
          <DkRow>
            <DkCol span="12">
              <!--    横线     -->
              <div class="ep-draggable-item" tid="DKModule.hline">
                <div class="label">
                  <span class="glyphicon glyphicon-resize-horizontal" aria-hidden="true"></span>
                </div>
                <span class="label">横线</span>
              </div>
            </DkCol>
            <DkCol span="12">
              <!--    竖线     -->
              <div class="ep-draggable-item" tid="DKModule.vline">
                <div class="label">
                  <span class="glyphicon glyphicon-resize-vertical" aria-hidden="true"></span>
                </div>
                <span class="label">竖线</span>
              </div>
            </DkCol>
          </DkRow>
          <DkRow>
            <DkCol span="12">
              <!--    矩形     -->
              <div class="ep-draggable-item" tid="DKModule.rect">
                <div class="label">
                  <Icon type="md-square-outline" size="42" style="color: #0f90ee;"/>
                </div>
                <span class="label">矩形</span>
              </div>
            </DkCol>
            <DkCol span="12">
              <!--    圆形     -->
              <div class="ep-draggable-item" tid="DKModule.oval">
                <div class="label">
                  <Icon type="md-radio-button-off" :size="42" style="color: #0f90ee;"/>
                </div>
                <span class="label">圆形</span>
              </div>
            </DkCol>
          </DkRow>
        </Sider>
        <!--   中间设计器     -->
        <Content style="padding: 14px;overflow: hidden;overflow-x: auto;overflow-y: auto;">
          <div ref="design" id="hiprint-printTemplate" class="hiprint-printTemplate design" style="height: 100%"></div>
        </Content>
        <!--    右侧高级设置    -->
        <Sider class="side" :width="350">
          <div id="PrintElementOptionSetting"/>
        </Sider>
      </Layout>
      <!--   底部操作栏   -->
      <Footer class="footer">
        <div class="tools">
          <!--    旋转纸张      -->
          <Tooltip content="旋转纸张">
            <Button icon="md-refresh" @click="()=>{hiprintTemplate?.rotatePaper()}"></Button>
          </Tooltip>
          <!--    缩放比例      -->
          <Poptip trigger="hover" class="scale">
            <Button icon="md-resize"></Button>
            <div slot="content" style="background: #f8f8f9;">
              <Card title="调整缩放比例" icon="md-resize" :padding="0" shadow style="width: 200px;">
                <CellGroup>
                  <Cell style="display: flex;justify-content: center;">
                    <InputNumber v-model="scaleValue"
                                 :min="scaleMin"
                                 :max="scaleMax"
                                 :step="0.1"
                                 controls-outside
                                 :editable="false"
                                 style="width: 150px"
                                 :formatter="value => `${(value * 100).toFixed(0)}%`"
                                 :parser="value => value.replace('%', '')"
                                 @on-change="(e)=>{hiprintTemplate.zoom(e)}"
                    ></InputNumber>
                  </Cell>
                </CellGroup>
              </Card>
            </div>
          </Poptip>
          <!--    设置纸张大小      -->
          <Poptip trigger="hover" class="paper-size">
            <Button icon="md-copy"></Button>
            <div slot="content" style="background: #f8f8f9;">
              <Card title="设置纸张大小" icon="md-copy" :padding="0" shadow style="width: 200px;">
                <CellGroup>
                  <Cell style="display: flex;justify-content: center">
                    <ButtonGroup>
                      <Button style="width: 60px" @click="setPaper('A3')">A3</Button>
                      <Button style="width: 60px" @click="setPaper('A4')">A4</Button>
                      <Button style="width: 60px" @click="setPaper('A5')">A5</Button>
                    </ButtonGroup>
                  </Cell>
                  <Cell style="display: flex;justify-content: center">
                    <ButtonGroup>
                      <Button style="width: 60px" @click="setPaper('B3')">B3</Button>
                      <Button style="width: 60px" @click="setPaper('B4')">B4</Button>
                      <Button style="width: 60px" @click="setPaper('B5')">B5</Button>
                    </ButtonGroup>
                  </Cell>
                  <Cell>
                    <Divider orientation="center" :plain="true">自定义纸张大小(mm)</Divider>
                    <div style="display: flex;justify-content: space-around">
                      <div style="width: 90px;margin-left: 2px">
                        <InputNumberPop v-model="paperWidth" placeholder="宽" :digits="0"/>
                      </div>
                      <div style="width: 90px;margin-left: 15px">
                        <InputNumberPop v-model="paperHeight" placeholder="高" :digits="0"/>
                      </div>
                    </div>
                    <DkButton style="width: 92%;margin:3px 0 0 1px;" type="primary" @click="setPaper('custom')">确定
                    </DkButton>
                  </Cell>
                </CellGroup>
              </Card>
            </div>
          </Poptip>
          <!--    对齐     -->
          <Poptip trigger="hover" class="align">
            <Button icon="md-list"></Button>
            <div slot="content" style="background: #f8f8f9;">
              <Card title="元素对齐" icon="md-list" :padding="0" shadow style="width: 180px;">
                <CellGroup>
                  <Cell>
                    <DkButton @click="setElsAlign('left')">水平左对齐</DkButton>
                    <div slot="extra" class="glyphicon glyphicon-object-align-left align"/>
                  </Cell>
                  <Cell>
                    <DkButton @click="setElsAlign('vertical')">水平居中对齐</DkButton>
                    <div slot="extra" class="glyphicon glyphicon-object-align-vertical align"/>
                  </Cell>
                  <Cell>
                    <DkButton @click="setElsAlign('right')">水平右对齐</DkButton>
                    <div slot="extra" class="glyphicon glyphicon-object-align-right align"/>
                  </Cell>
                  <Cell>
                    <DkButton @click="setElsAlign('top')">垂直顶部对齐</DkButton>
                    <div slot="extra" class="glyphicon glyphicon-object-align-top align"/>
                  </Cell>
                  <Cell>
                    <DkButton @click="setElsAlign('horizontal')">垂直居中对齐</DkButton>
                    <div slot="extra" class="glyphicon glyphicon-object-align-horizontal align"/>
                  </Cell>
                  <Cell>
                    <DkButton @click="setElsAlign('bottom')">垂直底部对齐</DkButton>
                    <div slot="extra" class="glyphicon glyphicon-object-align-bottom align"/>
                  </Cell>
                </CellGroup>
              </Card>
            </div>
          </Poptip>
          <!--    快捷键      -->
          <Poptip trigger="hover">
            <Button icon="ios-options"></Button>
            <div slot="content" style="background: #f8f8f9;">
              <Card title="快捷键说明" icon="ios-options" :padding="0" shadow style="width: 350px;">
                <CellGroup>
                  <Cell title="复制">
                    <div slot="extra" style="display: flex">
                      <div class="key">Ctrl</div>
                      <div class="key">C</div>
                    </div>
                  </Cell>
                  <Cell title="粘贴">
                    <div slot="extra" style="display: flex">
                      <div class="key">Ctrl</div>
                      <div class="key">V</div>
                    </div>
                  </Cell>
                  <Cell title="撤销">
                    <div slot="extra" style="display: flex">
                      <div class="key">Ctrl</div>
                      <div class="key">Z</div>
                    </div>
                  </Cell>
                  <Cell title="撤回撤销">
                    <div slot="extra" style="display: flex">
                      <div class="key">Ctrl</div>
                      <div class="key">Shift</div>
                      <div class="key">Z</div>
                    </div>
                  </Cell>
                  <Cell title="删除">
                    <div slot="extra" style="display: flex">
                      <div class="key">BackSpace</div>
                      <div style="padding-left:3px">或</div>
                      <div class="key">Delete</div>
                    </div>
                  </Cell>
                  <Cell title="多选">
                    <div slot="extra" style="display: flex;align-items: center">
                      <div>按住</div>
                      <div class="key">Ctrl</div>
                      <div style="padding-left:3px">+ 点击鼠标左键</div>
                    </div>
                  </Cell>
                  <Cell title="二维码/条形码自由调整">
                    <div slot="extra" style="display: flex;align-items: center">
                      <div>按住</div>
                      <div class="key">Shift</div>
                      <div style="padding-left:3px">+ 元素右下角</div>
                    </div>
                  </Cell>
                  <Cell title="正交水平移动">
                    <div slot="extra" style="display: flex;align-items: center">
                      <div>按住</div>
                      <div class="key">Shift</div>
                      <div style="padding-left:3px">+ 移动元素</div>
                    </div>
                  </Cell>
                  <Cell title="正交垂直移动">
                    <div slot="extra" style="display: flex;align-items: center">
                      <div>按住</div>
                      <div class="key">Shift</div>
                      <div class="key">Alt</div>
                      <div style="padding-left:3px">+ 移动元素</div>
                    </div>
                  </Cell>
                  <Cell title="框选元素" extra="空白处开始拖拽，出现矩形选区"/>
                  <Cell title="元素位置微调" extra="选中元素后，按方向键调整"/>
                </CellGroup>
              </Card>
            </div>
          </Poptip>
          <!--    打印预览      -->
          <Tooltip content="打印预览">
            <Button icon="md-eye" @click="()=>{this.setPrintPreviewModalDisplay(true)}"></Button>
          </Tooltip>
          <!--    测试打印      -->
          <Tooltip content="测试打印">
            <Button icon="md-print" @click="testPrint"></Button>
          </Tooltip>
          <!--    获取json      -->
          <Poptip trigger="click" class="json">
            <Button icon="md-code-working"></Button>
            <div slot="content" style="background: #f8f8f9;">
              <Card title="获取json" icon="md-code-working" :padding="0" shadow style="width: 800px;">
                <CellGroup>
                  <Cell style="width: 100%">
                    <div>
                      <Input v-model="templateData" type="textarea" :autosize="{minRows: 5,maxRows: 20}"/>
                    </div>
                    <DkButton style="width: 100%;margin:10px 0;" type="primary" @click="()=>{this.templateData=JSON.stringify(hiprintTemplate?.getJson())}">确定 </DkButton>
                  </Cell>
                </CellGroup>
              </Card>
            </div>
          </Poptip>
        </div>
        <div>
          <DkButton style="margin-right: 10px;" ref="save" type="primary" @click="save">{{ $t('save') }}</DkButton>
          <DkButton ref="close" @click="close('/mst/label-print-layout/index')">{{ $t('close') }}</DkButton>
        </div>
      </Footer>
    </Layout>
    <PrintPreview ref="preView" v-if="print.preview.display" :print-template="hiprintTemplate"></PrintPreview>
  </div>
</template>

<script>
import { hiprint } from 'vue-plugin-hiprint'
import './css/layout-setting.css'
import providers from './js/providers'
import {formMixin} from '@/mixins/form'
import PrintPreview from '_c/business/print/print-preview'
import { mapState, mapMutations } from 'vuex'

export default {
  name: "layout-setting",
  mixins: [formMixin],
  components: {PrintPreview},
  props: {
    type: {
      type: String,
      default: 'edit'
    },
  },
  data() {
    return {
      showPreview:false,
      templateData:undefined,
      hiprintTemplate: null,
      paperTypes: {
        'A3': {
          width: 420,
          height: 296.6
        },
        'A4': {
          width: 210,
          height: 296.6
        },
        'A5': {
          width: 210,
          height: 147.6
        },
        'B3': {
          width: 500,
          height: 352.6
        },
        'B4': {
          width: 250,
          height: 352.6
        },
        'B5': {
          width: 250,
          height: 175.6
        }
      },
      paperWidth: null,
      paperHeight: null,
      scaleValue: 1,
      scaleMax: 5,
      scaleMin: 0.5,
      labelPrintItemList: [],
      formData:{}
    }
  },
  computed: {
    ...mapState(['print']),
  },
  methods: {
    ...mapMutations(['setPrintPreviewModalDisplay']),
    /**
     * @desc   : 提交保存
     * @author : 张潇木
     * @date   : 2023/6/30 15:57
     */
    save() {
      console.log('this.id',this.formData)
      this.excute(this.$service.printLayoutService, this.$service.printLayoutService.update, {
        layoutId: this.formData.layoutId,
        layoutData: this.hiprintTemplate?.getJson()
      }).then(res=>{
        if (res.code === this.$config.SUCCESS_CODE) {
          this.$Message.success(res.message)
          this.close(false);
        } else {
          this.$Message.warning(res.message)
        }
      })
    },

    /**
     * @desc   : 重写计算表格高度方法，避免报错
     * @author : 张潇木
     * @date   : 2022-5-13 12:58
     */
    resizeTable() {
      // console.log('重写resizeTable')
    },

    /**
     * @desc   : 重写监听键盘事件
     * @author : 张潇木
     * @date   : 2022-5-12 10:07
     */
    addKeyBoardEvent() {
      console.log('重写监听键盘事件')
    },

    /**
     * @desc   : 获取模板数据源项目
     * @author : 张潇木
     * @date   : 2023/6/21 13:34
     */
    getLabelPrintItem() {
      return this.excute(this.$service.commonService, this.$service.commonService.getLabelPrintItem, {docName:this.formData.docName})
    },

    /**
     * @desc   : 根据模板id查询
     * @author : 张潇木
     * @date   : 2023/6/21 16:28
     */
    detail(id) {
      return this.excuteNoParam(this.$service.printLayoutService, this.$service.printLayoutService.selectById,[id],false)
    },

    /**
     * @desc   : 加载初始值
     * @author : 张潇木
     * @date   : 2023/6/21 16:44
     */
    setValuesByEdit(data) {
      if(data) this.formData = data
      this.getLabelPrintItem().then(res => {
        if (res.code === 200) {
          this.labelPrintItemList = res.data
          this.init()
        }else{
          this.$Message.warning(res.message)
        }
      })
    },

    /**
     * @desc   : 对齐
     * @author : 张潇木
     * @date   : 2023/6/19 15:44
     */
    setElsAlign(e) {
      this.hiprintTemplate.setElsAlign(e)
    },

    /**
     * @desc   : 设置纸张大小
     * @author : 张潇木
     * @date   : 2023/6/20 10:30
     */
    setPaper(type) {
      if (Object.keys(this.paperTypes).includes(type)) {
        let value = this.paperTypes[type]
        this.curPaper = { type: type, width: value.width, height: value.height }
        this.hiprintTemplate.setPaper(value.width, value.height)
      } else {
        this.curPaper = { type: 'custom', width: this.paperWidth, height: this.paperHeight }
        this.hiprintTemplate.setPaper(this.paperWidth, this.paperHeight)
      }
    },

    /**
     * @desc   : 初始化设计器
     * @author : 张潇木
     * @date   : 2023/6/21 14:10
     */
    init() {
      console.log('PrintElementTypeGroup',hiprint.PrintElementTypeGroup)
      let self = this
      // 初始化 provider
      this.$dkprint.init({
        providers: [providers],
      })
      this.resetTableColumn()

      // 还原配置
      hiprint.setConfig()
      // 替换配置
      hiprint.setConfig({
        optionItems: [
          //重写数据源
          this.fieldSetting(),
          //重写预览数据
          this.testDataSetting(),
          //重写上传图片空间
          this.uploadSetting(),
          // //自定义元素位置坐标(mm)
          // this.coordinateMM(),
          // //自定义元素宽高大小(mm)
          // this.widthHeightMM(),
        ],
        //隐藏的项目
        panel: {
          supportOptions: [
            { name: 'panelPaperRule', hidden: true },
            { name: 'panelPageRule', hidden: true },
            { name: 'firstPaperFooter', hidden: true },
            { name: 'evenPaperFooter', hidden: true },
            { name: 'oddPaperFooter', hidden: true },
            { name: 'lastPaperFooter', hidden: true },
            { name: 'leftOffset', hidden: true },
            { name: 'topOffset', hidden: true },
            { name: 'orient', hidden: true },
            // { name: 'paperNumberDisabled', hidden: true },
            { name: 'paperNumberContinue', hidden: true },
            // { name: 'paperNumberFormat', hidden: true },
            { name: 'watermarkOptions', hidden: true },
            { name: 'panelLayoutOptions', hidden: true },
          ]
        },
        //自定义项目
        text:{
          tabs:[
            {
              name:'基础',
              options:[

                {name:'fixed',hidden: true},

              ]
            },
            {
              name:'样式',
              options:[]
            },
            {
              name:'边框',
              options:[]
            },
            {
              name:'高级',
              options:[
                {name:'pageBreak',hidden:true},
                {name:'showInPage',hidden:true},
                {name:'unShowInPage',hidden:true},
                {name:'upperCase',hidden:true},
                {name:'formatter',hidden:true},
                {name:'styler',hidden:true},
              ]
            }
          ],
        },
        table:{
          tabs:[
            {
              name:'基础',
              options:[
                {name:'field',hidden: true},
                {name:'testData',hidden: true},

                // {name:'coordinate',hidden: true},
                // {name:'widthHeight',hidden: true},
                // {name:'fixed',hidden: true},
                // {
                //   name:'coordinateMM',
                //   after:'coordinate',
                //   hidden:false,
                // },
                // {
                //   name:'widthHeightMM',
                //   after:'widthHeight',
                //   hidden:false,
                // }
              ]
            },
            {
              name:'样式',
              options:[]
            },
            {
              name:'列',
              options:[]
            },
            {
              name:'高级',
              options:[]
            }
          ]
        },
        image:{
          tabs:[
            {
              name:'基础',
              options:[
                {name:'field',hidden: true},

                {name:'fixed',hidden: true},
                {name:'showInPage',hidden:true},
                {name:'unShowInPage',hidden:true},

              ]
            },
            {
              name:'样式',
              options:[]
            },
            {
              name:'高级',
              options:[
                {name:'pageBreak',hidden:true},
                {name:'formatter',hidden:true},
                {name:'styler',hidden:true},
              ]
            }
          ],
        },
        hline:{
          tabs:[
            {
              name:'基础',
              options:[

                {name:'fixed',hidden: true},

              ]
            },
            {
              name:'样式',
              options:[]
            },
            {
              name:'高级',
              options:[
                {name:'pageBreak',hidden:true},
              ]
            }
          ],
        },
        vline:{
          tabs:[
            {
              name:'基础',
              options:[

                {name:'fixed',hidden: true},


              ]
            },
            {
              name:'样式',
              options:[]
            },
            {
              name:'高级',
              options:[
                {name:'pageBreak',hidden:true},
              ]
            }
          ],
        },
        rect:{
          tabs:[
            {
              name:'基础',
              options:[

                {name:'fixed',hidden: true},


              ]
            },
            {
              name:'样式',
              options:[]
            },
            {
              name:'高级',
              options:[
                {name:'pageBreak',hidden:true},
              ]
            }
          ],
        },
        oval:{
          tabs:[
            {
              name:'基础',
              options:[

                {name:'fixed',hidden: true},

              ]
            },
            {
              name:'样式',
              options:[]
            },
            {
              name:'高级',
              options:[
                {name:'pageBreak',hidden:true},
              ]
            }
          ],
        },
      })

      //定义模板默认值，默认隐藏页码
      let template=this.formData?.layoutData
      if(template&&Object.keys(template).length==0){
        template={"panels":[{"index":0,"name":1,"paperType":"A4","height":297,"width":210,"paperHeader":10,"paperFooter":830,"printElements":[],"paperNumberLeft":565,"paperNumberTop":819,"paperNumberContinue":false,"paperNumberFormat":"${paperNo}/${paperCount}"}]}
      }

      //构建左侧可拖拽元素
      this.$dkprint.PrintElementTypeManager.buildByHtml($('.ep-draggable-item'))

      // 先清空, 避免重复构建
      $('#hiprint-printTemplate').empty()
      this.hiprintTemplate = new hiprint.PrintTemplate({
        // 图片选择功能
        onImageChooseClick: (target) => {
          // 创建input，模拟点击，然后 target.refresh 更新
          let input = document.createElement("input");
          input.setAttribute("type", "file");
          input.click();
          input.onchange = function () {
            let file = this.files[0];
            console.log('file',file)
            if (!file) {
              return;
            }
            if (!(self.$config.uploadFileConfig.acceptPicType).split(',').includes(file.type)) {
              self.$Message.warning('文件格式不在允许的范围内')
              return;
            }
            if (file.size / 1024  > self.$config.uploadFileConfig.maxSize) {
              self.$Message.warning(`上传图片大小不能超过${self.$config.uploadFileConfig.maxSize / 1024}M,当前大小:${(file.size / 1024 / 1024).toFixed(2)}M`)
              return;
            }

            let reader = new FileReader();
            //通过文件流行文件转换成Base64字行串
            reader.readAsDataURL(file);
            //转换成功后
            reader.onloadend = function () {
              // 通过 target.refresh 更新图片元素
              target.refresh(reader.result);
            }
          }
          input.remove();
        },
        //导入模板
        template:template,
        //设置字体
        fontList: [
          { title: '微软雅黑', value: 'Microsoft YaHei' },
          { title: '黑体', value: 'STHeitiSC-Light' },
          { title: '宋体', value: 'SimSun' },
          { title: '楷体', value: 'STKaiti' },
        ],
        dataMode: 1, // 1:getJson 其他：getJsonTid 默认1
        history: true, // 是否需要 撤销重做功能
        onDataChanged: (type, json) => {
          // console.log('onDataChanged')
          // console.log('onDataChanged',type,json); // type:新增、移动、删除、修改(参数调整)、大小、旋转
          // console.log( this.hiprintTemplate)
          this.resetPositionAfterMove(type)
          // .updateOption('draggable', false, true);
          // console.log('template',json); // 返回 template
        },
        //右侧高级设置
        settingContainer: '#PrintElementOptionSetting', // 元素参数容器
      })
      // 构建中间设计器 并填充到容器中
      this.hiprintTemplate.design('#hiprint-printTemplate', { grid: true })

      //重写纸张大小
      this.paperHeight=this.formData?.layoutData?.panels?.[0]?.height
      this.paperWidth=this.formData?.layoutData?.panels?.[0]?.width
      if( this.paperHeight&&this.paperWidth){
        this.setPaper('other')
      }

      //添加class 点击时取消选择
      self.$refs['design'].children[0].classList.add('design')

      //模板参数
      console.log('HIPRINT_CONFIG',window.HIPRINT_CONFIG )
      console.log('table',window.HIPRINT_CONFIG.table )
      console.log('hiprintTemplate',this.hiprintTemplate )
      console.log('hinnn',hinnn )
      console.log('hiprint',hiprint )

      // {
      //   options: {
      //   field: 'table',
      //     tableHeaderRepeat: 'first',
      //     tableFooterRepeat: 'last',
      //     fields: [
      //     {text: '名称', field: 'NAME'},
      //     {text: '数量', field: 'SL'},
      //     {text: '规格', field: 'GG'},
      //     {text: '条码', field: 'TM'},
      //     {text: '单价', field: 'DJ'},
      //     {text: '金额', field: 'JE'},
      //   ],
      // },
      //   editable: true,
      //     columnDisplayEditable: true,//列显示是否能编辑
      //   columnDisplayIndexEditable: true,//列顺序显示是否能编辑
      //   columnTitleEditable: true,//列标题是否能编辑
      //   columnResizable: true, //列宽是否能调整
      //   columnAlignEditable: true,//列对齐是否调整
      //   isEnableEditField: true, //编辑字段
      //   isEnableContextMenu: true, //开启右键菜单 默认true
      //   isEnableInsertRow: true, //插入行
      //   isEnableDeleteRow: true, //删除行
      //   isEnableInsertColumn: true, //插入列
      //   isEnableDeleteColumn: true, //删除列
      //   isEnableMergeCell: true, //合并单元格
      //   columns: [
      //   [
      //     {title: '名称', align: 'center', field: 'NAME', width: 150},
      //     {title: '数量', align: 'center', field: 'SL', width: 80},
      //     {title: '规格', align: 'center', field: 'GG', width: 80, checked: false},
      //     {title: '条码', align: 'center', field: 'TM', width: 100, checked: false},
      //     {title: '单价', align: 'center', field: 'DJ', width: 100},
      //     {title: '金额', align: 'center', field: 'JE', width: 100, checked: false},
      //   ],
      // ],
      // },

    },

    /**
     * @desc   : 重写数据源设置
     * @author : 张潇木
     * @date   : 2023/6/21 13:44
     */
    fieldSetting() {
      let self = this

      function t() {
        this.name = 'field' // 重写的参数 key
      }

      // 涉及修改元素样式， 添加一个 css 方法
      return t.prototype.createTarget = function () {
        // console.log('fieldSetting', self.labelPrintItemList)
        let list = '\n            <option value="" >无</option>'
        self.labelPrintItemList.filter(it=>it.itemType==0).forEach(it => {
          list += '\n            <option value="' + it.dataKey + '">' + it.itemName + '</option>'
        })
        this.target = $(' <div class="hiprint-option-item hiprint-option-item-row">\n        <div class="hiprint-option-item-label">\n        数据源\n        </div>\n        <div class="hiprint-option-item-field">\n        <select class="auto-submit">        </select>\n        </div>\n    </div>')
        this.target.find('.auto-submit').append($(list))
        return this.target
      },
        // 获取值
        t.prototype.getValue = function () {
          //新值
          let newValue = this.target.find('select').val()
          //原值
          let oldValue=self.hiprintTemplate.getSelectEls()[0]?.options?.field
          console.log('oldValue',oldValue)
          console.log('newValue',newValue)
          //联动处理，如果改变了数据源，自动设置标题和测试数据。数据源为无时，不处理
          if(newValue&&oldValue!==newValue){
            console.log('改变了数据源，自动设置标题和测试数据。数据源为无时，不处理')
            self.$nextTick(() => {
              self.hiprintTemplate.updateOption('title', undefined, true);
              self.hiprintTemplate.updateOption('testData', undefined, true);
              self.hiprintTemplate.updateOption('dataType', undefined, true);
              self.hiprintTemplate.updateOption('formatter', undefined, true);
            })
            self.changeField()
          }
          //如果数据源原来不是无，但切换成了无，还原成初始值。如果用户自行设置了，则不处理
          if(!newValue&&oldValue){
            console.log('当前数据源是无，且原来不是无，还原成初始值。如果用户自行设置了标题，则不处理')
            self.$nextTick(() => {
              self.hiprintTemplate.updateOption('title', undefined, true);
              self.hiprintTemplate.updateOption('testData', undefined, true);
              self.hiprintTemplate.updateOption('dataType', undefined, true);
              self.hiprintTemplate.updateOption('formatter', undefined, true);
              //模拟点击元素，实现元素容器内数据刷新
              hinnn.event.trigger("PrintElementSelectEventKey_" + self.hiprintTemplate.id, {printElement: self.hiprintTemplate.getSelectEls()[0] })
            })
          }
          if (newValue) return newValue
        },
        // 设置值
        t.prototype.setValue = function (t) {
          // console.log('setValue', t)
          t && (this.target.find('option[value="' + t + '"]').length || this.target.find('select').prepend('<option value="' + t + '" >' + t + '</option>'))
          this.target.find('select').val(t)
        },
        // 销毁 DOM
        t.prototype.destroy = function () {
          this.target.remove()
        }, t
    },

    /**
     * @desc   : 重写预览数据设置(只改名'测试数据'->'预览数据')
     * @author : 张潇木
     * @date   : 2023/6/21 13:44
     */
    testDataSetting() {
      function t() {
        this.name = "testData";
      }

      return t.prototype.createTarget = function () {
        return this.target = $(`<div class="hiprint-option-item hiprint-option-item-row">\n        <div class="hiprint-option-item-label">\n        预览数据\n        </div>\n        <div class="hiprint-option-item-field">\n        <input type="text" placeholder="仅设置数据源时有效" class="auto-submit" >\n        </div>\n    </div>`), this.target;
      }, t.prototype.getValue = function () {
        let t = this.target.find("input").val();
        if (t) return t.toString();
      }, t.prototype.setValue = function (t) {
        this.target.find("input").val(t);
      }, t.prototype.destroy = function () {
        this.target.remove();
      }, t;
    },

    /**
     * @desc   : 重写上传图片控件
     * @author : 张潇木
     * @date   : 2023/6/21 13:44
     */
    uploadSetting() {

      function t() {
        this.name = "src";
      }


      return t.prototype.createTarget = function (t) {
        this.el = t;
        let e = void 0, i = this;
        // this.target = $(`<div class="hiprint-option-item hiprint-option-item-row">\n        <div class="hiprint-option-item-label">\n        图片地址\n        </div>\n        <div class="hiprint-option-item-field" style="display: flex;align-items: baseline;">\n        <input type="text" placeholder="请输入图片地址" class="auto-submit" style="width:70%">\n    <button class="hiprint-option-item-settingBtn" style="padding:0 10px;margin:0 0 0 5px" type="button">选择</button>        </div>\n    </div>`);
        this.target = $(`<div class="hiprint-option-item hiprint-option-item-row">\n
                          <input type="text" style="display: none" placeholder="请输入图片地址" class="auto-submit" style="width:70%">
                          <button class="hiprint-option-item-settingBtn" style="padding:0 10px;margin:10px 0 0 0" type="button">选择图片</button>
                          </div>`);
        if (t && (e = t.getOnImageChooseClick()), e) {
          this.target.find('button').click(function () {
            e && e(i);
          })
        }
        return this.target;
      }, t.prototype.getValue = function () {
        let t = this.target.find("input").val();
        if (t) return t.toString();
      }, t.prototype.setValue = function (t) {
        this.target.find("input").val(t);
      }, t.prototype.refresh = function (t, opt, cb) {
        let that = this;
        this.setValue(t), this.target.find("input").change();
        if (this.el && opt) {
          let img = new Image();
          img.src = t;
          if (img.complete) {
            that.updateEl(img.width, img.height, opt, cb)
          } else {
            img.onload = function () {
              that.updateEl(img.width, img.height, opt, cb)
            }
          }
        }
      }, t.prototype.updateEl = function (width, height, opt, cb) {
        if (opt) {
          let ratio, w, h;
          if (opt || opt.auto) {
            if (width >= height) {
              opt.width = true;
            } else {
              opt.height = true;
            }
          }
          if (opt.width) {
            ratio = height / width;
            w = this.el.options.width;
            h = Math.floor(w * ratio * 10) / 10;
            this.el.options.height = h;
            this.el.designTarget.css('height', h + "pt");
          } else if (opt.height) {
            ratio = width / height;
            h = this.el.options.height;
            w = Math.floor(h * ratio * 10) / 10;
            this.el.options.width = w;
            this.el.designTarget.css('width', w + "pt");
          } else if (opt.real) {
            w = hinnn.px.toPt(width);
            h = hinnn.px.toPt(height);
            this.el.options.width = w;
            this.el.options.height = h;
            this.el.designTarget.css('width', w + "pt");
            this.el.designTarget.css('height', h + "pt");
          }
          this.el.designTarget.children('.resize-panel').trigger($.Event('click'));
        } else {
          cb && cb(this.el, width, height);
        }
      }, t.prototype.destroy = function () {
        this.target.remove();
      }, t;
    },

    /**
     * @desc   : 自定义参数 - 元素位置坐标（mm）
     * @author : 张潇木
     * @date   : 2023/7/24 10:28
     */
    coordinateMM(){
      let self =this

      function t() {
        this.name = "coordinateMM";
      }

      return t.prototype.createTarget = function (t, o) {
        let n = this;
        n.target = $('<div class="hiprint-option-item hiprint-option-item-row">' +
          '<div class="hiprint-option-item-label">\n        位置坐标(mm)\n        </div>' +
          '<div class="hiprint-option-item-field" style="display: flex;align-items: baseline;justify-content: space-between">\n        ' +
          '<input type="number" style="width:48%" placeholder="X位置(左)" class="auto-submit" />\n        ' +
          '<input type="number" style="width:48%" placeholder="Y位置(上)" class="auto-submit" />\n        ' +
          '</div>\n' +
          '</div>');
        return n.target;
      },

        t.prototype.css = function (t) {
          if (t && t.length && this.target) {
            // 仅当前元素被选中才更新坐标位置, 以避免冲突
            if (('block' == t.find('.resize-panel').css('display') || t[0].className.includes('table')) ) {
              let v = this.getValue();
              // 设置option值，避免再次点击的时值错乱
              self.hiprintTemplate.getSelectEls()[0].options.left=hinnn.mm.toPt(v.left)
              self.hiprintTemplate.getSelectEls()[0].options.top=hinnn.mm.toPt(v.top)
              // 位置调整
              return t.css("left", hinnn.mm.toPt(v.left)+"pt").css("top", hinnn.mm.toPt(v.top)+"pt");
            }

          }
          return null;
        },

        t.prototype.getValue = function () {
          let v = {
            left: 0,
            top: 0,
          }
          v.left = parseFloat(this.target.find("input:first").val() || 0)
          v.top = parseFloat(this.target.find("input:last").val() || 0)
          return v;
        },

        t.prototype.setValue = function (t, el) {
          self.$nextTick(()=>{
            let { left , top }=self.hiprintTemplate.getSelectEls()?.[0]?.options
            console.log( left , top)
            this.target.find("input:first").val(hinnn.pt.toMm(left));
            this.target.find("input:last").val(hinnn.pt.toMm(top));
          })
        },

        t.prototype.destroy = function () {
          this.target.remove();
        }, t;
    },

    /**
     * @desc   : 自定义参数 - 元素宽高大小（mm）
     * @author : 张潇木
     * @date   : 2023/7/25 11:27
     */
    widthHeightMM(){
      let self =this

      function t() {
        this.name = "widthHeightMM";
      }

      return t.prototype.createTarget = function (t, o) {
        let n = this;
        n.target = $('<div class="hiprint-option-item hiprint-option-item-row">' +
          '<div class="hiprint-option-item-label">\n        宽高大小(mm)\n        </div>' +
          '<div class="hiprint-option-item-field" style="display: flex;align-items: baseline;justify-content: space-between">\n        ' +
          '<input type="number" style="width:48%" placeholder="宽" class="auto-submit" />\n        ' +
          '<input type="number" style="width:48%" placeholder="高" class="auto-submit" />\n        ' +
          '</div>\n' +
          '</div>');
        return n.target;
      },

        t.prototype.css = function (t) {
          if (t && t.length && this.target) {
            // 仅当前元素被选中才更新宽高大小, 以避免冲突
            if (('block' == t.find('.resize-panel').css('display') || t[0].className.includes('table')) ) {
              let v = this.getValue();
              // 设置option值，避免再次点击的时值错乱
              self.hiprintTemplate.getSelectEls()[0].options.width=hinnn.mm.toPt(v.width)
              self.hiprintTemplate.getSelectEls()[0].options.height=hinnn.mm.toPt(v.height)
              // 位置调整
              return t.css("width", hinnn.mm.toPt(v.width)+"pt").css("height", hinnn.mm.toPt(v.height)+"pt");
            }
          }
          return null;
        },

        t.prototype.getValue = function () {
          let v = {
            width: 0,
            height: 0,
          }
          v.width = parseFloat(this.target.find("input:first").val() || 0)
          v.height = parseFloat(this.target.find("input:last").val() || 0)
          return v;
        },

        t.prototype.setValue = function (t, el) {
          self.$nextTick(()=>{
            let { width , height }=self.hiprintTemplate.getSelectEls()?.[0]?.options
            this.target.find("input:first").val(hinnn.pt.toMm(width));
            this.target.find("input:last").val(hinnn.pt.toMm(height));
          })
        },

        t.prototype.destroy = function () {
          this.target.remove();
        }, t;
    },

    /**
     * @desc   : 联动处理，自动带出标题，测试数据，如果field是日期类型，自动设置格式
     * @author : 张潇木
     * @date   : 2023/6/26 16:26
     */
    changeField() {
      this.$nextTick(()=>{
        //选择元素
        let selectElement=this.hiprintTemplate.getSelectEls()[0]
        // console.log('selectElement',selectElement)
        if(selectElement?.options?.field){
          //所选元素的参数
          let selectOptions=selectElement?.options
          //匹配到的打印项目
          let findItem=this.labelPrintItemList.find(it=>it.dataKey==selectOptions.field)
          //设置默认值，无是undefined
          this.hiprintTemplate.updateOption('title', findItem?.itemName, true);
          this.hiprintTemplate.updateOption('testData', findItem?.itemSample, true);
          //联动修改日期类型默认值
          if(findItem.itemStyle===2){
            console.log('联动修改日期类型默认值')
            this.hiprintTemplate.updateOption('dataType', 'datetime', true);
            selectElement.options.format='yyyy-MM-dd HH:mm:ss'
            this.$nextTick(()=> {
              this.hiprintTemplate.updateOption('formatter', "yyyy-MM-dd HH:mm:ss", true);
            })
          }
          //模拟点击元素，实现元素容器内数据刷新
          this.$nextTick(()=> {
            hinnn.event.trigger("PrintElementSelectEventKey_" + this.hiprintTemplate.id, {printElement: selectElement })
          })
        }
      })
    },

    /**
     * @desc   : 测试打印
     * @author : 张潇木
     * @date   : 2023/7/4 16:07
     */
    testPrint(){
      let printData={}

      this.hiprintTemplate?.getJson()?.panels[0].printElements.forEach(it=>{
        let element=it?.options
        if(element?.field&&element?.testData){
          printData[element?.field]=element?.testData
        }
      })
      console.log('printData',printData)
      console.log('模板',this.hiprintTemplate)
      console.log('打印机列表',this.$dkprint.hiwebSocket.getPrinterList())
      return
      this.$dkprint.hiwebSocket.setHost('http://192.168.0.215:17521',(connected, e) => {
        if(connected){
          //设置打印模板
          this.hiprintTemplate.print2(printData)
        }
      })
    },

    /**
     * @desc   : 移动后重新设置位置（为了解决复制并选择数据源后，元素位置会还原到初始位置的bug）
     * @author : 张潇木
     * @date   : 2024/6/17 13:07
     */
    resetPositionAfterMove(type) {
      if(type=='移动'&&this.hiprintTemplate.getSelectEls()?.[0]!==undefined){
        this.hiprintTemplate.updateOption('left', this.hiprintTemplate.getSelectEls()[0]?.options?.left, true);
        this.hiprintTemplate.updateOption('top', this.hiprintTemplate.getSelectEls()[0]?.options?.top, true);
        hinnn.event.trigger("PrintElementSelectEventKey_" + this.hiprintTemplate.id, {printElement: this.hiprintTemplate.getSelectEls()[0] })
      }
    },
    /**
     * @desc   : 设置table可选列
     * @author : 张潇木
     * @date   : 2024/6/17 15:07
     */
    resetTableColumn() {
      //新建时设置table的列
      hiprint.updateElementType('DKModule.table', (type) => {
        console.log('updateElementType')
        let fields = this.labelPrintItemList.filter(it=>it.itemType==1).map(it=>{
          return{
            text:it.itemName,
            field:it.dataKey
          }
        })
        type.options={
          fields: fields,
        }
        return type;
      })
      //编辑时，设置table的列
      if(this.formData?.layoutData){
        this.formData.layoutData.panels?.[0]?.printElements
          ?.filter(it=>it?.printElementType?.type==='table')
          ?.forEach(it=>{
            it.options.fields = this.labelPrintItemList.filter(it=>it.itemType==1).map(it=>{
              return{
                text:it.itemName,
                field:it.dataKey
              }
            })
          })
      }
    }
  },
  created() {
    console.log('重写created')
    this.addKeyBoardEvent()
    this.setPrintPreviewModalDisplay(false)
  },
}
</script>

<style scoped>
.side {
  background-color: #f5f7f9 !important;
  box-shadow: inset 0 -4px 5px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  overflow-x: auto;
  overflow-y: auto;
}

.footer {
  z-index: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 30px 10px 200px;
  background-color: #F5F5F5 !important;
  box-shadow: 0 -4px 5px rgba(0, 0, 0, 0.1);
}

.key {
  align-items: center;
  background-image: linear-gradient(180deg, #f2f4f5, #fff);
  border: 1px solid #d1d5d9;
  border-radius: 4px;
  box-shadow: 0 1px 0 0 #b8bfc4, inset 0 2px 0 0 #fff;
  color: #666;
  display: flex;
  font-size: 12px;
  font-weight: 500;
  height: 20px;
  justify-content: center;
  margin-left: 5px;
  min-width: 20px;
  padding: 0 5px;
}

.ivu-row {
  margin: 0 !important;
}

.Col {
  padding: 10px !important;
  margin: 0 !important;
}

.label {
  width: 100%;
  display: flex;
  justify-content: center;
}

.ep-draggable-item {
  height: 80px;
  border: 1px solid transparent;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.ep-draggable-item:hover {
  border: #0f90ee 1px solid;
}

.title {
  font-size: 14px;
  font-weight: bold;
  padding-left: 10px;
  background: #eeeeee;
  height: 34px;
  display: flex;
  align-items: center;
}

.icon {
  margin-right: 6px;
}

/*纸张边框颜色*/
/deep/ .hiprint-printPaper.design {
  /*background: white!important;*/
  border-color: red;
}
/*元素边框颜色*/
/deep/ .design .hiprint-printElement-text-content{
  border-color: red;
}

/*table选择块颜色*/
/deep/ .design .hiprint-printElement-table-handle{
  opacity: 0.7;
  background-color: rgb(45, 140, 240);
}

/deep/ .ivu-card-head {
  padding: 7px 8px !important;
}

/deep/ .ivu-cell {
  padding: 3px 8px !important;
}

/deep/ .paper-size .ivu-cell {
  padding: 8px !important;
}

/deep/ .ivu-cell-group {
  padding: 2px 0 !important;
}

/deep/ .ivu-btn-icon-only {
  padding: 0 !important;
  font-size: 28px !important;
  width: 48px !important;
  height: 48px !important;
  border: none !important;
  outline: none !important; /*去除点击时的蓝色边框*/
  box-shadow: none !important; /*同时去除阴影的蓝色边框*/
  background: #F5F5F5;
  /*border-radius:0px!important;*/
}

/deep/ .scale .ivu-btn-icon-only {
  font-size: 24px !important;
}

/deep/ .scale .ivu-cell {
  padding: 24px 8px !important;
}

/deep/ .json .ivu-cell-main {
  width: 100% !important;
}

/deep/ .ivu-cell:hover {
  background-color: #fff !important;
}

.tools {
  height: 48px;
}

.align {
  font-size: 24px;
}

/deep/ .ivu-divider-inner-text {
  padding: 0 6px !important;
  font-size: 12px !important;
  /*font-weight: bold;*/
}

/deep/ .ivu-divider-horizontal {
  margin: 0 16px 6px 0 !important;
}

/deep/ .scale .ivu-input-number-input {
  text-align: center;
}

/deep/ .ivu-input-number-controls-outside-btn i {
  font-size: 18px;
  font-weight: bold;
}

/deep/ .hiprint-option-items {
  background-color: #f5f7f9 !important;
}

/deep/ .prop-tabs {
  background-color: #f5f7f9 !important;
}

/deep/ .prop-tabs .prop-tab-items {
  background-color: #eeeeee !important;
}

/deep/ .prop-tabs .prop-tab-items .prop-tab-item {
  background-color: #eeeeee !important;
}

/*辅助线样式*/
/deep/ .toplineOfPosition {
  border: 0;
  border-top: 1px dashed purple;
}

/deep/ .bottomlineOfPosition {
  border: 0;
  border-top: 1px dashed purple;
}

/deep/ .leftlineOfPosition {
  border: 0;
  border-left: 1px dashed purple;
}

/deep/ .rightlineOfPosition {
  border: 0;
  border-left: 1px dashed purple;
}
/*拖拽*/
/deep/ .drag_item_box {
  height: 100%;
  padding: 6px;
}

/deep/ .drag_item_box > div {
  height: 100%;
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}

/deep/ .drag_item_box > div > a {
  text-align: center;
  text-decoration-line: none;
}

/deep/ .drag_item_box > div > a > span {
  font-size: 28px;
}

/deep/ .drag_item_box > div > a > p {
  margin: 0;
}

/deep/ .drag_item_title {
  font-size: 16px;
  padding: 12px 6px 0 6px;
  font-weight: bold;
}

/*拖动元素隐藏 样式污染*/
/deep/ .hide{
  display: none!important;
}
/deep/ .del-btn{
  display: none;
}

/*修改 页眉页脚线 样式*/
/deep/ .hiprint-headerLine, /deep/.hiprint-footerLine {
  border-color: red !important;
}

/deep/ .hiprint-headerLine:hover, /deep/.hiprint-footerLine:hover {
  border-top: 3px dashed red !important;
}

/deep/ .hiprint-headerLine:hover:before {
  content: "页眉线";
  left: calc(50% - 18px);
  position: relative;
  background: #d3dbe4;
  top: -12px;
  color: red;
  font-size: 12px;
}

/deep/ .hiprint-footerLine:hover:before {
  content: "页脚线";
  left: calc(50% - 18px);
  position: relative;
  color: red;
  background: #d3dbe4;
  top: -12px;
  font-size: 12px;
}

</style>
