"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
var d3 = require("d3");
var D3Chart_1 = require("../D3Chart");
var _ = require("lodash");
var common_1 = require("../common");
var StackWidth = 16;
var default_1 = /** @class */ (function (_super) {
    __extends(default_1, _super);
    function default_1() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.__ClassName = '_vc_bar_multi_hori';
        _this.__Grid = {
            top: 12,
            left: 80,
            right: 24,
            bottom: 30,
        };
        _this.min = 0;
        _this.max = 0;
        _this.maxCount = 15;
        _this.widthScale = null;
        _this.heightScale = null;
        _this.legend = null;
        _this.SelectedKeys = null;
        _this.keyMap = new Map();
        _this.currentIndex = -1;
        return _this;
    }
    default_1.prototype.sort = function () {
        var _a;
        var _this = this;
        if (this.SelectedKeys === null) {
            this.SelectedKeys = _.concat([], this.props.valueFields);
        }
        var data = this.props.data.map(function (item) {
            item.__sum = 0;
            item.__total = 0;
            _this.props.valueFields.map(function (field) {
                item.__sum += item[field];
            });
            _this.SelectedKeys.map(function (field) {
                item.__total += item[field];
            });
            return item;
        });
        this.DATA = _.orderBy(data, function (d) { return d.__total; }, 'desc');
        if (this.DATA.length > this.maxCount) {
            this.DATA.length = this.maxCount;
        }
        _a = __read(this.extent(this.DATA, function (d) { return d.__total; }), 2), this.min = _a[0], this.max = _a[1];
        this.max = common_1.DefUtil.fixMax(this.max);
        this.widthScale = d3.scaleBand().rangeRound([0, this.LAYOUT.w])
            .domain(this.DATA.map(function (item) { return item[_this.props.labelField]; }));
        this.heightScale = d3.scaleLinear().rangeRound([this.LAYOUT.h, 0])
            .domain([0, this.max]).nice();
        this.DATA = d3.stack().keys(this.SelectedKeys)(this.DATA);
    };
    default_1.prototype.resize = function () {
        this.SVG.select("g._x_axis")
            .transition().duration(this.DURATION)
            .attr("transform", "translate(" + this.LAYOUT.x + "," + (this.LAYOUT.y + this.LAYOUT.h) + ")");
        this.SVG.select("g._y_axis")
            .attr("transform", "translate(" + this.LAYOUT.x + "," + this.LAYOUT.y + ")");
        this.SVG.select("g._axis_line")
            .transition().duration(this.DURATION)
            .attr("transform", "translate(" + this.LAYOUT.x + "," + this.LAYOUT.y + ")");
        if (this.props.legend && this.props.legend.show) {
            var legWidth = this.props.legend.width || 200;
            this.SVG.select('g._legends')
                .transition().duration(this.DURATION)
                .attr("transform", "translate(" + (this.LAYOUT.x + this.LAYOUT.w - legWidth) + "," + this.LAYOUT.y + ")");
        }
        this.widthScale.rangeRound([0, this.LAYOUT.w]);
        this.heightScale.rangeRound([this.LAYOUT.h, 0]);
        this.update();
    };
    default_1.prototype.build = function () {
        var _this = this;
        this.SVG.append("g")
            .attr("class", "_x_axis")
            .attr("transform", "translate(" + this.LAYOUT.x + "," + (this.LAYOUT.y + this.LAYOUT.h) + ")");
        this.SVG.append("g")
            .attr("class", "_y_axis")
            .attr("transform", "translate(" + this.LAYOUT.x + "," + this.LAYOUT.y + ")");
        this.SVG.append("g")
            .attr("class", "_axis_line")
            .attr("transform", "translate(" + this.LAYOUT.x + "," + this.LAYOUT.y + ")");
        this.SVG.append('g').attr('class', '_container')
            .attr("transform", "translate(" + this.LAYOUT.x + "," + this.LAYOUT.y + ")");
        if (this.props.legend && this.props.legend.show) {
            var legWidth = this.props.legend.width || 200;
            var group = this.SVG.append('g')
                .attr("class", "_legends")
                .attr("transform", "translate(" + (this.LAYOUT.x + this.LAYOUT.w - legWidth) + "," + this.LAYOUT.y + ")");
            this.legend = new common_1.Legend(group, 1, function (SelectedKeys) {
                _this.SelectedKeys = SelectedKeys;
                _this.sort();
                _this.update();
            }, legWidth, this.DURATION);
        }
        this.update();
    };
    default_1.prototype.updateLegend = function () {
        var _this = this;
        var legendMap = {};
        this.props.valueFields.map(function (field, i) { return legendMap[field] = { value: _.sumBy(_this.props.data, field), label: _this.props.labels[i] }; });
        var legends = [];
        _.keys(legendMap).map(function (key) {
            legends.push({
                key: key,
                label: legendMap[key].label,
                value: legendMap[key].value,
            });
        });
        legends = _.orderBy(legends, 'value', 'desc');
        this.legend.update(legends);
    };
    default_1.prototype.getIndex = function (key) {
        // console.log(key);
        // console.log(this.legend);
        // console.log(this.keyMap)
        // if(this.legend){
        // return this.legend.getIndex(key);
        // }
        return this.keyMap.get(key);
    };
    default_1.prototype.update = function () {
        var _this = this;
        var container = this.SVG.select('g._container');
        var band = this.widthScale.bandwidth();
        var diff = (band - StackWidth) / 2;
        this.keyMap.clear();
        this.DATA.map(function (item, i) { return _this.keyMap.set(item.key, i); });
        var series = container.selectAll("g._series").data(this.DATA, function (d) { return d['key']; });
        series.attr("class", function (d) { return "_series _series_" + _this.getIndex(d['key']); })
            .classed('_item_hover', this.props.onClick != undefined);
        var seriesAdd = series
            .enter().append("g")
            .attr("class", function (d) { return "_series _series_" + _this.getIndex(d['key']); })
            .classed('_item_hover', this.props.onClick != undefined);
        //这段代码有问题，后续要使用merge简化
        var newRects = seriesAdd.selectAll("rect")
            .data(function (d) { return d; }, function (d) { return d['key']; }).enter()
            .append("rect")
            .attr('class', function (d, i) { return "_item_rect _item_rect_" + i; })
            .attr("x", function (d, i) { return band * i + diff; })
            .attr("y", function (d) { return _this.heightScale(d[0]); })
            .attr("width", StackWidth)
            .attr("height", 0);
        var rects = series.selectAll("rect")
            .data(function (d) { return d; }, function (d) { return d['key']; })
            .attr('class', function (d, i) { return "_item_rect _item_rect_" + i; });
        var rectAdd = rects.enter()
            .append("rect")
            .attr('class', function (d, i) { return "_item_rect _item_rect_" + i; })
            .attr("x", function (d, i) { return band * i + diff; })
            .attr("y", function (d) { return _this.heightScale(d[0]); })
            .attr("width", StackWidth)
            .attr("height", 0);
        rectAdd.transition()
            .duration(this.DURATION)
            .attr('y', function (d) { return _this.heightScale(d[1]); })
            .attr('height', function (d) { return _this.heightScale(d[0]) - _this.heightScale(d[1]); });
        newRects.transition()
            .duration(this.DURATION)
            .attr('y', function (d) { return _this.heightScale(d[1]); })
            .attr('height', function (d) { return _this.heightScale(d[0]) - _this.heightScale(d[1]); });
        rects.transition()
            .duration(this.DURATION)
            .attr("x", function (d, i) { return band * i + diff; })
            .attr('y', function (d) { return _this.heightScale(d[1]); })
            .attr('height', function (d) { return _this.heightScale(d[0]) - _this.heightScale(d[1]); });
        rects.exit().remove();
        series.exit().remove();
        rectAdd.on('mouseover', function (d, i) {
            container.selectAll('rect._item_rect').classed('active', false);
            container.selectAll('rect._item_rect_' + i).classed('active', true);
            // @ts-ignore
            var valField = _this.props.valueFields[_this.getIndex(d3.select(d3.select(d3.event.srcElement).node().parentNode).data()[0].key)];
            if (_.has(_this.props, 'tip')) {
                common_1.ToolTip.show(_this.props.tip(d.data, valField));
            }
            else {
                common_1.ToolTip.show("<h2>" + _this.FormatLabel(d.data[_this.props.labelField]) + "\n                    " + _this.props.valueFields.map(function (key, i) {
                    return "<p class=\"" + (key == valField ? 'high' : '') + "\">" + _this.props.labels[i] + ":<span class=\"vapfont\">" + (d.data[key] || 0) + "</span></p>";
                }).join('') + "\n                </h2>");
            }
        }).on('mouseout', function () {
            container.selectAll('rect._item_rect').classed('active', false);
            if (_this.currentIndex >= 0) {
                container.selectAll('rect._item_rect_' + _this.currentIndex).classed('active', true);
            }
            common_1.ToolTip.hide();
        });
        newRects.on('mouseover', function (d, i) {
            container.selectAll('rect._item_rect').classed('active', false);
            container.selectAll('rect._item_rect_' + i).classed('active', true);
            // @ts-ignore
            var valField = _this.props.valueFields[_this.getIndex(d3.select(d3.select(d3.event.srcElement).node().parentNode).data()[0].key)];
            if (_.has(_this.props, 'tip')) {
                common_1.ToolTip.show(_this.props.tip(d.data, valField));
            }
            else {
                common_1.ToolTip.show("<h2>" + _this.FormatLabel(d.data[_this.props.labelField]) + "\n                    " + _this.props.valueFields.map(function (key, i) {
                    return "<p class=\"" + (key == valField ? 'high' : '') + "\">" + _this.props.labels[i] + ":<span class=\"vapfont\">" + (d.data[key] || 0) + "</span></p>";
                }).join('') + "\n                </h2>");
            }
        }).on('mouseout', function () {
            container.selectAll('rect._item_rect').classed('active', false);
            if (_this.currentIndex >= 0) {
                container.selectAll('rect._item_rect_' + _this.currentIndex).classed('active', true);
            }
            common_1.ToolTip.hide();
        });
        if (this.props.onClick) {
            newRects.on('click', function (d, i) {
                if (_this.props.doubleCancel && _this.currentIndex == i) {
                    _this.currentIndex = -1;
                    _this.props.onClick(null);
                    container.selectAll('rect._item_rect_' + _this.currentIndex).classed('active', false);
                    return;
                }
                _this.currentIndex = i;
                // @ts-ignore
                var valField = _this.props.valueFields[_this.getIndex(d3.select(d3.select(d3.event.srcElement).node().parentNode).data()[0].key)];
                _this.props.onClick(d.data, valField);
                container.selectAll('rect._item_rect_' + _this.currentIndex).classed('active', true);
            });
            rectAdd.on('click', function (d, i) {
                if (_this.props.doubleCancel && _this.currentIndex == i) {
                    _this.currentIndex = -1;
                    _this.props.onClick(null);
                    container.selectAll('rect._item_rect_' + _this.currentIndex).classed('active', false);
                    return;
                }
                _this.currentIndex = i;
                // @ts-ignore
                var valField = _this.props.valueFields[_this.getIndex(d3.select(d3.select(d3.event.srcElement).node().parentNode).data()[0].key)];
                _this.props.onClick(d.data, valField);
                container.selectAll('rect._item_rect_' + _this.currentIndex).classed('active', true);
            });
        }
        if (this.props.legend && this.props.legend.show) {
            this.updateLegend();
        }
        series.exit().remove();
        this.SVG.select('g._x_axis').call(d3.axisBottom(this.widthScale).tickSize(1).tickFormat(function (e) { return _this.FormatLabel(e); }));
        this.SVG.select('g._y_axis').call(d3.axisLeft(this.heightScale).ticks(3).tickSize(0).tickFormat(function (e) { return _this.FormatValue(e); }));
        this.SVG.select('g._axis_line').call(d3.axisLeft(this.heightScale).ticks(3).tickSize(-this.LAYOUT.w).tickFormat(function () { return ''; }));
    };
    return default_1;
}(D3Chart_1.default));
exports.default = default_1;
