<template>
  <div class="x-print" :class="classes">
    <Dropdown class="x-print__dropdown"
              :split-button="isSplitButton"
              :placement="placement"
              :type="type"
              :disabled="disabled"
              @click="handleButtonClick"
              @command="handleCommand">
      <ElButton v-if="disabled || !splitButton"
                :icon="icon"
                :type="type"
                :disabled="disabled"
                @click="handleButtonClick">{{text}}
        <i v-if="hasTemplate" class="el-icon-arrow-down el-icon--right"></i></ElButton>
      <span v-else>
        <i v-if="icon" :class="icon"></i>
        {{text}} </span>
      <DropdownMenu class="x-print__menu" :class="{'is-empty':!hasTemplate}" slot="dropdown">
        <DropdownItem v-for="(item,index) in items"
                      :key="`${item.code}_${index}`"
                      :command="item"
                      v-bind="item"
                      class="x-print__item">
          <span>{{item.label}}</span>
          <span class="x-print__tools">
          <i class="el-icon-view" title="打印预览" @click.stop="handlePreview(item)"></i>
          <i class="el-icon-printer" title="选择打印机" @click.stop="handlePrinter(item)"></i>
            </span>
        </DropdownItem>
      </DropdownMenu>
    </Dropdown>
  </div>
</template>

<script>
/**
 *  打印按钮
 * @module XPrint
 *
 */
import {
  Button as ElButton,
  Dropdown,
  DropdownMenu,
  DropdownItem
} from 'element-ui';

export default {
  name: 'XPrint',
  components: {
    ElButton,
    Dropdown,
    DropdownMenu,
    DropdownItem
  },
  /**
   * 属性参数
   * @member props
   * @property {string} [icon] 图标样式
   * @property {boolean} [splitButton] 分隔按钮模式
   * @property {object[]} [items] 模板选项数组
   * @property {string} [items.label] 显示文本
   * @property {string} [items.code] 模板编码
   * @property {boolean} [items.disabled] 禁用
   * @property {string} [placement=bottom-start] 下拉层显示位置
   * @property {string} [text=打印] 按钮文本
   * @property {boolean} [disabled] 禁用
   * @property {string} [docCode] 打印文档编码
   * @property {string} [localApi=http://127.0.0.1:58081/print.do] 本地服务接口地址
   * @property {string} [pluginHost] 插件服务端接口主机，默认当前访问的页面host，带协议
   * @property {string} [pluginPath=/api/wbs/pluginPrint/wbsWeight] 插件服务端接口路径
   * @property {boolean} [printFirst] 开启点击按钮打印第一个模板
   * @property {object|Function} [params] 附件参数数据
   * @property {number} [paramType] 类型
   * @property {Object} [headers] 附加接口请求头
   * @property {Function} [validate] 验证函数，需要返回Promise
   * @property {boolean} [checkPrint] 是否检查打印
   * @property {boolean} [showExport=true] 预览是否支持导出
   */
  props: {
    icon: {
      type: String
    },
    splitButton: {
      type: Boolean,
      default: false
    },
    items: {
      type: Array
    },
    placement: {
      type: String,
      default: 'bottom-start'
    },
    text: {
      type: String,
      default: '打印'
    },
    type: {
      type: String,
      default: 'primary'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    docCode: {
      type: String,
      default: ''
    },
    localApi: {
      type: String,
      default: 'http://127.0.0.1:58081/print.do'
    },
    pluginHost: {
      type: String
    },
    pluginPath: {
      type: String,
      default: '/api/wbs/auth/pluginPrint/wbsWeight'
    },
    printFirst: Boolean,
    params: {
      type: [Object, Function]
    },
    paramType: {
      type: Number
    },
    headers: Object,
    validate: Function,
    checkPrint: Boolean,
    showExport: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      value: ''
    };
  },
  computed: {
    isSplitButton() {
      return this.disabled === true ? false : this.splitButton;
    },
    hasTemplate() {
      return this.items && this.items.length > 0;
    },
    classes() {
      return {
        'is-disabled': this.disabled
      };
    }
  },
  methods: {
    createIframe(url, onload) {
      if (!this.iframe) {
        this.iframe = document.createElement('iframe');
        this.iframe.style.display = 'none';
      }
      this.iframe.src = url;
      this.iframe.onload = () => {
        onload && onload(this.iframe);
        this.iframe.onload = null;
      };
      this.$el.appendChild(this.iframe);
    },
    async localPrint(opts) {
      const { docCode, templateCode, preview = false, printer = false } = opts || {};
      if (this.validate) {
        const valid = await this.validate(opts, this);
        if (!valid) return;
      }
      const { protocol, host, pathname } = location;
      const pluginHost = this.pluginHost ? this.pluginHost : `${protocol}//${host}`;
      const url = `${pluginHost}${this.pluginPath}?docCode=${docCode}&templateCode=${templateCode}`;
      let api = `${this.localApi}?url=${encodeURIComponent(url)}&preview=${preview}&showPrintDlg=${printer}`;
      const params = this.params;
      const queryParams = typeof params === 'function' ? await params(opts) : params;
      if (queryParams) {
        api += `&queryParams=${JSON.stringify(queryParams)}`;
      }
      if (this.paramType !== undefined) {
        api += `&type=${this.paramType}`;
      }
      if (this.checkPrint) {
        api += '&checkPrint=true';
      }
      if (!this.showExport) {
        api += '&showExport=false';
      }
      const domain = encodeURIComponent(pluginHost + pathname);
      api += `&domain=${domain}`;
      const headers = this.headers || {};
      const token = this.$access?.getToken() || '';
      if (token) {
        headers.Token = token;
      }
      return fetch(api, {
        headers: new Headers(headers)
      }).then(res => {
        return res.json();
      }).then(res => {
        if (!res.success) {
          this.$notify.error(res.msg);
        }
        return res;
      }).catch(e => {
        this.$notify.error('您的电脑还没安装打印插件或插件没启动，请与管理员联系！');
      });
    },
    handleCommand(item) {
      this.localPrint({
        docCode: this.docCode,
        templateCode: item.code,
        preview: false,
        printer: false
      });
    },
    handleButtonClick() {
      if (this.printFirst && this.hasTemplate) {
        const item = this.items[0];
        this.handleCommand(item);
      }
      this.$emit('click');
    },
    async handlePreview(item) {
      return this.localPrint({
        docCode: this.docCode,
        templateCode: item.code,
        preview: true,
        printer: false
      });
    },
    handlePrinter(item) {
      return this.localPrint({
        docCode: this.docCode,
        templateCode: item.code,
        preview: false,
        printer: true
      });
    }
  },
  beforeDestroy() {
    if (this.iframe) {
      this.iframe.onload = null;
      this.iframe.parentNode.removeChild(this.iframe);
      this.iframe = null;
    }
  }
};
</script>

<style scoped>

</style>
