
export default (editor, options) => {
    editor.TraitManager.addType('csvDownload', {
        events: {
          'click button': 'handleClick'
        },

        handleClick() {
            const {model} = this;
            const fileName = `${model.get('preFileName')}_示例数据.csv`;
            const dataStr = this._convertToCSV(model.get('datas'), model.get('dataType'));

            const link = document.createElement('a');
            link.style.display = 'none';
            link.href = window.URL.createObjectURL(new Blob([dataStr], {type: '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'}));
            link.setAttribute('download', fileName);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        },

        getInputEl() {
            if (!this.$input) {
                const { model, ppfx } = this;
                const className = `${ppfx}csv-button`;
                const input = `<div class=${className}><button class="${ppfx}btn-prim">查看</button>`;
                this.input = input;
                this.$input = $(input);
            }
            return this.$input.get(0);
        },

        renderField() {
            if (!this.$input) {
                this.getInputEl();
                this.$el.find('.' + this.ppfx + 'field-wrp').html(this.input);
              }
        },

        _convertToCSV(arr, dataType) {
            let str = '';
            if (dataType === 'gauge') {
                const keys = Object.keys(arr[0]);
                str+=keys.join(',');
                str+='\r\n';
                arr.forEach(data => {
                    keys.forEach(key => {
                        str += `${data[key]},`;
                    });
                    str+='\r\n';
                });
                return str
            }

            arr.forEach(data => {
                str += data.valueOf() + '\r\n';
            });
            return str;
        }
    })
}