<script>
import util from 'eoss-ui/src/utils/util';
export default {
  name: 'EsButton',
  inject: {
    esSelect: {
      default: ''
    },
    esForm: {
      default: ''
    },
    esTable: {
      default: ''
    },
    btnGroup: {
      default: ''
    }
  },
  props: {
    data: {},
    icon: String,
    iconPlacement: {
      type: String,
      default: 'start'
    },
    link: String,
    hide: Boolean,
    param: Object,
    type: String,
    mold: String,
    size: String,
    open: Boolean,
    reload: Boolean,
    name: {
      type: String,
      default: ''
    },
    specs: [Boolean, String],
    required: [String, Array, Object],
    fields: [String, Array, Object],
    message: [Object, Boolean],
    alert: [Object, Boolean],
    mapFields: Object,
    useCaseCode: String,
    closed: Function,
    stop: Boolean,
    syncKeys: Object,
    text: String,
    onClick: Function,
    badge: [Object, Number, Function],
    float: String,
    selector: Boolean,
    upload: Boolean,
    outside: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    _type() {
      return this.type ? this.type : this.mold;
    }
  },
  data() {
    return {};
  },
  methods: {
    handleClick(evt) {
      if (this.onClick) {
        this.onClick(evt);
      } else {
        if (this.open && this.link) {
          let windows;
          let fields = [];
          let param = this.param ? this.param : {};
          evt.stopPropagation();
          evt.preventDefault();
          let width = 0;
          let height = 0;
          width = util.win.screen.availWidth - 10;
          height = util.win.screen.availHeight - 60;
          let flag = true;
          if (this.esForm) {
            let params = util.getParams({ url: this.link });
            let modal = this.esForm.models;
            let models = util.extend({}, params || {}, modal);
            if (this.required) {
              if (Array.isArray(this.required)) {
                this.esForm.validateField(this.required, (res) => {
                  if (res) {
                    flag = false;
                  } else {
                    flag = true;
                  }
                });
                if (flag) {
                  fields = this.required;
                  this.required.forEach((item) => {
                    param[item] = models[item];
                  });
                }
              } else if (typeof this.required === 'object') {
                for (let i in this.required) {
                  fields.push(this.required[i]);
                  param[i] = models[this.required[i]];
                }
                this.esForm.validateField(fields, (res) => {
                  if (res) {
                    flag = false;
                  } else {
                    flag = true;
                  }
                });
              } else {
                this.esForm.validateField(this.required, (res) => {
                  if (res) {
                    flag = false;
                  } else {
                    flag = true;
                  }
                });
                if (flag) {
                  fields = this.required;
                  if (
                    models[this.required] == null ||
                    models[this.required] == undefined ||
                    models[this.required] == ''
                  ) {
                    param[this.required] = models[this.required];
                  }
                }
              }
            }
            if (this.fields) {
              let empty = [];
              if (Array.isArray(this.fields)) {
                this.fields.forEach((item) => {
                  if (models[item] == undefined || models[item] == '') {
                    empty.push(item);
                  }
                  param[item] = models[item];
                });
              } else if (typeof this.fields === 'object') {
                for (let i in this.fields) {
                  if (
                    models[this.fields[i]] == undefined ||
                    models[this.fields[i]] == ''
                  ) {
                    empty.push(this.fields[i]);
                  }
                  param[i] = models[this.fields[i]];
                }
              } else {
                if (
                  models[this.fields] == undefined ||
                  models[this.fields] == ''
                ) {
                  empty.push(this.fields);
                }
                param[this.fields] = models[this.fields];
              }
              if (empty.length) {
                let msg = [];
                if (this.mapFields) {
                  empty.forEach((item) => {
                    msg.push(this.mapFields[item]);
                  });
                } else {
                  msg = empty;
                }
                if (this.message) {
                  flag = false;
                  if (typeof this.message == 'boolean') {
                    this.$message.error(msg.join(',') + '不能为空！');
                  } else {
                    let message =
                      msg.join(',') + (this.message.message || '不能为空！');
                    this.$message({
                      type: 'error',
                      ...this.message,
                      message: message
                    });
                  }
                }
                if (this.alert) {
                  flag = false;
                  if (typeof this.alert == 'boolean') {
                    this.$alert(msg.join(',') + '不能为空！', '提示', {
                      type: 'error',
                      confirmButtonText: '确定'
                    }).catch();
                  } else {
                    let message =
                      msg.join(',') + (this.alert.message || '不能为空！');
                    this.$alert(
                      message,
                      this.alert.titl || '提示',
                      this.alert.config || {
                        type: 'error',
                        confirmButtonText: '确定'
                      }
                    ).catch();
                  }
                }
              }
            }
          }
          if (this.btnGroup && this.syncKeys) {
            let data = this.btnGroup.data;
            if (
              data &&
              Object.keys(data).length &&
              Object.keys(this.syncKeys).length
            ) {
              for (let i in this.syncKeys) {
                param[i] = data[this.syncKeys[i]];
              }
            }
          }
          if (flag) {
            if (this.specs) {
              if (typeof this.specs === 'boolean') {
                windows = util.win.open(
                  util.urlJoinParams({ url: this.link, param: param }),
                  this.name,
                  `width=${width}px,height=${height}px,resizable=yes,status=yes,menubar=no,scrollbars=yes`
                );
              } else {
                windows = util.win.open(
                  util.urlJoinParams({ url: this.link, param: param }),
                  this.name,
                  this.specs
                );
              }
            } else {
              windows = util.win.open(
                util.urlJoinParams({ url: this.link, param: param })
              );
            }
          }
          if (windows) {
            let times = setInterval(() => {
              if (windows.closed) {
                clearInterval(times);
                this.closed && this.closed(param);
                if (this.reload) {
                  this.esSelect && this.esSelect.reload(null, param, true);
                  this.esTable && this.esTable.reload(param);
                }
              }
            }, 1000);
          }
        } else if (this.stop) {
          evt.stopPropagation();
          evt.preventDefault();
        }
        this.$emit('click', evt, this.text);
      }
    }
  },
  render(h) {
    let useCaseCodes = util.getStorage('useCaseCodes');
    if (useCaseCodes && this.useCaseCode) {
      if (useCaseCodes.indexOf(this.useCaseCode) == -1) {
        return false;
      }
    }
    let tag = 'el-button';
    let clas = '';
    let props = {};
    let attrs = {};
    let listeners = {};
    let config = {};
    let badgeConfig;
    if (this.selector) {
      tag = 'es-selector';
      props = {
        reset: true,
        ...this.$attrs,
        button: { type: this._type, size: this.size }
      };
      listeners = this.$listeners;
    } else if (this.upload) {
      tag = 'es-upload';
      props = { ...this.$attrs, showFileList: false };
      listeners = this.$listeners;
      config = {
        type: this._type,
        size: this.size
      };
    } else {
      clas = ['es-button'];
      props = { ...this.$attrs, type: this._type, size: this.size };
      listeners = { ...this.$listeners, click: this.handleClick };
      if (this.link && !this.open) {
        const link = this.param
          ? util.urlJoinParams({ url: this.link, param: this.param })
          : this.link;
        attrs = { href: link };
        tag = 'a';
        clas = clas.concat([
          'el-button',
          this._type ? `el-button--${this._type}` : 'el-button--default',
          this.size ? `el-button--${this.size}` : '',
          this.float ? `es-button--${this.float}` : ''
        ]);
      }
      if (this.badge) {
        if (typeof this.badge === 'number') {
          badgeConfig = {
            class: 'es-button-badge',
            props: { value: this.badge }
          };
        } else if (typeof this.badge === 'function') {
          let badge = this.badge(this.data);
          if (badge) {
            if (typeof badge === 'number') {
              badgeConfig = {
                class: 'es-button-badge',
                props: { value: badge }
              };
            } else {
              let { value, max, isDot, hidden, type } = badge;
              badgeConfig = {
                class: this.badge.class
                  ? this.badge.class + ' es-button-badge'
                  : 'es-button-badge',
                props: { value, max, isDot, hidden, type }
              };
            }
          }
        } else {
          let { value, max, isDot, hidden, type } = this.badge;
          badgeConfig = {
            class: this.badge.class
              ? this.badge.class + ' es-button-badge'
              : 'es-button-badge',
            props: { value, max, isDot, hidden, type }
          };
        }
        if (badgeConfig && Object.keys(badgeConfig).length && this.outside) {
          return h('el-badge', badgeConfig, [
            h(
              tag,
              {
                class: clas,
                props: { ...this.$attrs, ...props },
                attrs: attrs,
                on: { ...this.$listeners, click: this.handleClick },
                directives: [
                  {
                    name: 'show',
                    value: !this.hide
                  }
                ]
              },
              this.iconPlacement === 'start'
                ? [
                    this.icon ? h('i', { class: this.icon }) : '',
                    this.$slots.default || this.text
                  ]
                : [
                    this.$slots.default || this.text,
                    this.icon ? h('i', { class: this.icon }) : ''
                  ]
            )
          ]);
        }
      }
    }
    return h(
      tag,
      {
        class: clas,
        props: props,
        attrs: attrs,
        on: listeners,
        directives: [
          {
            name: 'show',
            value: !this.hide
          }
        ]
      },
      [
        ...(this.iconPlacement === 'start'
          ? [
              this.icon ? h('i', { class: this.icon }) : '',
              this.upload
                ? h(
                    'el-button',
                    {
                      props: config
                    },
                    [this.$slots.default || this.text]
                  )
                : this.$slots.default || this.text
            ]
          : [
              this.upload
                ? h(
                    'el-button',
                    {
                      props: config
                    },
                    [this.$slots.default || this.text]
                  )
                : this.$slots.default || this.text,
              this.icon ? h('i', { class: this.icon }) : ''
            ]),
        !this.outside && badgeConfig && Object.keys(badgeConfig).length
          ? h('el-badge', badgeConfig)
          : ''
      ]
    );
  }
};
</script>
