<script>
export default {
  name: 'EsToolbar',
  inheritAttrs: false,
  inject: {
    table: {
      default: ''
    }
  },
  props: {
    searchValue: {
      type: Object,
      default: () => {
        return {};
      }
    },
    advanceValue: {
      type: Object,
      default: () => {
        return {};
      }
    },
    contents: {
      type: Array,
      default: []
    },
    active: String,
    fixed: {
      type: Boolean,
      default: false
    },
    close: Boolean,
    callBack: {
      type: Function,
      default: () => {}
    },
    showFormBtn: {
      type: Boolean,
      default: true
    },
    small: {
      type: Boolean,
      default: true
    },
    showLabel: {
      type: Boolean,
      default: false
    },
    labelWidth: {
      type: String,
      default: 'auto'
    }
  },
  watch: {
    searchValue: {
      deep: true,
      handler(val) {
        this.searchData = JSON.parse(JSON.stringify(val));
      }
    },
    advanceValue: {
      deep: true,
      handler(val) {
        this.advancedData = JSON.parse(JSON.stringify(val));
      }
    }
  },
  data() {
    return {
      show: false,
      searchData: JSON.parse(JSON.stringify(this.searchValue)),
      advancedData: JSON.parse(JSON.stringify(this.advanceValue))
    };
  },
  created() {
    //this.traversal();
  },
  mounted() {
    this.$nextTick(() => {
      this.callBack();
    });
  },
  methods: {
    handleClick(res) {
      if (!this.table && res.event && typeof res.event === 'function') {
        res.event(res);
      } else {
        this.$emit('click', { handle: res });
      }
    },
    hanleSearch(data, multi) {
      let other = {};
      if (multi) {
        for (let i in multi) {
          other[i] = data[multi[i]];
        }
      }
      this.$emit('search', { ...data, ...other });
    },
    handleChange(key, value, data, values, items) {
      let obj = {};
      obj[key] = value;
      if (items.changeSearch) {
        this.$emit('search', values);
      }
      this.$emit('change', key, value, data, values);
    },
    hanleSubmit(data) {
      if (this.close) {
        this.show = false;
      }
      this.$emit('submit', { data: data });
    },
    handleSelect(res, num) {
      this.$emit('tabs', { item: res, index: num });
    },
    hanleReset() {
      this.reset();
      this.$emit('reset', this.searchData);
    },
    reset() {
      this.$refs.filter && this.$refs.filter.resetFields();
      this.searchData = JSON.parse(JSON.stringify(this.searchValue));
      this.advancedData = JSON.parse(JSON.stringify(this.advanceValue));
    },
    hanleCancel() {
      this.show = false;
      this.advancedData = JSON.parse(JSON.stringify(this.advanceValue));
      this.$emit('cancel', this.advancedData);
    }
  },
  render(h) {
    let text = [];
    let buttons = [];
    let search = [];
    let info = [];
    let filter = [];

    this.contents.forEach((items) => {
      let {
        config,
        type,
        reset,
        multiCondition,
        contents,
        group,
        events,
        ...other
      } = items;
      if (type === 'text') {
        text = [
          h(
            'div',
            { class: 'es-toolbar-text' },
            Array.isArray(contents)
              ? contents.map((item) => {
                  return h('span', { class: 'es-text' }, [
                    h('span', { class: 'es-info-label' }, [`${item.label}：`]),
                    h('span', { class: 'es-info-value' }, [item.value])
                  ]);
                })
              : contents
          )
        ];
      }
      if (
        type === 'button' ||
        type === 'button-group' ||
        type === 'buttonGroup'
      ) {
        if (type === 'button-group' || type === 'buttonGroup' || group) {
          buttons = [
            h('es-button-group', {
              class: 'es-toolbar-button-group',
              props: {
                moreText: '更多',
                size: 'medium',
                ...other,
                contents: contents
              },
              on: {
                handleClick: (res) => {
                  this.handleClick(res.handle);
                }
              }
            })
          ];
        } else {
          contents.forEach((item) => {
            if (!item.hide && (item.upload || (item.code && item.ownId))) {
              buttons.push(
                h('es-upload', {
                  class: 'el-button',
                  attrs: {
                    ...item,
                    method: 'post',
                    btnSize: 'medium',
                    showFileList: false,
                    selectType: item.type ? item.type : ''
                  }
                })
              );
            } else {
              buttons.push(
                h(
                  'es-button',
                  {
                    attrs: {
                      ...item,
                      size: 'medium'
                    },
                    on: {
                      click: () => {
                        this.handleClick(item);
                      }
                    }
                  },
                  item.text
                )
              );
            }
          });
        }
      }
      if (type === 'tabs') {
        buttons = buttons.concat([
          h(
            'el-menu',
            {
              props: {
                defaultActive: this.active
                  ? this.active
                  : contents[0].name
                  ? contents[0].name
                  : '0',
                mode: 'horizontal'
              },
              on: {
                select: (res) => {
                  this.handleSelect(contents[parseInt(res, 10)], res);
                }
              }
            },
            contents.map((item, index) => {
              return h(
                'el-menu-item',
                {
                  props: {
                    index: item.name ? item.name : String(index)
                  }
                },
                item.label || item.text
              );
            })
          )
        ]);
      }
      if (type === 'search') {
        for (let i = 0; i < contents.length; i++) {
          if (contents[i].type == 'selector') {
            contents[i].inputHeight = 32;
            break;
          }
        }
        let itemClass = {
          radio: 'es-toolbar-item-radio',
          checkbox: 'es-toolbar-item-checkbox',
          switch: 'es-toolbar-item-switch'
        };
        search = [
          h('es-form', {
            class: [
              'es-form-search',
              this.small ? 'es-form-search-small' : '',
              this.showLabel ? 'es-form-search-nobtn' : ''
            ],
            props: {
              size: 'medium',
              showLabel: this.showLabel,
              labelWidth: this.labelWidth,
              closeDialog: false,
              model: this.searchData,
              contents: contents,
              itemClass: itemClass,
              inline: true,
              search: true,
              isReset: reset,
              showButton: this.showFormBtn,
              ...other,
              ...(config || {})
            },
            on: {
              submit: (data) => {
                this.hanleSearch(data, multiCondition);
              },
              reset: this.hanleReset,
              change: this.handleChange
            }
          })
        ];
      }
      if (type === 'info') {
        info.push(
          h(
            'div',
            { class: 'es-toolbar-info' },
            contents.map((item) => {
              return h('span', { class: 'es-info' }, [
                h('span', { class: 'es-info-label' }, [`${item.label}：`]),
                h('span', { class: 'es-info-value' }, [item.value])
              ]);
            })
          )
        );
      }
      if (type === 'filter') {
        info.push(
          h(
            'el-button',
            {
              class: 'es-advanced-btn',
              props: {
                type: 'primary',
                size: 'medium'
              },
              on: {
                click: () => {
                  this.show = !this.show;
                }
              }
            },
            [
              '高级搜索',
              h('i', {
                class: {
                  'el-icon-arrow-down': !this.show,
                  'el-icon-arrow-up': this.show,
                  'es-advanced-icon': 1
                }
              })
            ]
          )
        );
        filter = h(
          'transition',
          {
            props: {
              name: 'el-zoom-in-top'
            }
          },
          [
            h(
              'div',
              {
                class: {
                  'es-absolute': !this.fixed,
                  'es-advanced-filter': 1
                },
                directives: [
                  {
                    name: 'show',
                    value: this.show
                  }
                ]
              },
              [
                this.show
                  ? h(
                      'es-form',
                      {
                        class: 'es-form-advanced-filter',
                        ref: 'filter',
                        props: {
                          ...other,
                          ...(config || {}),
                          size: 'medium',
                          closeDialog: false,
                          model: this.advancedData,
                          contents: contents
                        },
                        on: events
                          ? events
                          : {
                              submit: this.hanleSubmit,
                              reset: this.hanleCancel
                            }
                      },
                      []
                    )
                  : ''
              ]
            )
          ]
        );
      }
    });
    let box = [
      h(
        'div',
        {
          class: 'es-button-content'
        },
        buttons
      )
    ];
    let dom;
    if (text.length) {
      dom = text.concat(box, search, info);
    } else {
      dom = box.concat(search, info);
    }
    return h(
      'div',
      {
        class: 'es-toolbar'
      },
      [
        h(
          'div',
          {
            class: 'es-toolbar-content'
          },
          dom
        ),
        filter
      ]
    );
  }
};
</script>
