"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;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
var D3Chart_1 = require("../D3Chart");
var d3 = require("d3");
var _ = require("lodash");
var moment = require("moment");
var common_1 = require("../common");
/**
 * 日期趋势
*/
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_line_datetrend';
        _this.__Grid = { left: 30, right: 30, top: 12, bottom: 16 };
        _this.type = 'line';
        _this.marginLeft = 0; //左Label宽度
        _this.showYAxis = false;
        _this.dateFormat = 'YYYY-MM-DD';
        _this.dates = [];
        _this.dataMap = new Map();
        _this.labelRotate = 0;
        _this.itemWidth = 0; // 一格的大小
        _this.barWidth = 12; // 一列的大小，最大为12
        _this.widthScale = null;
        _this.heightScale = null;
        _this.lineTween = null;
        return _this;
    }
    default_1.prototype.init = function () {
        this.type = this.props.type || 'line';
        if (this.props.showYAxis) {
            this.showYAxis = true;
            this.marginLeft = this.props.marginLeft || 30;
        }
        this.dateFormat = this.props.dateFormat || 'YYYY-MM-DD';
        this.labelRotate = this.props.labelRotate || 0;
    };
    default_1.prototype.sort = function () {
        var _a, _b;
        var _this = this;
        var _c = __read([this.props.start, this.props.end], 2), start = _c[0], end = _c[1];
        if (end === undefined) {
            _a = __read(common_1.DateUtil.toRange(start), 2), start = _a[0], end = _a[1];
        }
        this.dates = common_1.DateUtil.dateArr(start, end, this.dateFormat);
        this.dataMap.clear();
        this.dates.map(function (item) { return _this.dataMap.set(item, { value: 0 }); });
        this.props.data.map(function (item) {
            var key = moment(item[_this.props.labelField]).format(_this.dateFormat);
            if (_this.dataMap.has(key)) {
                var obj = _this.dataMap.get(key);
                obj.value = item[_this.props.valueField];
                obj.data = item;
                _this.dataMap.set(key, obj);
            }
        });
        this.DATA = __spread(this.dataMap.keys()).map(function (key) { return { label: key, value: _this.dataMap.get(key).value, data: _this.dataMap.get(key).data || {} }; });
        this.DATA = _.orderBy(this.DATA, 'label', 'asc');
        var _d = __read([0, 1], 2), min = _d[0], max = _d[1];
        if (this.props.data.length > 0) {
            _b = __read(d3.extent(this.props.data, function (item) { return item[_this.props.valueField]; }), 2), min = _b[0], max = _b[1];
            if (min == max) {
                min = 0;
            }
            if (max == 0) {
                max = 1;
            }
        }
        this.widthScale = d3.scaleLinear().domain([0, this.DATA.length]).range([0, this.LAYOUT.w]);
        this.heightScale = d3.scaleLinear().domain([max, 0]).range([this.LAYOUT.h, 0]);
        this.itemWidth = this.LAYOUT.w / this.DATA.length;
        // this.widthScale.
        // this.itemWidth = this.widthScale.barWidth(); 
        // this.barWidth = this.itemWidth > this.barWidth ? this.barWidth : this.itemWidth;
        // this.diff = (this.itemWidth - this.barWidth) / 2;
    };
    default_1.prototype.build = function () {
        this.SVG.append('defs').html(common_1.DefUtil.BuildLineDistribution());
        this.SVG.append('g').attr('class', '_line')
            .attr('transform', "translate(" + (this.LAYOUT.x + this.marginLeft) + "," + this.LAYOUT.y + ")")
            .append('path');
        this.SVG.append('g').attr('class', '_items')
            .attr('transform', "translate(" + (this.LAYOUT.x + this.marginLeft) + "," + this.LAYOUT.y + ")")
            .classed('_group_hover', this.props.onClick ? true : false);
        this.SVG.append("g")
            .attr("class", "_x_axis")
            .attr("transform", "translate(" + (this.LAYOUT.x + this.marginLeft) + "," + (this.LAYOUT.h + this.LAYOUT.y) + ")");
        this.SVG.append("g")
            .attr("class", "_y_axis")
            .attr("transform", "translate(" + (this.LAYOUT.x + this.marginLeft) + "," + this.LAYOUT.y + ")");
        this.update();
    };
    default_1.prototype.updateLine = function () {
        var _this = this;
        var lineTween = function (t) { return d3.line()
            .curve(d3.curveMonotoneX)
            .x(function (d, i) { return _this.itemWidth * i; })
            .y(function (d, i) { return _this.LAYOUT.h - (_this.heightScale(d['value'])) * t; }); };
        this.SVG.select('g._line path').datum(this.DATA)
            .transition()
            .duration(this.DURATION)
            .attrTween('d', function (d) { return function (t) { return lineTween(t)(d); }; });
    };
    default_1.prototype.updateArea = function () {
    };
    default_1.prototype.updateBar = function () {
        var _this = this;
        var group = this.SVG.select('g._items').selectAll('g._item').data(this.DATA, function (d) { return d['label']; });
        var enter = group.enter().append('g').attr('class', '_item');
        enter.append('rect')
            .merge(group.select('rect'))
            .attr('x', function (d, i) { return -_this.barWidth / 2 + _this.itemWidth * i; })
            .transition()
            .duration(this.DURATION)
            .attr('width', this.barWidth)
            // @ts-ignore
            .attrTween('y', function (d) { return function (t) { return _this.LAYOUT.h - t * _this.heightScale(d['value']); }; })
            // @ts-ignore
            .attrTween('height', function (d) { return function (t) { return t * _this.heightScale(d['value']); }; });
        if (this.props.onClick) {
            enter.on('click', function (d, i, u) {
                if (d['data']) {
                    enter.classed('_item_selected', false);
                    d3.select(u[i]).classed('_item_selected', true);
                    _this.props.onClick(d['label'], d['data']);
                }
            });
        }
        if (this.props.defSelect) {
            enter.classed('_item_selected', function (d) { return d['label'] == _this.props.defSelect; });
        }
        enter.on('mouseover', function (d) {
            if (d['data']) {
                if (_this.props.tip) {
                    common_1.ToolTip.show(_this.props.tip(d['data']));
                }
                else {
                    common_1.ToolTip.show("<h2 class=\"vapfont\">" + d['label'] + " : " + d['value'] + "</h2>");
                }
            }
        }).on('mouseout', function () { return common_1.ToolTip.hide(); });
        group.exit().remove();
    };
    default_1.prototype.update = function () {
        var _this = this;
        switch (this.type) {
            case 'line':
                this.updateLine();
                break;
            case 'area':
                this.updateArea();
                break;
            case 'bar':
                this.updateBar();
                break;
            case 'linebar':
                this.updateLine();
                this.updateBar();
                break;
        }
        this.SVG.select('g._x_axis').call(d3.axisBottom(this.widthScale).ticks(this.DATA.length > 7 ? 7 : this.DATA.length).tickSize(1).tickFormat(function (d) {
            if (_this.DATA.length <= d) {
                return '';
            }
            return _this.DATA[d]['label'];
        }));
        if (this.showYAxis) {
            this.SVG.select('g._y_axis').call(d3.axisLeft(this.heightScale).ticks(4).tickSize(1).tickFormat(function (e) { return _this.FormatValue(e); }));
        }
    };
    return default_1;
}(D3Chart_1.default));
exports.default = default_1;
